blob: af33cbc0ac1c838c2c3dae5520ac6e9430bac174 [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.
288 private static final String KEY_MIN_FUTURITY = "min_futurity";
289 private static final String KEY_MIN_INTERVAL = "min_interval";
Christopher Tate22e919d2018-02-16 16:16:50 -0800290 private static final String KEY_MAX_INTERVAL = "max_interval";
Dianne Hackborna750a632015-06-16 17:18:23 -0700291 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
292 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
293 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
294 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700295 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700296
Suprabh Shukla75edab12018-01-29 14:09:06 -0800297 // Keys for specifying throttling delay based on app standby bucketing
298 private final String[] KEYS_APP_STANDBY_DELAY = {
299 "standby_active_delay",
300 "standby_working_delay",
301 "standby_frequent_delay",
302 "standby_rare_delay",
303 "standby_never_delay",
304 };
305
Dianne Hackborna750a632015-06-16 17:18:23 -0700306 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
307 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800308 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700309 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700310 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700311 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700312 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800313 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
314 0, // Active
315 6 * 60_000, // Working
316 30 * 60_000, // Frequent
317 2 * 60 * 60_000, // Rare
318 10 * 24 * 60 * 60_000 // Never
319 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700320
Dianne Hackborna750a632015-06-16 17:18:23 -0700321 // Minimum futurity of a new alarm
322 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
323
324 // Minimum alarm recurrence interval
325 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
326
Christopher Tate22e919d2018-02-16 16:16:50 -0800327 // Maximum alarm recurrence interval
328 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
329
Dianne Hackborna750a632015-06-16 17:18:23 -0700330 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
331 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
332
333 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
334 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
335
336 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
337 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
338 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
339
Christopher Tate14a7bb02015-10-01 10:24:31 -0700340 // Direct alarm listener callback timeout
341 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
342
Suprabh Shukla75edab12018-01-29 14:09:06 -0800343 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
344
Dianne Hackborna750a632015-06-16 17:18:23 -0700345 private ContentResolver mResolver;
346 private final KeyValueListParser mParser = new KeyValueListParser(',');
347 private long mLastAllowWhileIdleWhitelistDuration = -1;
348
349 public Constants(Handler handler) {
350 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700351 updateAllowWhileIdleWhitelistDurationLocked();
352 }
353
354 public void start(ContentResolver resolver) {
355 mResolver = resolver;
356 mResolver.registerContentObserver(Settings.Global.getUriFor(
357 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
358 updateConstants();
359 }
360
Dianne Hackborna750a632015-06-16 17:18:23 -0700361 public void updateAllowWhileIdleWhitelistDurationLocked() {
362 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
363 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
364 BroadcastOptions opts = BroadcastOptions.makeBasic();
365 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
366 mIdleOptions = opts.toBundle();
367 }
368 }
369
370 @Override
371 public void onChange(boolean selfChange, Uri uri) {
372 updateConstants();
373 }
374
375 private void updateConstants() {
376 synchronized (mLock) {
377 try {
378 mParser.setString(Settings.Global.getString(mResolver,
379 Settings.Global.ALARM_MANAGER_CONSTANTS));
380 } catch (IllegalArgumentException e) {
381 // Failed to parse the settings string, log this and move on
382 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800383 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700384 }
385
386 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
387 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800388 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700389 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
390 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
391 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
392 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
393 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
394 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
395 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700396 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
397 DEFAULT_LISTENER_TIMEOUT);
Christopher Tatef2159712018-03-27 16:04:14 -0700398 APP_STANDBY_MIN_DELAYS[ACTIVE_INDEX] = mParser.getDurationMillis(
399 KEYS_APP_STANDBY_DELAY[ACTIVE_INDEX],
400 DEFAULT_APP_STANDBY_DELAYS[ACTIVE_INDEX]);
401 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800402 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
403 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
404 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700405 updateAllowWhileIdleWhitelistDurationLocked();
406 }
407 }
408
409 void dump(PrintWriter pw) {
410 pw.println(" Settings:");
411
412 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
413 TimeUtils.formatDuration(MIN_FUTURITY, pw);
414 pw.println();
415
416 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
417 TimeUtils.formatDuration(MIN_INTERVAL, pw);
418 pw.println();
419
Christopher Tate22e919d2018-02-16 16:16:50 -0800420 pw.print(" "); pw.print(KEY_MAX_INTERVAL); pw.print("=");
421 TimeUtils.formatDuration(MAX_INTERVAL, pw);
422 pw.println();
423
Christopher Tate14a7bb02015-10-01 10:24:31 -0700424 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
425 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
426 pw.println();
427
Dianne Hackborna750a632015-06-16 17:18:23 -0700428 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
429 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
430 pw.println();
431
432 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
433 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
434 pw.println();
435
436 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
437 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
438 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800439
440 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
441 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
442 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
443 pw.println();
444 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700445 }
Kweku Adams61e03292017-10-19 14:27:12 -0700446
447 void dumpProto(ProtoOutputStream proto, long fieldId) {
448 final long token = proto.start(fieldId);
449
450 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
451 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800452 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700453 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
454 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
455 ALLOW_WHILE_IDLE_SHORT_TIME);
456 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
457 ALLOW_WHILE_IDLE_LONG_TIME);
458 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
459 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
460
461 proto.end(token);
462 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700463 }
464
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700465 Constants mConstants;
Dianne Hackborna750a632015-06-16 17:18:23 -0700466
Christopher Tate1590f1e2014-10-02 17:27:57 -0700467 // Alarm delivery ordering bookkeeping
468 static final int PRIO_TICK = 0;
469 static final int PRIO_WAKEUP = 1;
470 static final int PRIO_NORMAL = 2;
471
Dianne Hackborna750a632015-06-16 17:18:23 -0700472 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700473 int seq;
474 int priority;
475
476 PriorityClass() {
477 seq = mCurrentSeq - 1;
478 priority = PRIO_NORMAL;
479 }
480 }
481
Dianne Hackborna750a632015-06-16 17:18:23 -0700482 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700483 int mCurrentSeq = 0;
484
Dianne Hackborna750a632015-06-16 17:18:23 -0700485 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700486 public long when;
487 public int uid;
488 public String action;
489
490 public WakeupEvent(long theTime, int theUid, String theAction) {
491 when = theTime;
492 uid = theUid;
493 action = theAction;
494 }
495 }
496
Adam Lesinski182f73f2013-12-05 16:48:06 -0800497 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
498 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700499
Adrian Roosc42a1e12014-07-07 23:35:53 +0200500 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700501 long start; // These endpoints are always in ELAPSED
502 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700503 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700504
505 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
506
507 Batch() {
508 start = 0;
509 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700510 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700511 }
512
513 Batch(Alarm seed) {
514 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800515 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700516 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700517 alarms.add(seed);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700518 if (seed.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700519 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800520 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700521 }
522
523 int size() {
524 return alarms.size();
525 }
526
527 Alarm get(int index) {
528 return alarms.get(index);
529 }
530
531 boolean canHold(long whenElapsed, long maxWhen) {
532 return (end >= whenElapsed) && (start <= maxWhen);
533 }
534
535 boolean add(Alarm alarm) {
536 boolean newStart = false;
537 // narrows the batch if necessary; presumes that canHold(alarm) is true
538 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
539 if (index < 0) {
540 index = 0 - index - 1;
541 }
542 alarms.add(index, alarm);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700543 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700544 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800545 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700546 if (DEBUG_BATCH) {
547 Slog.v(TAG, "Adding " + alarm + " to " + this);
548 }
549 if (alarm.whenElapsed > start) {
550 start = alarm.whenElapsed;
551 newStart = true;
552 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700553 if (alarm.maxWhenElapsed < end) {
554 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700555 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700556 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700557
558 if (DEBUG_BATCH) {
559 Slog.v(TAG, " => now " + this);
560 }
561 return newStart;
562 }
563
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800564 boolean remove(Alarm alarm) {
565 return remove(a -> (a == alarm));
566 }
567
Christopher Tate1d99c392017-12-07 16:54:04 -0800568 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700569 boolean didRemove = false;
570 long newStart = 0; // recalculate endpoints as we go
571 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700572 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700573 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700574 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800575 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700576 alarms.remove(i);
577 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200578 if (alarm.alarmClock != null) {
579 mNextAlarmClockMayChange = true;
580 }
Christopher Tatec8b7f432018-09-28 16:23:10 -0700581 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700582 mLastTickRemoved = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800583 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700584 } else {
585 if (alarm.whenElapsed > newStart) {
586 newStart = alarm.whenElapsed;
587 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700588 if (alarm.maxWhenElapsed < newEnd) {
589 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700590 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700591 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700592 i++;
593 }
594 }
595 if (didRemove) {
596 // commit the new batch bounds
597 start = newStart;
598 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700599 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700600 }
601 return didRemove;
602 }
603
Christopher Tatee0a22b32013-07-11 14:43:13 -0700604 boolean hasPackage(final String packageName) {
605 final int N = alarms.size();
606 for (int i = 0; i < N; i++) {
607 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700608 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700609 return true;
610 }
611 }
612 return false;
613 }
614
615 boolean hasWakeups() {
616 final int N = alarms.size();
617 for (int i = 0; i < N; i++) {
618 Alarm a = alarms.get(i);
619 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
620 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
621 return true;
622 }
623 }
624 return false;
625 }
626
627 @Override
628 public String toString() {
629 StringBuilder b = new StringBuilder(40);
630 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
631 b.append(" num="); b.append(size());
632 b.append(" start="); b.append(start);
633 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700634 if (flags != 0) {
635 b.append(" flgs=0x");
636 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700637 }
638 b.append('}');
639 return b.toString();
640 }
Kweku Adams61e03292017-10-19 14:27:12 -0700641
642 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
643 long nowRTC) {
644 final long token = proto.start(fieldId);
645
646 proto.write(BatchProto.START_REALTIME, start);
647 proto.write(BatchProto.END_REALTIME, end);
648 proto.write(BatchProto.FLAGS, flags);
649 for (Alarm a : alarms) {
650 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
651 }
652
653 proto.end(token);
654 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700655 }
656
657 static class BatchTimeOrder implements Comparator<Batch> {
658 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800659 long when1 = b1.start;
660 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800661 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700662 return 1;
663 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800664 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700665 return -1;
666 }
667 return 0;
668 }
669 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800670
671 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
672 @Override
673 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700674 // priority class trumps everything. TICK < WAKEUP < NORMAL
675 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
676 return -1;
677 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
678 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800679 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700680
681 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800682 if (lhs.whenElapsed < rhs.whenElapsed) {
683 return -1;
684 } else if (lhs.whenElapsed > rhs.whenElapsed) {
685 return 1;
686 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700687
688 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800689 return 0;
690 }
691 };
692
Christopher Tate1590f1e2014-10-02 17:27:57 -0700693 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
694 final int N = alarms.size();
695 for (int i = 0; i < N; i++) {
696 Alarm a = alarms.get(i);
697
698 final int alarmPrio;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700699 if (a.listener == mTimeTickTrigger) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700700 alarmPrio = PRIO_TICK;
701 } else if (a.wakeup) {
702 alarmPrio = PRIO_WAKEUP;
703 } else {
704 alarmPrio = PRIO_NORMAL;
705 }
706
707 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800708 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700709 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700710 if (packagePrio == null) {
711 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700712 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700713 }
714 a.priorityClass = packagePrio;
715
716 if (packagePrio.seq != mCurrentSeq) {
717 // first alarm we've seen in the current delivery generation from this package
718 packagePrio.priority = alarmPrio;
719 packagePrio.seq = mCurrentSeq;
720 } else {
721 // Multiple alarms from this package being delivered in this generation;
722 // bump the package's delivery class if it's warranted.
723 // TICK < WAKEUP < NORMAL
724 if (alarmPrio < packagePrio.priority) {
725 packagePrio.priority = alarmPrio;
726 }
727 }
728 }
729 }
730
Christopher Tatee0a22b32013-07-11 14:43:13 -0700731 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800732 static final long MIN_FUZZABLE_INTERVAL = 10000;
733 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700734 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
735
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700736 // 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 -0700737 // to run during this time are placed in mPendingWhileIdleAlarms
738 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700739 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700740 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700741
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700742 @VisibleForTesting
743 AlarmManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800744 super(context);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700745 mInjector = injector;
Jeff Brownb880d882014-02-10 19:47:07 -0800746 }
747
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700748 AlarmManagerService(Context context) {
749 this(context, new Injector(context));
750 }
751
752 private long convertToElapsed(long when, int type) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700753 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
754 if (isRtc) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700755 when -= mInjector.getCurrentTimeMillis() - mInjector.getElapsedRealtime();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700756 }
757 return when;
758 }
759
760 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
761 // calculate the end of our nominal delivery window for the alarm.
762 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
763 // Current heuristic: batchable window is 75% of either the recurrence interval
764 // [for a periodic alarm] or of the time from now to the desired delivery time,
765 // with a minimum delay/interval of 10 seconds, under which we will simply not
766 // defer the alarm.
767 long futurity = (interval == 0)
768 ? (triggerAtTime - now)
769 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700770 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700771 futurity = 0;
772 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800773 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700774 }
775
776 // returns true if the batch was added at the head
777 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
778 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
779 if (index < 0) {
780 index = 0 - index - 1;
781 }
782 list.add(index, newBatch);
783 return (index == 0);
784 }
785
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800786 private void insertAndBatchAlarmLocked(Alarm alarm) {
787 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
788 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
789
790 if (whichBatch < 0) {
791 addBatchLocked(mAlarmBatches, new Batch(alarm));
792 } else {
793 final Batch batch = mAlarmBatches.get(whichBatch);
794 if (batch.add(alarm)) {
795 // The start time of this batch advanced, so batch ordering may
796 // have just been broken. Move it to where it now belongs.
797 mAlarmBatches.remove(whichBatch);
798 addBatchLocked(mAlarmBatches, batch);
799 }
800 }
801 }
802
Christopher Tate385e4982013-07-23 18:22:29 -0700803 // Return the index of the matching batch, or -1 if none found.
804 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700805 final int N = mAlarmBatches.size();
806 for (int i = 0; i < N; i++) {
807 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700808 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700809 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700810 }
811 }
Christopher Tate385e4982013-07-23 18:22:29 -0700812 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700813 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800814 /** @return total count of the alarms in a set of alarm batches. */
815 static int getAlarmCount(ArrayList<Batch> batches) {
816 int ret = 0;
817
818 final int size = batches.size();
819 for (int i = 0; i < size; i++) {
820 ret += batches.get(i).size();
821 }
822 return ret;
823 }
824
825 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
826 if (alarms.size() == 0) {
827 return false;
828 }
829 final int batchSize = alarms.size();
830 for (int j = 0; j < batchSize; j++) {
Christopher Tatec8b7f432018-09-28 16:23:10 -0700831 if (alarms.get(j).listener == mTimeTickTrigger) {
Makoto Onuki5d93b832018-01-10 16:12:39 -0800832 return true;
833 }
834 }
835 return false;
836 }
837
838 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
839 final int numBatches = batches.size();
840 for (int i = 0; i < numBatches; i++) {
841 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
842 return true;
843 }
844 }
845 return false;
846 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700847
848 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
849 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700850 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700851 rebatchAllAlarmsLocked(true);
852 }
853 }
854
855 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800856 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800857 final int oldCount =
858 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
859 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
860 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
861
Christopher Tate4cb338d2013-07-26 13:11:31 -0700862 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
863 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700864 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700865 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate4cb338d2013-07-26 13:11:31 -0700866 final int oldBatches = oldSet.size();
867 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
868 Batch batch = oldSet.get(batchNum);
869 final int N = batch.size();
870 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700871 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700872 }
873 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700874 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
875 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
876 + " to " + mPendingIdleUntil);
877 if (mPendingIdleUntil == null) {
878 // Somehow we lost this... we need to restore all of the pending alarms.
879 restorePendingWhileIdleAlarmsLocked();
880 }
881 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800882 final int newCount =
883 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
884 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
885 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
886
887 if (oldCount != newCount) {
888 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
889 }
890 if (oldHasTick != newHasTick) {
891 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
892 }
893
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700894 rescheduleKernelAlarmsLocked();
895 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800896 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700897 }
898
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800899 /**
900 * Re-orders the alarm batches based on newly evaluated send times based on the current
901 * app-standby buckets
902 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
903 * null indicates all
904 * @return True if there was any reordering done to the current list.
905 */
906 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
907 final long start = mStatLogger.getTime();
908 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
909
910 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
911 final Batch batch = mAlarmBatches.get(batchIndex);
912 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
913 final Alarm alarm = batch.get(alarmIndex);
914 final Pair<String, Integer> packageUser =
915 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
916 if (targetPackages != null && !targetPackages.contains(packageUser)) {
917 continue;
918 }
919 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
920 batch.remove(alarm);
921 rescheduledAlarms.add(alarm);
922 }
923 }
924 if (batch.size() == 0) {
925 mAlarmBatches.remove(batchIndex);
926 }
927 }
928 for (int i = 0; i < rescheduledAlarms.size(); i++) {
929 final Alarm a = rescheduledAlarms.get(i);
930 insertAndBatchAlarmLocked(a);
931 }
932
933 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
934 return rescheduledAlarms.size() > 0;
935 }
936
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700937 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
938 a.when = a.origWhen;
939 long whenElapsed = convertToElapsed(a.when, a.type);
940 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700941 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700942 // Exact
943 maxElapsed = whenElapsed;
944 } else {
945 // Not exact. Preserve any explicit window, otherwise recalculate
946 // the window based on the alarm's new futurity. Note that this
947 // reflects a policy of preferring timely to deferred delivery.
948 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -0800949 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700950 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
951 }
952 a.whenElapsed = whenElapsed;
953 a.maxWhenElapsed = maxElapsed;
954 setImplLocked(a, true, doValidate);
955 }
956
Christopher Tate22e919d2018-02-16 16:16:50 -0800957 static long clampPositive(long val) {
958 return (val >= 0) ? val : Long.MAX_VALUE;
959 }
960
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700961 /**
962 * Sends alarms that were blocked due to user applied background restrictions - either because
963 * the user lifted those or the uid came to foreground.
964 *
965 * @param uid uid to filter on
966 * @param packageName package to filter on, or null for all packages in uid
967 */
968 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
969 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
970 if (alarmsForUid == null || alarmsForUid.size() == 0) {
971 return;
972 }
973 final ArrayList<Alarm> alarmsToDeliver;
974 if (packageName != null) {
975 if (DEBUG_BG_LIMIT) {
976 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
977 }
978 alarmsToDeliver = new ArrayList<>();
979 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
980 final Alarm a = alarmsForUid.get(i);
981 if (a.matches(packageName)) {
982 alarmsToDeliver.add(alarmsForUid.remove(i));
983 }
984 }
985 if (alarmsForUid.size() == 0) {
986 mPendingBackgroundAlarms.remove(uid);
987 }
988 } else {
989 if (DEBUG_BG_LIMIT) {
990 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
991 }
992 alarmsToDeliver = alarmsForUid;
993 mPendingBackgroundAlarms.remove(uid);
994 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700995 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700996 }
997
Makoto Onuki2206af32017-11-21 16:25:35 -0800998 /**
999 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
1000 * restricted.
1001 *
1002 * This is only called when the global "force all apps-standby" flag changes or when the
1003 * power save whitelist changes, so it's okay to be slow.
1004 */
1005 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001006 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -08001007
1008 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1009 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
1010
1011 if (alarmsToDeliver.size() > 0) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001012 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Makoto Onuki2206af32017-11-21 16:25:35 -08001013 }
1014 }
1015
1016 @VisibleForTesting
1017 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1018 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1019 Predicate<Alarm> isBackgroundRestricted) {
1020
1021 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1022 final int uid = pendingAlarms.keyAt(uidIndex);
1023 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1024
1025 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1026 final Alarm alarm = alarmsForUid.get(alarmIndex);
1027
1028 if (isBackgroundRestricted.test(alarm)) {
1029 continue;
1030 }
1031
1032 unrestrictedAlarms.add(alarm);
1033 alarmsForUid.remove(alarmIndex);
1034 }
1035
1036 if (alarmsForUid.size() == 0) {
1037 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001038 }
1039 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001040 }
1041
1042 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1043 final int N = alarms.size();
1044 boolean hasWakeup = false;
1045 for (int i = 0; i < N; i++) {
1046 final Alarm alarm = alarms.get(i);
1047 if (alarm.wakeup) {
1048 hasWakeup = true;
1049 }
1050 alarm.count = 1;
1051 // Recurring alarms may have passed several alarm intervals while the
1052 // alarm was kept pending. Send the appropriate trigger count.
1053 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001054 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001055 // Also schedule its next recurrence
1056 final long delta = alarm.count * alarm.repeatInterval;
1057 final long nextElapsed = alarm.whenElapsed + delta;
1058 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1059 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1060 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1061 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1062 // Kernel alarms will be rescheduled as needed in setImplLocked
1063 }
1064 }
1065 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1066 // No need to wakeup for non wakeup alarms
1067 if (mPendingNonWakeupAlarms.size() == 0) {
1068 mStartCurrentDelayTime = nowELAPSED;
1069 mNextNonWakeupDeliveryTime = nowELAPSED
1070 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1071 }
1072 mPendingNonWakeupAlarms.addAll(alarms);
1073 mNumDelayedAlarms += alarms.size();
1074 } else {
1075 if (DEBUG_BG_LIMIT) {
1076 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1077 }
1078 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1079 if (mPendingNonWakeupAlarms.size() > 0) {
1080 alarms.addAll(mPendingNonWakeupAlarms);
1081 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1082 mTotalDelayTime += thisDelayTime;
1083 if (mMaxDelayTime < thisDelayTime) {
1084 mMaxDelayTime = thisDelayTime;
1085 }
1086 mPendingNonWakeupAlarms.clear();
1087 }
1088 calculateDeliveryPriorities(alarms);
1089 Collections.sort(alarms, mAlarmDispatchComparator);
1090 deliverAlarmsLocked(alarms, nowELAPSED);
1091 }
1092 }
1093
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001094 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001095 if (RECORD_DEVICE_IDLE_ALARMS) {
1096 IdleDispatchEntry ent = new IdleDispatchEntry();
1097 ent.uid = 0;
1098 ent.pkg = "FINISH IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001099 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001100 mAllowWhileIdleDispatches.add(ent);
1101 }
1102
Dianne Hackborn35d54032015-04-23 10:30:43 -07001103 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001104 if (mPendingWhileIdleAlarms.size() > 0) {
1105 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1106 mPendingWhileIdleAlarms = new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001107 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001108 for (int i=alarms.size() - 1; i >= 0; i--) {
1109 Alarm a = alarms.get(i);
1110 reAddAlarmLocked(a, nowElapsed, false);
1111 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001112 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001113
1114 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001115 rescheduleKernelAlarmsLocked();
1116 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001117
1118 // And send a TIME_TICK right now, since it is important to get the UI updated.
Christopher Tatec8b7f432018-09-28 16:23:10 -07001119 mHandler.post(() -> getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001120 }
1121
Christopher Tate14a7bb02015-10-01 10:24:31 -07001122 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001123 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001124 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001125 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001126 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001127 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001128 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001129 final BroadcastStats mBroadcastStats;
1130 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001131 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001132
Christopher Tate14a7bb02015-10-01 10:24:31 -07001133 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1134 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1135 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001136 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001137 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001138 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001139 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001140 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001141 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001142 mBroadcastStats = (pendingIntent != null)
1143 ? service.getStatsLocked(pendingIntent)
1144 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001145 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001146 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001147 fs = new FilterStats(mBroadcastStats, mTag);
1148 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001149 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001150 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001151 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001152 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001153 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001154
1155 @Override
1156 public String toString() {
1157 return "InFlight{"
1158 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001159 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001160 + ", workSource=" + mWorkSource
1161 + ", uid=" + mUid
1162 + ", tag=" + mTag
1163 + ", broadcastStats=" + mBroadcastStats
1164 + ", filterStats=" + mFilterStats
1165 + ", alarmType=" + mAlarmType
1166 + "}";
1167 }
Kweku Adams61e03292017-10-19 14:27:12 -07001168
1169 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1170 final long token = proto.start(fieldId);
1171
1172 proto.write(InFlightProto.UID, mUid);
1173 proto.write(InFlightProto.TAG, mTag);
1174 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1175 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1176 if (mPendingIntent != null) {
1177 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1178 }
1179 if (mBroadcastStats != null) {
1180 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1181 }
1182 if (mFilterStats != null) {
1183 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1184 }
1185 if (mWorkSource != null) {
1186 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1187 }
1188
1189 proto.end(token);
1190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001192
Adam Lesinski182f73f2013-12-05 16:48:06 -08001193 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001194 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001195 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001196
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001197 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001199 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 int numWakeup;
1201 long startTime;
1202 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001203
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001204 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001205 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001206 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001207 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001208
1209 @Override
1210 public String toString() {
1211 return "FilterStats{"
1212 + "tag=" + mTag
1213 + ", lastTime=" + lastTime
1214 + ", aggregateTime=" + aggregateTime
1215 + ", count=" + count
1216 + ", numWakeup=" + numWakeup
1217 + ", startTime=" + startTime
1218 + ", nesting=" + nesting
1219 + "}";
1220 }
Kweku Adams61e03292017-10-19 14:27:12 -07001221
1222 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1223 final long token = proto.start(fieldId);
1224
1225 proto.write(FilterStatsProto.TAG, mTag);
1226 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1227 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1228 proto.write(FilterStatsProto.COUNT, count);
1229 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1230 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1231 proto.write(FilterStatsProto.NESTING, nesting);
1232
1233 proto.end(token);
1234 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001235 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001236
Adam Lesinski182f73f2013-12-05 16:48:06 -08001237 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001238 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001239 final String mPackageName;
1240
1241 long aggregateTime;
1242 int count;
1243 int numWakeup;
1244 long startTime;
1245 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001246 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001247
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001248 BroadcastStats(int uid, String packageName) {
1249 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001250 mPackageName = packageName;
1251 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001252
1253 @Override
1254 public String toString() {
1255 return "BroadcastStats{"
1256 + "uid=" + mUid
1257 + ", packageName=" + mPackageName
1258 + ", aggregateTime=" + aggregateTime
1259 + ", count=" + count
1260 + ", numWakeup=" + numWakeup
1261 + ", startTime=" + startTime
1262 + ", nesting=" + nesting
1263 + "}";
1264 }
Kweku Adams61e03292017-10-19 14:27:12 -07001265
1266 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1267 final long token = proto.start(fieldId);
1268
1269 proto.write(BroadcastStatsProto.UID, mUid);
1270 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1271 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1272 proto.write(BroadcastStatsProto.COUNT, count);
1273 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1274 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1275 proto.write(BroadcastStatsProto.NESTING, nesting);
1276
1277 proto.end(token);
1278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001280
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001281 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1282 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001283
1284 int mNumDelayedAlarms = 0;
1285 long mTotalDelayTime = 0;
1286 long mMaxDelayTime = 0;
1287
Adam Lesinski182f73f2013-12-05 16:48:06 -08001288 @Override
1289 public void onStart() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001290 mInjector.init();
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001291
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001292 synchronized (mLock) {
1293 mHandler = new AlarmHandler(Looper.myLooper());
1294 mConstants = new Constants(mHandler);
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001295
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001296 mNextWakeup = mNextNonWakeup = 0;
1297
1298 // We have to set current TimeZone info to kernel
1299 // because kernel doesn't keep this after reboot
1300 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
1301
1302 // Also sure that we're booting with a halfway sensible current time
Christopher Tate247571462017-04-10 11:45:05 -07001303 final long systemBuildTime = Environment.getRootDirectory().lastModified();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001304 if (mInjector.getCurrentTimeMillis() < systemBuildTime) {
1305 Slog.i(TAG, "Current time only " + mInjector.getCurrentTimeMillis()
Christopher Tate247571462017-04-10 11:45:05 -07001306 + ", advancing to build time " + systemBuildTime);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001307 mInjector.setKernelTime(systemBuildTime);
Christopher Tate247571462017-04-10 11:45:05 -07001308 }
Christopher Tate247571462017-04-10 11:45:05 -07001309
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001310 // Determine SysUI's uid
1311 mSystemUiUid = mInjector.getSystemUiUid();
1312 if (mSystemUiUid <= 0) {
1313 Slog.wtf(TAG, "SysUI package not found!");
1314 }
1315 mWakeLock = mInjector.getAlarmWakeLock();
1316
Christopher Tatec8b7f432018-09-28 16:23:10 -07001317 mTimeTickIntent = new Intent(Intent.ACTION_TIME_TICK).addFlags(
1318 Intent.FLAG_RECEIVER_REGISTERED_ONLY
1319 | Intent.FLAG_RECEIVER_FOREGROUND
1320 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1321
1322 mTimeTickTrigger = new IAlarmListener.Stub() {
1323 @Override
1324 public void doAlarm(final IAlarmCompleteListener callback) throws RemoteException {
1325 if (DEBUG_BATCH) {
1326 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1327 }
1328
1329 // Via handler because dispatch invokes this within its lock. OnAlarmListener
1330 // takes care of this automatically, but we're using the direct internal
1331 // interface here rather than that client-side wrapper infrastructure.
1332 mHandler.post(() -> {
1333 getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL);
1334
1335 try {
1336 callback.alarmComplete(this);
1337 } catch (RemoteException e) { /* local method call */ }
1338 });
1339
1340 synchronized (mLock) {
1341 mLastTickReceived = mInjector.getCurrentTimeMillis();
1342 }
1343 mClockReceiver.scheduleTimeTickEvent();
1344 }
1345 };
1346
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001347 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
1348 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1349 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1350 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
1351 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
1352
1353 mClockReceiver = mInjector.getClockReceiver(this);
1354 new InteractiveStateReceiver();
1355 new UninstallReceiver();
1356
1357 if (mInjector.isAlarmDriverPresent()) {
1358 AlarmThread waitThread = new AlarmThread();
1359 waitThread.start();
Christopher Tatebb9cce52017-04-18 14:19:43 -07001360 } else {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001361 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
Christopher Tatebb9cce52017-04-18 14:19:43 -07001362 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001363
1364 try {
1365 ActivityManager.getService().registerUidObserver(new UidObserver(),
1366 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1367 | ActivityManager.UID_OBSERVER_ACTIVE,
1368 ActivityManager.PROCESS_STATE_UNKNOWN, null);
1369 } catch (RemoteException e) {
1370 // ignored; both services live in system_server
1371 }
Christopher Tatebb9cce52017-04-18 14:19:43 -07001372 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001373 publishLocalService(AlarmManagerInternal.class, new LocalService());
Adam Lesinski182f73f2013-12-05 16:48:06 -08001374 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001376
1377 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001378 public void onBootPhase(int phase) {
1379 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001380 synchronized (mLock) {
1381 mConstants.start(getContext().getContentResolver());
1382 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
1383 mLocalDeviceIdleController =
1384 LocalServices.getService(DeviceIdleController.LocalService.class);
1385 mUsageStatsManagerInternal =
1386 LocalServices.getService(UsageStatsManagerInternal.class);
1387 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001388
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001389 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1390 mAppStateTracker.addListener(mForceAppStandbyListener);
1391
1392 mClockReceiver.scheduleTimeTickEvent();
1393 mClockReceiver.scheduleDateChangedEvent();
1394 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001395 }
1396 }
1397
1398 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 protected void finalize() throws Throwable {
1400 try {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001401 mInjector.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 } finally {
1403 super.finalize();
1404 }
1405 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001406
mswest463f4c99d2018-02-01 10:13:10 -08001407 boolean setTimeImpl(long millis) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001408 if (!mInjector.isAlarmDriverPresent()) {
mswest463f4c99d2018-02-01 10:13:10 -08001409 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1410 return false;
1411 }
1412
1413 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001414 final long currentTimeMillis = mInjector.getCurrentTimeMillis();
1415 mInjector.setKernelTime(millis);
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001416 final TimeZone timeZone = TimeZone.getDefault();
1417 final int currentTzOffset = timeZone.getOffset(currentTimeMillis);
1418 final int newTzOffset = timeZone.getOffset(millis);
1419 if (currentTzOffset != newTzOffset) {
1420 Slog.i(TAG, "Timezone offset has changed, updating kernel timezone");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001421 mInjector.setKernelTimezone(-(newTzOffset / 60000));
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001422 }
1423 // The native implementation of setKernelTime can return -1 even when the kernel
1424 // time was set correctly, so assume setting kernel time was successful and always
1425 // return true.
1426 return true;
mswest463f4c99d2018-02-01 10:13:10 -08001427 }
1428 }
1429
Adam Lesinski182f73f2013-12-05 16:48:06 -08001430 void setTimeZoneImpl(String tz) {
1431 if (TextUtils.isEmpty(tz)) {
1432 return;
David Christieebe51fc2013-07-26 13:23:29 -07001433 }
1434
Adam Lesinski182f73f2013-12-05 16:48:06 -08001435 TimeZone zone = TimeZone.getTimeZone(tz);
1436 // Prevent reentrant calls from stepping on each other when writing
1437 // the time zone property
1438 boolean timeZoneWasChanged = false;
1439 synchronized (this) {
1440 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1441 if (current == null || !current.equals(zone.getID())) {
1442 if (localLOGV) {
1443 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1444 }
1445 timeZoneWasChanged = true;
1446 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1447 }
1448
1449 // Update the kernel timezone information
1450 // Kernel tracks time offsets as 'minutes west of GMT'
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001451 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
1452 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001453 }
1454
1455 TimeZone.setDefault(null);
1456
1457 if (timeZoneWasChanged) {
1458 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001459 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001460 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001461 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001462 intent.putExtra("time-zone", zone.getID());
1463 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001466
Christopher Tatec8b7f432018-09-28 16:23:10 -07001467 void removeImpl(PendingIntent operation, IAlarmListener listener) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001468 synchronized (mLock) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07001469 removeLocked(operation, listener);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001470 }
1471 }
1472
1473 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001474 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1475 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1476 int callingUid, String callingPackage) {
1477 // must be *either* PendingIntent or AlarmReceiver, but not both
1478 if ((operation == null && directReceiver == null)
1479 || (operation != null && directReceiver != null)) {
1480 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1481 // NB: previous releases failed silently here, so we are continuing to do the same
1482 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 return;
1484 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001485
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001486 // Sanity check the window length. This will catch people mistakenly
1487 // trying to pass an end-of-window timestamp rather than a duration.
1488 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1489 Slog.w(TAG, "Window length " + windowLength
1490 + "ms suspiciously long; limiting to 1 hour");
1491 windowLength = AlarmManager.INTERVAL_HOUR;
1492 }
1493
Christopher Tate498c6cb2014-11-17 16:09:27 -08001494 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001495 // seconds when the API expects milliseconds, or apps trying shenanigans
1496 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001497 final long minInterval = mConstants.MIN_INTERVAL;
1498 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001499 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001500 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001501 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001502 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001503 } else if (interval > mConstants.MAX_INTERVAL) {
1504 Slog.w(TAG, "Suspiciously long interval " + interval
1505 + " millis; clamping");
1506 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001507 }
1508
Christopher Tatee0a22b32013-07-11 14:43:13 -07001509 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1510 throw new IllegalArgumentException("Invalid alarm type " + type);
1511 }
1512
Christopher Tate5f221e82013-07-30 17:13:15 -07001513 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001514 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001515 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001516 + " pid=" + what);
1517 triggerAtTime = 0;
1518 }
1519
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001520 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001521 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1522 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001523 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001524 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1525
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001526 final long maxElapsed;
1527 if (windowLength == AlarmManager.WINDOW_EXACT) {
1528 maxElapsed = triggerElapsed;
1529 } else if (windowLength < 0) {
1530 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001531 // Fix this window in place, so that as time approaches we don't collapse it.
1532 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001533 } else {
1534 maxElapsed = triggerElapsed + windowLength;
1535 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001538 if (DEBUG_BATCH) {
1539 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001540 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001541 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001542 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001544 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001545 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1546 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549
Christopher Tate3e04b472013-10-21 17:51:31 -07001550 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001551 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1552 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1553 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001554 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001555 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1556 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001557 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001558 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001559 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1560 + " -- package not allowed to start");
1561 return;
1562 }
1563 } catch (RemoteException e) {
1564 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001565 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001566 setImplLocked(a, false, doValidate);
1567 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001568
Christopher Tatef2159712018-03-27 16:04:14 -07001569 /**
1570 * Return the minimum time that should elapse before an app in the specified bucket
1571 * can receive alarms again
1572 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001573 @VisibleForTesting
1574 long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001575 // UsageStats bucket values are treated as floors of their behavioral range.
1576 // In other words, a bucket value between WORKING and ACTIVE is treated as
1577 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1578 // values.
1579 final int index;
1580
1581 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1582 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1583 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1584 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1585 else index = ACTIVE_INDEX;
1586
1587 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001588 }
1589
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001590 /**
1591 * Adjusts the alarm delivery time based on the current app standby bucket.
1592 * @param alarm The alarm to adjust
1593 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001594 */
1595 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001596 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001597 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001598 }
1599 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001600 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001601 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001602 alarm.whenElapsed = alarm.expectedWhenElapsed;
1603 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1604 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001605 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001606 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001607 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001608 final long oldWhenElapsed = alarm.whenElapsed;
1609 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1610
Suprabh Shukla75edab12018-01-29 14:09:06 -08001611 final String sourcePackage = alarm.sourcePackage;
1612 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1613 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001614 sourcePackage, sourceUserId, mInjector.getElapsedRealtime());
Suprabh Shukla75edab12018-01-29 14:09:06 -08001615
1616 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1617 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1618 if (lastElapsed > 0) {
1619 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001620 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001621 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001622 } else {
1623 // app is now eligible to run alarms at the originally requested window.
1624 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001625 alarm.whenElapsed = alarm.expectedWhenElapsed;
1626 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001627 }
1628 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001629 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001630 }
1631
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001632 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1633 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001634 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001635 // The caller has given the time they want this to happen at, however we need
1636 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001637 // bring us out of idle at an earlier time.
1638 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001639 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001640 }
1641 // Add fuzz to make the alarm go off some time before the actual desired time.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001642 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001643 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001644 if (fuzz > 0) {
1645 if (mRandom == null) {
1646 mRandom = new Random();
1647 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001648 final int delta = mRandom.nextInt(fuzz);
1649 a.whenElapsed -= delta;
1650 if (false) {
1651 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1652 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1653 Slog.d(TAG, "Applied fuzz: " + fuzz);
1654 Slog.d(TAG, "Final delta: " + delta);
1655 Slog.d(TAG, "Final when: " + a.whenElapsed);
1656 }
1657 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001658 }
1659
1660 } else if (mPendingIdleUntil != null) {
1661 // We currently have an idle until alarm scheduled; if the new alarm has
1662 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001663 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1664 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1665 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001666 == 0) {
1667 mPendingWhileIdleAlarms.add(a);
1668 return;
1669 }
1670 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001671 if (RECORD_DEVICE_IDLE_ALARMS) {
1672 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1673 IdleDispatchEntry ent = new IdleDispatchEntry();
1674 ent.uid = a.uid;
1675 ent.pkg = a.operation.getCreatorPackage();
1676 ent.tag = a.operation.getTag("");
1677 ent.op = "SET";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001678 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001679 ent.argRealtime = a.whenElapsed;
1680 mAllowWhileIdleDispatches.add(ent);
1681 }
1682 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001683 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001684 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001686 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001687 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001688 }
1689
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001690 boolean needRebatch = false;
1691
1692 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001693 if (RECORD_DEVICE_IDLE_ALARMS) {
1694 if (mPendingIdleUntil == null) {
1695 IdleDispatchEntry ent = new IdleDispatchEntry();
1696 ent.uid = 0;
1697 ent.pkg = "START IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001698 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001699 mAllowWhileIdleDispatches.add(ent);
1700 }
1701 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001702 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1703 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1704 + " to " + a);
1705 }
1706
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001707 mPendingIdleUntil = a;
1708 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001709 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1710 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1711 mNextWakeFromIdle = a;
1712 // If this wake from idle is earlier than whatever was previously scheduled,
1713 // and we are currently idling, then we need to rebatch alarms in case the idle
1714 // until time needs to be updated.
1715 if (mPendingIdleUntil != null) {
1716 needRebatch = true;
1717 }
1718 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001719 }
1720
1721 if (!rebatching) {
1722 if (DEBUG_VALIDATE) {
1723 if (doValidate && !validateConsistencyLocked()) {
1724 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1725 + " when(hex)=" + Long.toHexString(a.when)
1726 + " whenElapsed=" + a.whenElapsed
1727 + " maxWhenElapsed=" + a.maxWhenElapsed
1728 + " interval=" + a.repeatInterval + " op=" + a.operation
1729 + " flags=0x" + Integer.toHexString(a.flags));
1730 rebatchAllAlarmsLocked(false);
1731 needRebatch = false;
1732 }
1733 }
1734
1735 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001736 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001737 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001738
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001739 rescheduleKernelAlarmsLocked();
1740 updateNextAlarmClockLocked();
1741 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001742 }
1743
Christopher Tate1d99c392017-12-07 16:54:04 -08001744 /**
1745 * System-process internal API
1746 */
1747 private final class LocalService implements AlarmManagerInternal {
1748 @Override
1749 public void removeAlarmsForUid(int uid) {
1750 synchronized (mLock) {
1751 removeLocked(uid);
1752 }
1753 }
1754 }
1755
1756 /**
1757 * Public-facing binder interface
1758 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001759 private final IBinder mService = new IAlarmManager.Stub() {
1760 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001761 public void set(String callingPackage,
1762 int type, long triggerAtTime, long windowLength, long interval, int flags,
1763 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1764 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001765 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001766
1767 // make sure the caller is not lying about which package should be blamed for
1768 // wakelock time spent in alarm delivery
1769 mAppOps.checkPackage(callingUid, callingPackage);
1770
1771 // Repeating alarms must use PendingIntent, not direct listener
1772 if (interval != 0) {
1773 if (directReceiver != null) {
1774 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1775 }
1776 }
1777
Adam Lesinski182f73f2013-12-05 16:48:06 -08001778 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001779 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001780 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001781 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001782 }
1783
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001784 // No incoming callers can request either WAKE_FROM_IDLE or
1785 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1786 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1787 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1788
1789 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1790 // manager when to come out of idle mode, which is only for DeviceIdleController.
1791 if (callingUid != Process.SYSTEM_UID) {
1792 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1793 }
1794
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001795 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001796 if (windowLength == AlarmManager.WINDOW_EXACT) {
1797 flags |= AlarmManager.FLAG_STANDALONE;
1798 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001799
1800 // If this alarm is for an alarm clock, then it must be standalone and we will
1801 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001802 if (alarmClock != null) {
1803 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001804
1805 // If the caller is a core system component or on the user's whitelist, and not calling
1806 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1807 // This means we will allow these alarms to go off as normal even while idle, with no
1808 // timing restrictions.
1809 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001810 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001811 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001812 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001813 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1814 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001815 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001816
Christopher Tate14a7bb02015-10-01 10:24:31 -07001817 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1818 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001819 }
Christopher Tate89779822012-08-31 14:40:03 -07001820
Adam Lesinski182f73f2013-12-05 16:48:06 -08001821 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001822 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001823 getContext().enforceCallingOrSelfPermission(
1824 "android.permission.SET_TIME",
1825 "setTime");
1826
mswest463f4c99d2018-02-01 10:13:10 -08001827 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001829
1830 @Override
1831 public void setTimeZone(String tz) {
1832 getContext().enforceCallingOrSelfPermission(
1833 "android.permission.SET_TIME_ZONE",
1834 "setTimeZone");
1835
1836 final long oldId = Binder.clearCallingIdentity();
1837 try {
1838 setTimeZoneImpl(tz);
1839 } finally {
1840 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 }
1842 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001843
Adam Lesinski182f73f2013-12-05 16:48:06 -08001844 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001845 public void remove(PendingIntent operation, IAlarmListener listener) {
1846 if (operation == null && listener == null) {
1847 Slog.w(TAG, "remove() with no intent or listener");
1848 return;
1849 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001850
Christopher Tate14a7bb02015-10-01 10:24:31 -07001851 synchronized (mLock) {
1852 removeLocked(operation, listener);
1853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001855
Adam Lesinski182f73f2013-12-05 16:48:06 -08001856 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001857 public long getNextWakeFromIdleTime() {
1858 return getNextWakeFromIdleTimeImpl();
1859 }
1860
1861 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001862 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001863 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1864 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1865 "getNextAlarmClock", null);
1866
1867 return getNextAlarmClockImpl(userId);
1868 }
1869
1870 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001871 public long currentNetworkTimeMillis() {
1872 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1873 if (time.hasCache()) {
1874 return time.currentTimeMillis();
1875 } else {
1876 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1877 }
1878 }
1879
1880 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001881 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001882 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001883
1884 if (args.length > 0 && "--proto".equals(args[0])) {
1885 dumpProto(fd);
1886 } else {
1887 dumpImpl(pw);
1888 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001889 }
mswest463f4c99d2018-02-01 10:13:10 -08001890
1891 @Override
1892 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1893 FileDescriptor err, String[] args, ShellCallback callback,
1894 ResultReceiver resultReceiver) {
1895 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
1896 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001897 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001898
Adam Lesinski182f73f2013-12-05 16:48:06 -08001899 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 synchronized (mLock) {
1901 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001902 mConstants.dump(pw);
1903 pw.println();
1904
Makoto Onukie4918212018-02-06 11:30:15 -08001905 if (mAppStateTracker != null) {
1906 mAppStateTracker.dump(pw, " ");
1907 pw.println();
1908 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001909
Suprabh Shukla75edab12018-01-29 14:09:06 -08001910 pw.println(" App Standby Parole: " + mAppStandbyParole);
1911 pw.println();
1912
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001913 final long nowELAPSED = mInjector.getElapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001914 final long nowUPTIME = SystemClock.uptimeMillis();
Christopher Tatec8b7f432018-09-28 16:23:10 -07001915 final long nowRTC = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001916 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001917
Dianne Hackborna750a632015-06-16 17:18:23 -07001918 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001919 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001920 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001921 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001922 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001923 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001924 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
Christopher Tate12cf0b62018-01-05 18:40:14 -08001925 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1926 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001927 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1928 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001929
Christopher Tatec8b7f432018-09-28 16:23:10 -07001930 if (RECORD_ALARMS_IN_HISTORY) {
1931 pw.println();
1932 pw.println(" Recent TIME_TICK history:");
1933 int i = mNextTickHistory;
1934 do {
1935 i--;
1936 if (i < 0) i = TICK_HISTORY_DEPTH - 1;
1937 final long time = mTickHistory[i];
1938 pw.print(" ");
1939 pw.println((time > 0)
1940 ? sdf.format(new Date(nowRTC - (nowELAPSED - time)))
1941 : "-");
1942 } while (i != mNextTickHistory);
1943 pw.println();
1944 }
1945
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001946 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
1947 if (ssm != null) {
1948 pw.println();
1949 pw.print(" RuntimeStarted=");
1950 pw.print(sdf.format(
1951 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
1952 if (ssm.isRuntimeRestarted()) {
1953 pw.print(" (Runtime restarted)");
1954 }
1955 pw.println();
1956 pw.print(" Runtime uptime (elapsed): ");
1957 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
1958 pw.println();
1959 pw.print(" Runtime uptime (uptime): ");
1960 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
1961 pw.println();
1962 }
1963
Dianne Hackbornc3527222015-05-13 14:03:20 -07001964 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001965 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001966 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001967 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1968 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001969 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001970 pw.print(" Max wakeup delay: ");
1971 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1972 pw.println();
1973 pw.print(" Time since last dispatch: ");
1974 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1975 pw.println();
1976 pw.print(" Next non-wakeup delivery time: ");
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001977 TimeUtils.formatDuration(mNextNonWakeupDeliveryTime, nowELAPSED, pw);
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001978 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001979
1980 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1981 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001982 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001983 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001984 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001985 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001986 pw.print(" set at "); TimeUtils.formatDuration(mNextNonWakeUpSetAt, nowELAPSED, pw);
1987 pw.println();
Christopher Tate8b98ade2018-02-09 11:13:19 -08001988 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1989 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001990 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001991 pw.print(" set at "); TimeUtils.formatDuration(mNextWakeUpSetAt, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001992 pw.println();
Suprabh Shukla2324e982018-06-05 21:06:22 -07001993
1994 pw.print(" Next kernel non-wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001995 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07001996 pw.println();
1997 pw.print(" Next kernel wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001998 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07001999 pw.println();
2000
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002001 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002002 pw.print(" = "); pw.println(mLastWakeup);
2003 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
2004 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07002005 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002006
John Spurlock604a5ee2015-06-01 12:27:22 -04002007 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002008 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04002009 final TreeSet<Integer> users = new TreeSet<>();
2010 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
2011 users.add(mNextAlarmClockForUser.keyAt(i));
2012 }
2013 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
2014 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2015 }
2016 for (int user : users) {
2017 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2018 final long time = next != null ? next.getTriggerTime() : 0;
2019 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07002020 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04002021 pw.print(" pendingSend:"); pw.print(pendingSend);
2022 pw.print(" time:"); pw.print(time);
2023 if (time > 0) {
2024 pw.print(" = "); pw.print(sdf.format(new Date(time)));
2025 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
2026 }
2027 pw.println();
2028 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002029 if (mAlarmBatches.size() > 0) {
2030 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002031 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07002032 pw.println(mAlarmBatches.size());
2033 for (Batch b : mAlarmBatches) {
2034 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07002035 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002038 pw.println();
2039 pw.println(" Pending user blocked background alarms: ");
2040 boolean blocked = false;
2041 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2042 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2043 if (blockedAlarms != null && blockedAlarms.size() > 0) {
2044 blocked = true;
2045 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
2046 }
2047 }
2048 if (!blocked) {
2049 pw.println(" none");
2050 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002051
Suprabh Shukla75edab12018-01-29 14:09:06 -08002052 pw.println(" mLastAlarmDeliveredForPackage:");
2053 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
2054 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
2055 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
2056 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
2057 pw.println();
2058 }
2059 pw.println();
2060
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002061 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002062 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002063 pw.println(" Idle mode state:");
2064 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002065 if (mPendingIdleUntil != null) {
2066 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002067 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002068 } else {
2069 pw.println("null");
2070 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002071 pw.println(" Pending alarms:");
2072 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002073 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002074 if (mNextWakeFromIdle != null) {
2075 pw.println();
2076 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002077 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002078 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002079
2080 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002081 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002082 if (mPendingNonWakeupAlarms.size() > 0) {
2083 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002084 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002085 } else {
2086 pw.println("(none)");
2087 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002088 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002089 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2090 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002091 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002092 pw.print(", max non-interactive time: ");
2093 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2094 pw.println();
2095
2096 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002097 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002098 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2099 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2100 pw.print(" Listener send count: "); pw.println(mListenerCount);
2101 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002102 pw.println();
2103
Christopher Tate7f2a0352015-12-08 10:24:33 -08002104 if (mInFlight.size() > 0) {
2105 pw.println("Outstanding deliveries:");
2106 for (int i = 0; i < mInFlight.size(); i++) {
2107 pw.print(" #"); pw.print(i); pw.print(": ");
2108 pw.println(mInFlight.get(i));
2109 }
2110 pw.println();
2111 }
2112
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002113 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002114 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002115 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002116 pw.print(" UID ");
2117 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2118 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002119 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002120 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2121 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2122
2123 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2124 pw.print(" Next allowed:");
2125 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2126 pw.print(" (");
2127 TimeUtils.formatDuration(minInterval, 0, pw);
2128 pw.print(")");
2129
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002130 pw.println();
2131 }
2132 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002133
2134 pw.print(" mUseAllowWhileIdleShortTime: [");
2135 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2136 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2137 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2138 pw.print(" ");
2139 }
2140 }
2141 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002142 pw.println();
2143
Dianne Hackborn81038902012-11-26 17:04:09 -08002144 if (mLog.dump(pw, " Recent problems", " ")) {
2145 pw.println();
2146 }
2147
2148 final FilterStats[] topFilters = new FilterStats[10];
2149 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2150 @Override
2151 public int compare(FilterStats lhs, FilterStats rhs) {
2152 if (lhs.aggregateTime < rhs.aggregateTime) {
2153 return 1;
2154 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2155 return -1;
2156 }
2157 return 0;
2158 }
2159 };
2160 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002161 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002162 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2163 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2164 for (int ip=0; ip<uidStats.size(); ip++) {
2165 BroadcastStats bs = uidStats.valueAt(ip);
2166 for (int is=0; is<bs.filterStats.size(); is++) {
2167 FilterStats fs = bs.filterStats.valueAt(is);
2168 int pos = len > 0
2169 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2170 if (pos < 0) {
2171 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002172 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002173 if (pos < topFilters.length) {
2174 int copylen = topFilters.length - pos - 1;
2175 if (copylen > 0) {
2176 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2177 }
2178 topFilters[pos] = fs;
2179 if (len < topFilters.length) {
2180 len++;
2181 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002182 }
2183 }
2184 }
2185 }
2186 if (len > 0) {
2187 pw.println(" Top Alarms:");
2188 for (int i=0; i<len; i++) {
2189 FilterStats fs = topFilters[i];
2190 pw.print(" ");
2191 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2192 TimeUtils.formatDuration(fs.aggregateTime, pw);
2193 pw.print(" running, "); pw.print(fs.numWakeup);
2194 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002195 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2196 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002197 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002198 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002199 pw.println();
2200 }
2201 }
2202
2203 pw.println(" ");
2204 pw.println(" Alarm Stats:");
2205 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002206 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2207 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2208 for (int ip=0; ip<uidStats.size(); ip++) {
2209 BroadcastStats bs = uidStats.valueAt(ip);
2210 pw.print(" ");
2211 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2212 UserHandle.formatUid(pw, bs.mUid);
2213 pw.print(":");
2214 pw.print(bs.mPackageName);
2215 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2216 pw.print(" running, "); pw.print(bs.numWakeup);
2217 pw.println(" wakeups:");
2218 tmpFilters.clear();
2219 for (int is=0; is<bs.filterStats.size(); is++) {
2220 tmpFilters.add(bs.filterStats.valueAt(is));
2221 }
2222 Collections.sort(tmpFilters, comparator);
2223 for (int i=0; i<tmpFilters.size(); i++) {
2224 FilterStats fs = tmpFilters.get(i);
2225 pw.print(" ");
2226 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2227 TimeUtils.formatDuration(fs.aggregateTime, pw);
2228 pw.print(" "); pw.print(fs.numWakeup);
2229 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002230 pw.print(" alarms, last ");
2231 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2232 pw.println(":");
2233 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002234 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002235 pw.println();
2236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 }
2238 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002239 pw.println();
2240 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002241
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002242 if (RECORD_DEVICE_IDLE_ALARMS) {
2243 pw.println();
2244 pw.println(" Allow while idle dispatches:");
2245 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2246 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2247 pw.print(" ");
2248 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2249 pw.print(": ");
2250 UserHandle.formatUid(pw, ent.uid);
2251 pw.print(":");
2252 pw.println(ent.pkg);
2253 if (ent.op != null) {
2254 pw.print(" ");
2255 pw.print(ent.op);
2256 pw.print(" / ");
2257 pw.print(ent.tag);
2258 if (ent.argRealtime != 0) {
2259 pw.print(" (");
2260 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2261 pw.print(")");
2262 }
2263 pw.println();
2264 }
2265 }
2266 }
2267
Christopher Tate18a75f12013-07-01 18:18:59 -07002268 if (WAKEUP_STATS) {
2269 pw.println();
2270 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002271 long last = -1;
2272 for (WakeupEvent event : mRecentWakeups) {
2273 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2274 pw.print('|');
2275 if (last < 0) {
2276 pw.print('0');
2277 } else {
2278 pw.print(event.when - last);
2279 }
2280 last = event.when;
2281 pw.print('|'); pw.print(event.uid);
2282 pw.print('|'); pw.print(event.action);
2283 pw.println();
2284 }
2285 pw.println();
2286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 }
2288 }
2289
Kweku Adams61e03292017-10-19 14:27:12 -07002290 void dumpProto(FileDescriptor fd) {
2291 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2292
2293 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002294 final long nowRTC = mInjector.getCurrentTimeMillis();
2295 final long nowElapsed = mInjector.getElapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002296 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2297 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2298 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002299 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002300 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002301 mLastTimeChangeRealtime);
2302
Yi Jin2b30f322018-02-20 15:41:47 -08002303 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002304
Makoto Onukie4918212018-02-06 11:30:15 -08002305 if (mAppStateTracker != null) {
2306 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002307 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002308 }
Kweku Adams61e03292017-10-19 14:27:12 -07002309
Yi Jin2b30f322018-02-20 15:41:47 -08002310 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002311 if (!mInteractive) {
2312 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002313 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002314 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002315 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002316 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002317 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002318 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002319 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002320 nowElapsed - mNextNonWakeupDeliveryTime);
2321 }
2322
Yi Jin2b30f322018-02-20 15:41:47 -08002323 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002324 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002325 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002326 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002327 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002328 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002329 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002330 nowElapsed - mNextWakeUpSetAt);
Yi Jin2b30f322018-02-20 15:41:47 -08002331 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002332
2333 final TreeSet<Integer> users = new TreeSet<>();
2334 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2335 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2336 users.add(mNextAlarmClockForUser.keyAt(i));
2337 }
2338 final int pendingSendNextAlarmClockChangedForUserSize =
2339 mPendingSendNextAlarmClockChangedForUser.size();
2340 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2341 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2342 }
2343 for (int user : users) {
2344 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2345 final long time = next != null ? next.getTriggerTime() : 0;
2346 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002347 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002348 proto.write(AlarmClockMetadataProto.USER, user);
2349 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2350 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2351 proto.end(aToken);
2352 }
2353 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002354 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002355 nowElapsed, nowRTC);
2356 }
2357 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2358 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2359 if (blockedAlarms != null) {
2360 for (Alarm a : blockedAlarms) {
2361 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002362 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002363 nowElapsed, nowRTC);
2364 }
2365 }
2366 }
2367 if (mPendingIdleUntil != null) {
2368 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002369 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002370 }
2371 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002372 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002373 nowElapsed, nowRTC);
2374 }
2375 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002376 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002377 nowElapsed, nowRTC);
2378 }
2379
2380 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002381 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002382 nowElapsed, nowRTC);
2383 }
2384
Yi Jin2b30f322018-02-20 15:41:47 -08002385 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2386 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2387 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2388 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002389 mNonInteractiveTime);
2390
Yi Jin2b30f322018-02-20 15:41:47 -08002391 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2392 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2393 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2394 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2395 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002396
2397 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002398 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002399 }
2400
Kweku Adams61e03292017-10-19 14:27:12 -07002401 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2402 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002403 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002404 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2405 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2406
Yi Jin2b30f322018-02-20 15:41:47 -08002407 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2408 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2409 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002410 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002411 proto.end(token);
2412 }
2413
Makoto Onukiadb50d82018-01-29 16:20:30 -08002414 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2415 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002416 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002417 mUseAllowWhileIdleShortTime.keyAt(i));
2418 }
2419 }
2420
Yi Jin2b30f322018-02-20 15:41:47 -08002421 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002422
2423 final FilterStats[] topFilters = new FilterStats[10];
2424 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2425 @Override
2426 public int compare(FilterStats lhs, FilterStats rhs) {
2427 if (lhs.aggregateTime < rhs.aggregateTime) {
2428 return 1;
2429 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2430 return -1;
2431 }
2432 return 0;
2433 }
2434 };
2435 int len = 0;
2436 // Get the top 10 FilterStats, ordered by aggregateTime.
2437 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2438 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2439 for (int ip = 0; ip < uidStats.size(); ++ip) {
2440 BroadcastStats bs = uidStats.valueAt(ip);
2441 for (int is = 0; is < bs.filterStats.size(); ++is) {
2442 FilterStats fs = bs.filterStats.valueAt(is);
2443 int pos = len > 0
2444 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2445 if (pos < 0) {
2446 pos = -pos - 1;
2447 }
2448 if (pos < topFilters.length) {
2449 int copylen = topFilters.length - pos - 1;
2450 if (copylen > 0) {
2451 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2452 }
2453 topFilters[pos] = fs;
2454 if (len < topFilters.length) {
2455 len++;
2456 }
2457 }
2458 }
2459 }
2460 }
2461 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002462 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002463 FilterStats fs = topFilters[i];
2464
Yi Jin2b30f322018-02-20 15:41:47 -08002465 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2466 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002467 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002468 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002469
2470 proto.end(token);
2471 }
2472
2473 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2474 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2475 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2476 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002477 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002478
2479 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002480 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002481
2482 // uidStats is an ArrayMap, which we can't sort.
2483 tmpFilters.clear();
2484 for (int is = 0; is < bs.filterStats.size(); ++is) {
2485 tmpFilters.add(bs.filterStats.valueAt(is));
2486 }
2487 Collections.sort(tmpFilters, comparator);
2488 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002489 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002490 }
2491
2492 proto.end(token);
2493 }
2494 }
2495
2496 if (RECORD_DEVICE_IDLE_ALARMS) {
2497 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2498 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2499 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002500 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002501
2502 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2503 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2504 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2505 proto.write(IdleDispatchEntryProto.OP, ent.op);
2506 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2507 ent.elapsedRealtime);
2508 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2509
2510 proto.end(token);
2511 }
2512 }
2513
2514 if (WAKEUP_STATS) {
2515 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002516 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002517 proto.write(WakeupEventProto.UID, event.uid);
2518 proto.write(WakeupEventProto.ACTION, event.action);
2519 proto.write(WakeupEventProto.WHEN, event.when);
2520 proto.end(token);
2521 }
2522 }
2523 }
2524
2525 proto.flush();
2526 }
2527
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002528 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002529 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2530 PrintWriter pw = new PrintWriter(bs);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002531 final long nowRTC = mInjector.getCurrentTimeMillis();
2532 final long nowELAPSED = mInjector.getElapsedRealtime();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002533 final int NZ = mAlarmBatches.size();
2534 for (int iz = 0; iz < NZ; iz++) {
2535 Batch bz = mAlarmBatches.get(iz);
2536 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002537 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002538 pw.flush();
2539 Slog.v(TAG, bs.toString());
2540 bs.reset();
2541 }
2542 }
2543
2544 private boolean validateConsistencyLocked() {
2545 if (DEBUG_VALIDATE) {
2546 long lastTime = Long.MIN_VALUE;
2547 final int N = mAlarmBatches.size();
2548 for (int i = 0; i < N; i++) {
2549 Batch b = mAlarmBatches.get(i);
2550 if (b.start >= lastTime) {
2551 // duplicate start times are okay because of standalone batches
2552 lastTime = b.start;
2553 } else {
2554 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002555 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2556 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002557 return false;
2558 }
2559 }
2560 }
2561 return true;
2562 }
2563
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002564 private Batch findFirstWakeupBatchLocked() {
2565 final int N = mAlarmBatches.size();
2566 for (int i = 0; i < N; i++) {
2567 Batch b = mAlarmBatches.get(i);
2568 if (b.hasWakeups()) {
2569 return b;
2570 }
2571 }
2572 return null;
2573 }
2574
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002575 long getNextWakeFromIdleTimeImpl() {
2576 synchronized (mLock) {
2577 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2578 }
2579 }
2580
2581 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002582 synchronized (mLock) {
2583 return mNextAlarmClockForUser.get(userId);
2584 }
2585 }
2586
2587 /**
2588 * Recomputes the next alarm clock for all users.
2589 */
2590 private void updateNextAlarmClockLocked() {
2591 if (!mNextAlarmClockMayChange) {
2592 return;
2593 }
2594 mNextAlarmClockMayChange = false;
2595
Jose Lima235510e2014-08-13 12:50:01 -07002596 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002597 nextForUser.clear();
2598
2599 final int N = mAlarmBatches.size();
2600 for (int i = 0; i < N; i++) {
2601 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2602 final int M = alarms.size();
2603
2604 for (int j = 0; j < M; j++) {
2605 Alarm a = alarms.get(j);
2606 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002607 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002608 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002609
2610 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002611 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002612 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002613 " for user " + userId);
2614 }
2615
2616 // Alarms and batches are sorted by time, no need to compare times here.
2617 if (nextForUser.get(userId) == null) {
2618 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002619 } else if (a.alarmClock.equals(current)
2620 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2621 // same/earlier time and it's the one we cited before, so stick with it
2622 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002623 }
2624 }
2625 }
2626 }
2627
2628 // Update mNextAlarmForUser with new values.
2629 final int NN = nextForUser.size();
2630 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002631 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002632 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002633 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002634 if (!newAlarm.equals(currentAlarm)) {
2635 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2636 }
2637 }
2638
2639 // Remove users without any alarm clocks scheduled.
2640 final int NNN = mNextAlarmClockForUser.size();
2641 for (int i = NNN - 1; i >= 0; i--) {
2642 int userId = mNextAlarmClockForUser.keyAt(i);
2643 if (nextForUser.get(userId) == null) {
2644 updateNextAlarmInfoForUserLocked(userId, null);
2645 }
2646 }
2647 }
2648
Jose Lima235510e2014-08-13 12:50:01 -07002649 private void updateNextAlarmInfoForUserLocked(int userId,
2650 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002651 if (alarmClock != null) {
2652 if (DEBUG_ALARM_CLOCK) {
2653 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002654 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002655 }
2656 mNextAlarmClockForUser.put(userId, alarmClock);
2657 } else {
2658 if (DEBUG_ALARM_CLOCK) {
2659 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2660 }
2661 mNextAlarmClockForUser.remove(userId);
2662 }
2663
2664 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2665 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2666 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2667 }
2668
2669 /**
2670 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2671 * for which alarm clocks have changed since the last call to this.
2672 *
2673 * Do not call with a lock held. Only call from mHandler's thread.
2674 *
2675 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2676 */
2677 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002678 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002679 pendingUsers.clear();
2680
2681 synchronized (mLock) {
2682 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2683 for (int i = 0; i < N; i++) {
2684 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2685 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2686 }
2687 mPendingSendNextAlarmClockChangedForUser.clear();
2688 }
2689
2690 final int N = pendingUsers.size();
2691 for (int i = 0; i < N; i++) {
2692 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002693 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002694 Settings.System.putStringForUser(getContext().getContentResolver(),
2695 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002696 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002697 userId);
2698
2699 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2700 new UserHandle(userId));
2701 }
2702 }
2703
2704 /**
2705 * Formats an alarm like platform/packages/apps/DeskClock used to.
2706 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002707 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2708 int userId) {
2709 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002710 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2711 return (info == null) ? "" :
2712 DateFormat.format(pattern, info.getTriggerTime()).toString();
2713 }
2714
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002715 /**
2716 * If the last time AlarmThread woke up precedes any due wakeup or non-wakeup alarm that we set
2717 * by more than half a minute, log a wtf.
2718 */
2719 private void validateLastAlarmExpiredLocked(long nowElapsed) {
2720 final StringBuilder errorMsg = new StringBuilder();
2721 boolean stuck = false;
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002722 if (mNextNonWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextNonWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002723 stuck = true;
2724 errorMsg.append("[mNextNonWakeup=");
2725 TimeUtils.formatDuration(mNextNonWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002726 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002727 TimeUtils.formatDuration(mNextNonWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002728 errorMsg.append(", mLastWakeup=");
2729 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002730 errorMsg.append(", timerfd_gettime=" + mInjector.getNextAlarm(ELAPSED_REALTIME));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002731 errorMsg.append("];");
2732 }
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002733 if (mNextWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002734 stuck = true;
2735 errorMsg.append("[mNextWakeup=");
2736 TimeUtils.formatDuration(mNextWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002737 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002738 TimeUtils.formatDuration(mNextWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002739 errorMsg.append(", mLastWakeup=");
2740 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2741 errorMsg.append(", timerfd_gettime="
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002742 + mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002743 errorMsg.append("];");
2744 }
2745 if (stuck) {
2746 Slog.wtf(TAG, "Alarm delivery stuck: " + errorMsg.toString());
2747 }
2748 }
2749
Adam Lesinski182f73f2013-12-05 16:48:06 -08002750 void rescheduleKernelAlarmsLocked() {
2751 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2752 // prior to that which contains no wakeups, we schedule that as well.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002753 final long nowElapsed = mInjector.getElapsedRealtime();
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002754 validateLastAlarmExpiredLocked(nowElapsed);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002755 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002756 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002757 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002758 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002759 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002760 mNextWakeup = firstWakeup.start;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002761 mNextWakeUpSetAt = nowElapsed;
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002762 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002763 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002764 if (firstBatch != firstWakeup) {
2765 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002766 }
2767 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002768 if (mPendingNonWakeupAlarms.size() > 0) {
2769 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2770 nextNonWakeup = mNextNonWakeupDeliveryTime;
2771 }
2772 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002773 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002774 mNextNonWakeup = nextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002775 mNextNonWakeUpSetAt = nowElapsed;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002776 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2777 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002778 }
2779
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002780 void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002781 if (operation == null && directReceiver == null) {
2782 if (localLOGV) {
2783 Slog.w(TAG, "requested remove() of null operation",
2784 new RuntimeException("here"));
2785 }
2786 return;
2787 }
2788
Adam Lesinski182f73f2013-12-05 16:48:06 -08002789 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002790 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002791 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2792 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002793 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002794 if (b.size() == 0) {
2795 mAlarmBatches.remove(i);
2796 }
2797 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002798 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002799 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002800 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2801 mPendingWhileIdleAlarms.remove(i);
2802 }
2803 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002804 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2805 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2806 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2807 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2808 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2809 alarmsForUid.remove(j);
2810 }
2811 }
2812 if (alarmsForUid.size() == 0) {
2813 mPendingBackgroundAlarms.removeAt(i);
2814 }
2815 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002816 if (didRemove) {
2817 if (DEBUG_BATCH) {
2818 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2819 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002820 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002821 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002822 mPendingIdleUntil = null;
2823 restorePending = true;
2824 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002825 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002826 mNextWakeFromIdle = null;
2827 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002828 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002829 if (restorePending) {
2830 restorePendingWhileIdleAlarmsLocked();
2831 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002832 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002833 }
2834 }
2835
Christopher Tate1d99c392017-12-07 16:54:04 -08002836 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002837 if (uid == Process.SYSTEM_UID) {
2838 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2839 return;
2840 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002841 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002842 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002843 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2844 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002845 didRemove |= b.remove(whichAlarms);
2846 if (b.size() == 0) {
2847 mAlarmBatches.remove(i);
2848 }
2849 }
2850 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2851 final Alarm a = mPendingWhileIdleAlarms.get(i);
2852 if (a.uid == uid) {
2853 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2854 mPendingWhileIdleAlarms.remove(i);
2855 }
2856 }
2857 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2858 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2859 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2860 if (alarmsForUid.get(j).uid == uid) {
2861 alarmsForUid.remove(j);
2862 }
2863 }
2864 if (alarmsForUid.size() == 0) {
2865 mPendingBackgroundAlarms.removeAt(i);
2866 }
2867 }
2868 if (didRemove) {
2869 if (DEBUG_BATCH) {
2870 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2871 }
2872 rebatchAllAlarmsLocked(true);
2873 rescheduleKernelAlarmsLocked();
2874 updateNextAlarmClockLocked();
2875 }
2876 }
2877
2878 void removeLocked(final String packageName) {
2879 if (packageName == null) {
2880 if (localLOGV) {
2881 Slog.w(TAG, "requested remove() of null packageName",
2882 new RuntimeException("here"));
2883 }
2884 return;
2885 }
2886
2887 boolean didRemove = false;
2888 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002889 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002890 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2891 Batch b = mAlarmBatches.get(i);
2892 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002893 if (b.size() == 0) {
2894 mAlarmBatches.remove(i);
2895 }
2896 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002897 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2898 if (oldHasTick != newHasTick) {
2899 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2900 }
2901
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002902 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002903 final Alarm a = mPendingWhileIdleAlarms.get(i);
2904 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002905 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2906 mPendingWhileIdleAlarms.remove(i);
2907 }
2908 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002909 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2910 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2911 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2912 if (alarmsForUid.get(j).matches(packageName)) {
2913 alarmsForUid.remove(j);
2914 }
2915 }
2916 if (alarmsForUid.size() == 0) {
2917 mPendingBackgroundAlarms.removeAt(i);
2918 }
2919 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002920 if (didRemove) {
2921 if (DEBUG_BATCH) {
2922 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2923 }
2924 rebatchAllAlarmsLocked(true);
2925 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002926 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002927 }
2928 }
2929
Christopher Tate1d99c392017-12-07 16:54:04 -08002930 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002931 if (uid == Process.SYSTEM_UID) {
2932 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2933 return;
2934 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002935 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002936 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2937 try {
2938 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2939 uid, a.packageName)) {
2940 return true;
2941 }
2942 } catch (RemoteException e) { /* fall through */}
2943 return false;
2944 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002945 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2946 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002947 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002948 if (b.size() == 0) {
2949 mAlarmBatches.remove(i);
2950 }
2951 }
2952 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2953 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002954 if (a.uid == uid) {
2955 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2956 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002957 }
2958 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002959 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2960 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2961 mPendingBackgroundAlarms.removeAt(i);
2962 }
2963 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002964 if (didRemove) {
2965 if (DEBUG_BATCH) {
2966 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2967 }
2968 rebatchAllAlarmsLocked(true);
2969 rescheduleKernelAlarmsLocked();
2970 updateNextAlarmClockLocked();
2971 }
2972 }
2973
Adam Lesinski182f73f2013-12-05 16:48:06 -08002974 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002975 if (userHandle == UserHandle.USER_SYSTEM) {
2976 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2977 return;
2978 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002979 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002980 final Predicate<Alarm> whichAlarms =
2981 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002982 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2983 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002984 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002985 if (b.size() == 0) {
2986 mAlarmBatches.remove(i);
2987 }
2988 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002989 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002990 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002991 == userHandle) {
2992 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2993 mPendingWhileIdleAlarms.remove(i);
2994 }
2995 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002996 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2997 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2998 mPendingBackgroundAlarms.removeAt(i);
2999 }
3000 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003001 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
3002 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
3003 mLastAllowWhileIdleDispatch.removeAt(i);
3004 }
3005 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003006
3007 if (didRemove) {
3008 if (DEBUG_BATCH) {
3009 Slog.v(TAG, "remove(user) changed bounds; rebatching");
3010 }
3011 rebatchAllAlarmsLocked(true);
3012 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02003013 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003014 }
3015 }
3016
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003017 void interactiveStateChangedLocked(boolean interactive) {
3018 if (mInteractive != interactive) {
3019 mInteractive = interactive;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003020 final long nowELAPSED = mInjector.getElapsedRealtime();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003021 if (interactive) {
3022 if (mPendingNonWakeupAlarms.size() > 0) {
3023 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3024 mTotalDelayTime += thisDelayTime;
3025 if (mMaxDelayTime < thisDelayTime) {
3026 mMaxDelayTime = thisDelayTime;
3027 }
3028 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
3029 mPendingNonWakeupAlarms.clear();
3030 }
3031 if (mNonInteractiveStartTime > 0) {
3032 long dur = nowELAPSED - mNonInteractiveStartTime;
3033 if (dur > mNonInteractiveTime) {
3034 mNonInteractiveTime = dur;
3035 }
3036 }
3037 } else {
3038 mNonInteractiveStartTime = nowELAPSED;
3039 }
3040 }
3041 }
3042
Adam Lesinski182f73f2013-12-05 16:48:06 -08003043 boolean lookForPackageLocked(String packageName) {
3044 for (int i = 0; i < mAlarmBatches.size(); i++) {
3045 Batch b = mAlarmBatches.get(i);
3046 if (b.hasPackage(packageName)) {
3047 return true;
3048 }
3049 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003050 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003051 final Alarm a = mPendingWhileIdleAlarms.get(i);
3052 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003053 return true;
3054 }
3055 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003056 return false;
3057 }
3058
3059 private void setLocked(int type, long when) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003060 if (mInjector.isAlarmDriverPresent()) {
3061 mInjector.setAlarm(type, when);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003062 } else {
3063 Message msg = Message.obtain();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003064 msg.what = AlarmHandler.ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07003065
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003066 mHandler.removeMessages(msg.what);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003067 mHandler.sendMessageAtTime(msg, when);
3068 }
3069 }
3070
Dianne Hackborn043fcd92010-10-06 14:27:34 -07003071 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003072 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 for (int i=list.size()-1; i>=0; i--) {
3074 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003075 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3076 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003077 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 }
3079 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003080
3081 private static final String labelForType(int type) {
3082 switch (type) {
3083 case RTC: return "RTC";
3084 case RTC_WAKEUP : return "RTC_WAKEUP";
3085 case ELAPSED_REALTIME : return "ELAPSED";
3086 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003087 }
3088 return "--unknown--";
3089 }
3090
3091 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003092 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003093 for (int i=list.size()-1; i>=0; i--) {
3094 Alarm a = list.get(i);
3095 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003096 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3097 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003098 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003099 }
3100 }
3101
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003102 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003103 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003104 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003105 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003106 return false;
3107 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003108 if (alarm.operation != null) {
3109 if (alarm.operation.isActivity()) {
3110 // Don't defer starting actual UI
3111 return false;
3112 }
3113 if (alarm.operation.isForegroundService()) {
3114 // FG service alarms are nearly as important; consult AST policy
3115 exemptOnBatterySaver = true;
3116 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003117 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003118 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003119 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003120 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003121 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3122 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003123 }
3124
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003125 private static native long init();
3126 private static native void close(long nativeData);
3127 private static native int set(long nativeData, int type, long seconds, long nanoseconds);
3128 private static native int waitForAlarm(long nativeData);
3129 private static native int setKernelTime(long nativeData, long millis);
3130 private static native int setKernelTimezone(long nativeData, int minuteswest);
3131 private static native long getNextAlarm(long nativeData, int type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132
Makoto Onukiadb50d82018-01-29 16:20:30 -08003133 private long getWhileIdleMinIntervalLocked(int uid) {
3134 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003135 final boolean ebs = (mAppStateTracker != null)
3136 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003137 if (!dozing && !ebs) {
3138 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3139 }
3140 if (dozing) {
3141 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3142 }
3143 if (mUseAllowWhileIdleShortTime.get(uid)) {
3144 // if the last allow-while-idle went off while uid was fg, or the uid
3145 // recently came into fg, don't block the alarm for long.
3146 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3147 }
3148 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3149 }
3150
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003151 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003152 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003153 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003154 // batches are temporally sorted, so we need only pull from the
3155 // start of the list until we either empty it or hit a batch
3156 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003157 while (mAlarmBatches.size() > 0) {
3158 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003159 if (batch.start > nowELAPSED) {
3160 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 break;
3162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163
Christopher Tatee0a22b32013-07-11 14:43:13 -07003164 // We will (re)schedule some alarms now; don't let that interfere
3165 // with delivery of this current batch
3166 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003167
Christopher Tatee0a22b32013-07-11 14:43:13 -07003168 final int N = batch.size();
3169 for (int i = 0; i < N; i++) {
3170 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003171
3172 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3173 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003174 // schedule such alarms. The first such alarm from an app is always delivered.
3175 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003176 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003177 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003178 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3179 // alarm went off for this app. Reschedule the alarm to be in the
3180 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003181 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003182 if (alarm.maxWhenElapsed < minTime) {
3183 alarm.maxWhenElapsed = minTime;
3184 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003185 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003186 if (RECORD_DEVICE_IDLE_ALARMS) {
3187 IdleDispatchEntry ent = new IdleDispatchEntry();
3188 ent.uid = alarm.uid;
3189 ent.pkg = alarm.operation.getCreatorPackage();
3190 ent.tag = alarm.operation.getTag("");
3191 ent.op = "RESCHEDULE";
3192 ent.elapsedRealtime = nowELAPSED;
3193 ent.argRealtime = lastTime;
3194 mAllowWhileIdleDispatches.add(ent);
3195 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003196 setImplLocked(alarm, true, false);
3197 continue;
3198 }
3199 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003200 if (isBackgroundRestricted(alarm)) {
3201 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3202 if (DEBUG_BG_LIMIT) {
3203 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3204 }
3205 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3206 if (alarmsForUid == null) {
3207 alarmsForUid = new ArrayList<>();
3208 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3209 }
3210 alarmsForUid.add(alarm);
3211 continue;
3212 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003213
Christopher Tatee0a22b32013-07-11 14:43:13 -07003214 alarm.count = 1;
3215 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003216 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3217 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003218 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003219 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003220 if (mPendingIdleUntil == alarm) {
3221 mPendingIdleUntil = null;
3222 rebatchAllAlarmsLocked(false);
3223 restorePendingWhileIdleAlarmsLocked();
3224 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003225 if (mNextWakeFromIdle == alarm) {
3226 mNextWakeFromIdle = null;
3227 rebatchAllAlarmsLocked(false);
3228 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003229
3230 // Recurring alarms may have passed several alarm intervals while the
3231 // phone was asleep or off, so pass a trigger count when sending them.
3232 if (alarm.repeatInterval > 0) {
3233 // this adjustment will be zero if we're late by
3234 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003235 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003236
3237 // Also schedule its next recurrence
3238 final long delta = alarm.count * alarm.repeatInterval;
3239 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003240 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003241 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003242 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3243 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245
Christopher Tate864d42e2014-12-02 11:48:53 -08003246 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003247 hasWakeup = true;
3248 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003249
3250 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3251 if (alarm.alarmClock != null) {
3252 mNextAlarmClockMayChange = true;
3253 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003256
Christopher Tate1590f1e2014-10-02 17:27:57 -07003257 // This is a new alarm delivery set; bump the sequence number to indicate that
3258 // all apps' alarm delivery classes should be recalculated.
3259 mCurrentSeq++;
3260 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003261 Collections.sort(triggerList, mAlarmDispatchComparator);
3262
3263 if (localLOGV) {
3264 for (int i=0; i<triggerList.size(); i++) {
3265 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3266 }
3267 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003268
3269 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 /**
3273 * This Comparator sorts Alarms into increasing time order.
3274 */
3275 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3276 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003277 long when1 = a1.whenElapsed;
3278 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003279 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 return 1;
3281 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003282 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 return -1;
3284 }
3285 return 0;
3286 }
3287 }
Kweku Adams61e03292017-10-19 14:27:12 -07003288
Makoto Onuki2206af32017-11-21 16:25:35 -08003289 @VisibleForTesting
3290 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003291 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003292 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003293 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003294 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003295 public final IAlarmListener listener;
3296 public final String listenerTag;
3297 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003298 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003299 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003300 public final AlarmManager.AlarmClockInfo alarmClock;
3301 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003302 public final int creatorUid;
3303 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003304 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 public int count;
3306 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003307 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003308 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003309 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003310 // Expected alarm expiry time before app standby deferring is applied.
3311 public long expectedWhenElapsed;
3312 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003314 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003315
Christopher Tate3e04b472013-10-21 17:51:31 -07003316 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003317 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3318 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3319 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003320 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003321 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003322 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3323 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003324 when = _when;
3325 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003326 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003327 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003328 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003329 repeatInterval = _interval;
3330 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003331 listener = _rec;
3332 listenerTag = _listenerTag;
3333 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003334 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003335 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003336 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003337 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003338 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003339 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003340 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003342
Christopher Tate14a7bb02015-10-01 10:24:31 -07003343 public static String makeTag(PendingIntent pi, String tag, int type) {
3344 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3345 ? "*walarm*:" : "*alarm*:";
3346 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3347 }
3348
3349 public WakeupEvent makeWakeupEvent(long nowRTC) {
3350 return new WakeupEvent(nowRTC, creatorUid,
3351 (operation != null)
3352 ? operation.getIntent().getAction()
3353 : ("<listener>:" + listenerTag));
3354 }
3355
3356 // Returns true if either matches
3357 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3358 return (operation != null)
3359 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003360 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003361 }
3362
3363 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003364 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003365 }
3366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003368 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003369 StringBuilder sb = new StringBuilder(128);
3370 sb.append("Alarm{");
3371 sb.append(Integer.toHexString(System.identityHashCode(this)));
3372 sb.append(" type ");
3373 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003374 sb.append(" when ");
3375 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003376 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003377 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003378 sb.append('}');
3379 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 }
3381
Kweku Adams61e03292017-10-19 14:27:12 -07003382 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003383 SimpleDateFormat sdf) {
3384 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003385 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003386 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003387 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3388 expectedWhenElapsed, nowELAPSED, pw);
3389 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3390 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003391 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3392 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003393 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3394 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003395 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003396 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003397 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003398 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003399 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003400 }
3401 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003402 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003403 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003404 pw.print(" count="); pw.print(count);
3405 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003406 if (alarmClock != null) {
3407 pw.print(prefix); pw.println("Alarm clock:");
3408 pw.print(prefix); pw.print(" triggerTime=");
3409 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3410 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3411 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003412 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003413 if (listener != null) {
3414 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 }
Kweku Adams61e03292017-10-19 14:27:12 -07003417
3418 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3419 long nowRTC) {
3420 final long token = proto.start(fieldId);
3421
3422 proto.write(AlarmProto.TAG, statsTag);
3423 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003424 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003425 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3426 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3427 proto.write(AlarmProto.COUNT, count);
3428 proto.write(AlarmProto.FLAGS, flags);
3429 if (alarmClock != null) {
3430 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3431 }
3432 if (operation != null) {
3433 operation.writeToProto(proto, AlarmProto.OPERATION);
3434 }
3435 if (listener != null) {
3436 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3437 }
3438
3439 proto.end(token);
3440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003442
Christopher Tatee0a22b32013-07-11 14:43:13 -07003443 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3444 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003445 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3446 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003447 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003448 break;
3449 }
3450
Christopher Tatee0a22b32013-07-11 14:43:13 -07003451 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003452 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3453 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003454 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003455 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003456 }
3457 }
3458
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003459 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3460 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3461 if (timeSinceOn < 5*60*1000) {
3462 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3463 return 2*60*1000;
3464 } else if (timeSinceOn < 30*60*1000) {
3465 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3466 return 15*60*1000;
3467 } else {
3468 // Otherwise, we will delay by at most an hour.
3469 return 60*60*1000;
3470 }
3471 }
3472
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003473 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003474 if (duration < 15*60*1000) {
3475 // If the duration until the time is less than 15 minutes, the maximum fuzz
3476 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003477 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003478 } else if (duration < 90*60*1000) {
3479 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3480 return 15*60*1000;
3481 } else {
3482 // Otherwise, we will fuzz by at most half an hour.
3483 return 30*60*1000;
3484 }
3485 }
3486
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003487 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3488 if (mInteractive) {
3489 return false;
3490 }
3491 if (mLastAlarmDeliveryTime <= 0) {
3492 return false;
3493 }
minho.choo649acab2014-12-12 16:13:55 +09003494 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003495 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3496 // and the next delivery time is in the past, then just deliver them all. This
3497 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3498 return false;
3499 }
3500 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3501 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3502 }
3503
3504 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3505 mLastAlarmDeliveryTime = nowELAPSED;
3506 for (int i=0; i<triggerList.size(); i++) {
3507 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003508 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003509 if (alarm.wakeup) {
3510 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3511 } else {
3512 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3513 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003514 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003515 if (localLOGV) {
3516 Slog.v(TAG, "sending alarm " + alarm);
3517 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003518 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003519 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3520 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003521 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003522 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003523 } catch (RuntimeException e) {
3524 Slog.w(TAG, "Failure sending alarm.", e);
3525 }
Tim Murray175c0f92017-11-28 15:01:04 -08003526 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003527 }
3528 }
3529
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003530 private boolean isExemptFromAppStandby(Alarm a) {
3531 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3532 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3533 }
3534
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003535 @VisibleForTesting
3536 static class Injector {
3537 private long mNativeData;
3538 private Context mContext;
3539
3540 Injector(Context context) {
3541 mContext = context;
3542 }
3543
3544 void init() {
3545 mNativeData = AlarmManagerService.init();
3546 }
3547
3548 int waitForAlarm() {
3549 return AlarmManagerService.waitForAlarm(mNativeData);
3550 }
3551
3552 boolean isAlarmDriverPresent() {
3553 return mNativeData != 0;
3554 }
3555
3556 void setAlarm(int type, long millis) {
3557 // The kernel never triggers alarms with negative wakeup times
3558 // so we ensure they are positive.
3559 final long alarmSeconds, alarmNanoseconds;
3560 if (millis < 0) {
3561 alarmSeconds = 0;
3562 alarmNanoseconds = 0;
3563 } else {
3564 alarmSeconds = millis / 1000;
3565 alarmNanoseconds = (millis % 1000) * 1000 * 1000;
3566 }
3567
3568 final int result = AlarmManagerService.set(mNativeData, type, alarmSeconds,
3569 alarmNanoseconds);
3570 if (result != 0) {
3571 final long nowElapsed = SystemClock.elapsedRealtime();
3572 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
3573 + " type=" + type + " @ (" + alarmSeconds + "," + alarmNanoseconds
3574 + "), ret = " + result + " = " + Os.strerror(result));
3575 }
3576 }
3577
3578 long getNextAlarm(int type) {
3579 return AlarmManagerService.getNextAlarm(mNativeData, type);
3580 }
3581
3582 void setKernelTimezone(int minutesWest) {
3583 AlarmManagerService.setKernelTimezone(mNativeData, minutesWest);
3584 }
3585
3586 void setKernelTime(long millis) {
3587 if (mNativeData != 0) {
3588 AlarmManagerService.setKernelTime(mNativeData, millis);
3589 }
3590 }
3591
3592 void close() {
3593 AlarmManagerService.close(mNativeData);
3594 }
3595
3596 long getElapsedRealtime() {
3597 return SystemClock.elapsedRealtime();
3598 }
3599
3600 long getCurrentTimeMillis() {
3601 return System.currentTimeMillis();
3602 }
3603
3604 PowerManager.WakeLock getAlarmWakeLock() {
3605 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
3606 return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
3607 }
3608
3609 int getSystemUiUid() {
3610 int sysUiUid = -1;
3611 final PackageManager pm = mContext.getPackageManager();
3612 try {
3613 PermissionInfo sysUiPerm = pm.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
3614 ApplicationInfo sysUi = pm.getApplicationInfo(sysUiPerm.packageName, 0);
3615 if ((sysUi.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
3616 sysUiUid = sysUi.uid;
3617 } else {
3618 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
3619 + " defined by non-privileged app " + sysUi.packageName
3620 + " - ignoring");
3621 }
3622 } catch (NameNotFoundException e) {
3623 }
3624 return sysUiUid;
3625 }
3626
3627 ClockReceiver getClockReceiver(AlarmManagerService service) {
3628 return service.new ClockReceiver();
3629 }
3630 }
3631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 private class AlarmThread extends Thread
3633 {
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003634 private int mFalseWakeups;
3635 private int mWtfThreshold;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 public AlarmThread()
3637 {
3638 super("AlarmManager");
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003639 mFalseWakeups = 0;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003640 mWtfThreshold = 100;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
Kweku Adams61e03292017-10-19 14:27:12 -07003642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 public void run()
3644 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003645 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 while (true)
3648 {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003649 int result = mInjector.waitForAlarm();
3650 final long nowRTC = mInjector.getCurrentTimeMillis();
3651 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003652 synchronized (mLock) {
3653 mLastWakeup = nowELAPSED;
3654 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003655 if (result == 0) {
3656 Slog.wtf(TAG, "waitForAlarm returned 0, nowRTC = " + nowRTC
3657 + ", nowElapsed = " + nowELAPSED);
3658 }
Christopher Tate8b98ade2018-02-09 11:13:19 -08003659 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003662 // The kernel can give us spurious time change notifications due to
3663 // small adjustments it makes internally; we want to filter those out.
3664 final long lastTimeChangeClockTime;
3665 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003666 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003667 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3668 expectedClockTime = lastTimeChangeClockTime
3669 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003670 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003671 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3672 || nowRTC > (expectedClockTime+1000)) {
3673 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003674 // let's do it!
3675 if (DEBUG_BATCH) {
3676 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3677 }
Bookatz7948c872018-09-04 12:58:33 -07003678 // StatsLog requires currentTimeMillis(), which == nowRTC to within usecs.
3679 StatsLog.write(StatsLog.WALL_CLOCK_TIME_SHIFTED, nowRTC);
Christopher Tatec8b7f432018-09-28 16:23:10 -07003680 removeImpl(null, mTimeTickTrigger);
3681 removeImpl(mDateChangeSender, null);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003682 rebatchAllAlarms();
3683 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003684 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003685 synchronized (mLock) {
3686 mNumTimeChanged++;
3687 mLastTimeChangeClockTime = nowRTC;
3688 mLastTimeChangeRealtime = nowELAPSED;
3689 }
3690 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3691 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003692 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003693 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3694 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003695 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3696
3697 // The world has changed on us, so we need to re-evaluate alarms
3698 // regardless of whether the kernel has told us one went off.
3699 result |= IS_WAKEUP_MASK;
3700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702
Dianne Hackbornc3527222015-05-13 14:03:20 -07003703 if (result != TIME_CHANGED_MASK) {
3704 // If this was anything besides just a time change, then figure what if
3705 // anything to do about alarms.
3706 synchronized (mLock) {
3707 if (localLOGV) Slog.v(
3708 TAG, "Checking for alarms... rtc=" + nowRTC
3709 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003710
Dianne Hackbornc3527222015-05-13 14:03:20 -07003711 if (WAKEUP_STATS) {
3712 if ((result & IS_WAKEUP_MASK) != 0) {
3713 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3714 int n = 0;
3715 for (WakeupEvent event : mRecentWakeups) {
3716 if (event.when > newEarliest) break;
3717 n++; // number of now-stale entries at the list head
3718 }
3719 for (int i = 0; i < n; i++) {
3720 mRecentWakeups.remove();
3721 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003722
Dianne Hackbornc3527222015-05-13 14:03:20 -07003723 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003724 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003725 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003726
Christopher Tate8b98ade2018-02-09 11:13:19 -08003727 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003728 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3729 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3730 // if there are no wakeup alarms and the screen is off, we can
3731 // delay what we have so far until the future.
3732 if (mPendingNonWakeupAlarms.size() == 0) {
3733 mStartCurrentDelayTime = nowELAPSED;
3734 mNextNonWakeupDeliveryTime = nowELAPSED
3735 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3736 }
3737 mPendingNonWakeupAlarms.addAll(triggerList);
3738 mNumDelayedAlarms += triggerList.size();
3739 rescheduleKernelAlarmsLocked();
3740 updateNextAlarmClockLocked();
3741 } else {
3742 // now deliver the alarm intents; if there are pending non-wakeup
3743 // alarms, we need to merge them in to the list. note we don't
3744 // just deliver them first because we generally want non-wakeup
3745 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003746 if (mPendingNonWakeupAlarms.size() > 0) {
3747 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3748 triggerList.addAll(mPendingNonWakeupAlarms);
3749 Collections.sort(triggerList, mAlarmDispatchComparator);
3750 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3751 mTotalDelayTime += thisDelayTime;
3752 if (mMaxDelayTime < thisDelayTime) {
3753 mMaxDelayTime = thisDelayTime;
3754 }
3755 mPendingNonWakeupAlarms.clear();
3756 }
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003757 if (mLastTimeChangeRealtime != nowELAPSED && triggerList.isEmpty()) {
3758 if (++mFalseWakeups >= mWtfThreshold) {
3759 Slog.wtf(TAG, "Too many (" + mFalseWakeups
3760 + ") false wakeups, nowElapsed=" + nowELAPSED);
3761 if (mWtfThreshold < 100_000) {
3762 mWtfThreshold *= 10;
3763 } else {
3764 mFalseWakeups = 0;
3765 }
3766 }
3767 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003768 final ArraySet<Pair<String, Integer>> triggerPackages =
3769 new ArraySet<>();
3770 for (int i = 0; i < triggerList.size(); i++) {
3771 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003772 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003773 triggerPackages.add(Pair.create(
3774 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003775 }
3776 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003777 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003778 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3779 rescheduleKernelAlarmsLocked();
3780 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003783
3784 } else {
3785 // Just in case -- even though no wakeup flag was set, make sure
3786 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003787 synchronized (mLock) {
3788 rescheduleKernelAlarmsLocked();
3789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 }
3791 }
3792 }
3793 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003794
David Christieebe51fc2013-07-26 13:23:29 -07003795 /**
3796 * Attribute blame for a WakeLock.
3797 * @param pi PendingIntent to attribute blame to if ws is null.
3798 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003799 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003800 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003801 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003802 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003803 try {
Christopher Tatec8b7f432018-09-28 16:23:10 -07003804 mWakeLock.setHistoryTag(first ? tag : null);
3805
David Christieebe51fc2013-07-26 13:23:29 -07003806 if (ws != null) {
3807 mWakeLock.setWorkSource(ws);
3808 return;
3809 }
3810
Christopher Tate14a7bb02015-10-01 10:24:31 -07003811 final int uid = (knownUid >= 0)
3812 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003813 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003814 if (uid >= 0) {
3815 mWakeLock.setWorkSource(new WorkSource(uid));
3816 return;
3817 }
3818 } catch (Exception e) {
3819 }
3820
3821 // Something went wrong; fall back to attributing the lock to the OS
3822 mWakeLock.setWorkSource(null);
3823 }
3824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 private class AlarmHandler extends Handler {
3826 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003827 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3828 public static final int LISTENER_TIMEOUT = 3;
3829 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003830 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3831 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003832 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003833
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003834 AlarmHandler(Looper looper) {
3835 super(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 }
Kweku Adams61e03292017-10-19 14:27:12 -07003837
Makoto Onuki4d298b52018-02-05 10:54:58 -08003838 public void postRemoveForStopped(int uid) {
3839 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3840 }
3841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003843 switch (msg.what) {
3844 case ALARM_EVENT: {
3845 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3846 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003847 final long nowRTC = mInjector.getCurrentTimeMillis();
3848 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003849 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3850 updateNextAlarmClockLocked();
3851 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003852
Christopher Tate14a7bb02015-10-01 10:24:31 -07003853 // now trigger the alarms without the lock held
3854 for (int i=0; i<triggerList.size(); i++) {
3855 Alarm alarm = triggerList.get(i);
3856 try {
3857 alarm.operation.send();
3858 } catch (PendingIntent.CanceledException e) {
3859 if (alarm.repeatInterval > 0) {
3860 // This IntentSender is no longer valid, but this
3861 // is a repeating alarm, so toss the hoser.
Christopher Tatec8b7f432018-09-28 16:23:10 -07003862 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 }
3865 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003866 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003868
3869 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3870 sendNextAlarmClockChanged();
3871 break;
3872
3873 case LISTENER_TIMEOUT:
3874 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3875 break;
3876
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003877 case REPORT_ALARMS_ACTIVE:
3878 if (mLocalDeviceIdleController != null) {
3879 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3880 }
3881 break;
3882
Suprabh Shukla75edab12018-01-29 14:09:06 -08003883 case APP_STANDBY_PAROLE_CHANGED:
3884 synchronized (mLock) {
3885 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003886 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3887 rescheduleKernelAlarmsLocked();
3888 updateNextAlarmClockLocked();
3889 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003890 }
3891 break;
3892
3893 case APP_STANDBY_BUCKET_CHANGED:
3894 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003895 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3896 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3897 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3898 rescheduleKernelAlarmsLocked();
3899 updateNextAlarmClockLocked();
3900 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003901 }
3902 break;
3903
Makoto Onuki4d298b52018-02-05 10:54:58 -08003904 case REMOVE_FOR_STOPPED:
3905 synchronized (mLock) {
3906 removeForStoppedLocked(msg.arg1);
3907 }
3908 break;
3909
Christopher Tate14a7bb02015-10-01 10:24:31 -07003910 default:
3911 // nope, just ignore it
3912 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 }
3914 }
3915 }
Kweku Adams61e03292017-10-19 14:27:12 -07003916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 class ClockReceiver extends BroadcastReceiver {
3918 public ClockReceiver() {
3919 IntentFilter filter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003921 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 }
Kweku Adams61e03292017-10-19 14:27:12 -07003923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 @Override
3925 public void onReceive(Context context, Intent intent) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07003926 if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 // Since the kernel does not keep track of DST, we need to
3928 // reset the TZ information at the beginning of each day
3929 // based off of the current Zone gmt offset + userspace tracked
3930 // daylight savings information.
3931 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003932 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
3933 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003934 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 }
3936 }
Kweku Adams61e03292017-10-19 14:27:12 -07003937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 public void scheduleTimeTickEvent() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003939 final long currentTime = mInjector.getCurrentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003940 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003941
3942 // Schedule this event for the amount of time that it would take to get to
3943 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003944 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003945
David Christieebe51fc2013-07-26 13:23:29 -07003946 final WorkSource workSource = null; // Let system take blame for time tick events.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003947 setImpl(ELAPSED_REALTIME, mInjector.getElapsedRealtime() + tickEventDelay, 0,
Christopher Tatec8b7f432018-09-28 16:23:10 -07003948 0, null, mTimeTickTrigger, null, AlarmManager.FLAG_STANDALONE, workSource,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003949 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003950
3951 // Finally, remember when we set the tick alarm
3952 synchronized (mLock) {
3953 mLastTickSet = currentTime;
3954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 }
Christopher Tate385e4982013-07-23 18:22:29 -07003956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 public void scheduleDateChangedEvent() {
3958 Calendar calendar = Calendar.getInstance();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003959 calendar.setTimeInMillis(mInjector.getCurrentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003960 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 calendar.set(Calendar.MINUTE, 0);
3962 calendar.set(Calendar.SECOND, 0);
3963 calendar.set(Calendar.MILLISECOND, 0);
3964 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003965
3966 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003967 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3968 AlarmManager.FLAG_STANDALONE, workSource, null,
3969 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 }
3971 }
Kweku Adams61e03292017-10-19 14:27:12 -07003972
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003973 class InteractiveStateReceiver extends BroadcastReceiver {
3974 public InteractiveStateReceiver() {
3975 IntentFilter filter = new IntentFilter();
3976 filter.addAction(Intent.ACTION_SCREEN_OFF);
3977 filter.addAction(Intent.ACTION_SCREEN_ON);
3978 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3979 getContext().registerReceiver(this, filter);
3980 }
3981
3982 @Override
3983 public void onReceive(Context context, Intent intent) {
3984 synchronized (mLock) {
3985 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3986 }
3987 }
3988 }
3989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 class UninstallReceiver extends BroadcastReceiver {
3991 public UninstallReceiver() {
3992 IntentFilter filter = new IntentFilter();
3993 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3994 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003995 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003997 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003998 // Register for events related to sdcard installation.
3999 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004000 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004001 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004002 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08004003 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 }
Kweku Adams61e03292017-10-19 14:27:12 -07004005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 @Override
4007 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004008 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004010 String action = intent.getAction();
4011 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004012 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
4013 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4014 for (String packageName : pkgList) {
4015 if (lookForPackageLocked(packageName)) {
4016 setResultCode(Activity.RESULT_OK);
4017 return;
4018 }
4019 }
4020 return;
4021 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004022 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004023 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
4024 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
4025 if (userHandle >= 0) {
4026 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08004027 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
4028 final Pair<String, Integer> packageUser =
4029 mLastAlarmDeliveredForPackage.keyAt(i);
4030 if (packageUser.second == userHandle) {
4031 mLastAlarmDeliveredForPackage.removeAt(i);
4032 }
4033 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004034 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004035 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004036 if (uid >= 0) {
4037 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08004038 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004039 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004040 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08004041 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
4042 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
4043 // This package is being updated; don't kill its alarms.
4044 return;
4045 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004046 Uri data = intent.getData();
4047 if (data != null) {
4048 String pkg = data.getSchemeSpecificPart();
4049 if (pkg != null) {
4050 pkgList = new String[]{pkg};
4051 }
4052 }
4053 }
4054 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004055 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
4056 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
4057 if (ArrayUtils.contains(pkgList, packageUser.first)
4058 && packageUser.second == UserHandle.getUserId(uid)) {
4059 mLastAlarmDeliveredForPackage.removeAt(i);
4060 }
4061 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004062 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004063 if (uid >= 0) {
4064 // package-removed case
4065 removeLocked(uid);
4066 } else {
4067 // external-applications-unavailable etc case
4068 removeLocked(pkg);
4069 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07004070 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004071 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
4072 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
4073 if (uidStats.remove(pkg) != null) {
4074 if (uidStats.size() <= 0) {
4075 mBroadcastStats.removeAt(i);
4076 }
4077 }
4078 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 }
4081 }
4082 }
4083 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004084
4085 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004086 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004087 }
4088
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004089 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004090 if (disabled) {
4091 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08004092 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004093 }
4094
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004095 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004096 }
4097
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004098 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004099 if (disabled) {
4100 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08004101 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004102 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004103
4104 @Override public void onUidCachedChanged(int uid, boolean cached) {
4105 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004106 };
4107
Suprabh Shukla75edab12018-01-29 14:09:06 -08004108 /**
4109 * Tracking of app assignments to standby buckets
4110 */
4111 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4112 @Override
4113 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08004114 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004115 if (DEBUG_STANDBY) {
4116 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
4117 bucket);
4118 }
4119 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004120 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
4121 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08004122 }
4123
4124 @Override
4125 public void onParoleStateChanged(boolean isParoleOn) {
4126 if (DEBUG_STANDBY) {
4127 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
4128 }
4129 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
4130 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
4131 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
4132 Boolean.valueOf(isParoleOn)).sendToTarget();
4133 }
4134 };
4135
Makoto Onuki2206af32017-11-21 16:25:35 -08004136 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004137 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08004138 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004139 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08004140 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004141 }
4142 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004143
4144 @Override
4145 public void unblockAlarmsForUid(int uid) {
4146 synchronized (mLock) {
4147 sendPendingBackgroundAlarmsLocked(uid, null);
4148 }
4149 }
4150
4151 @Override
4152 public void unblockAlarmsForUidPackage(int uid, String packageName) {
4153 synchronized (mLock) {
4154 sendPendingBackgroundAlarmsLocked(uid, packageName);
4155 }
4156 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08004157
4158 @Override
4159 public void onUidForeground(int uid, boolean foreground) {
4160 synchronized (mLock) {
4161 if (foreground) {
4162 mUseAllowWhileIdleShortTime.put(uid, true);
4163
4164 // Note we don't have to drain the pending while-idle alarms here, because
4165 // this event should coincide with unblockAlarmsForUid().
4166 }
4167 }
4168 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004169 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004172 String pkg = pi.getCreatorPackage();
4173 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004174 return getStatsLocked(uid, pkg);
4175 }
4176
4177 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004178 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4179 if (uidStats == null) {
4180 uidStats = new ArrayMap<String, BroadcastStats>();
4181 mBroadcastStats.put(uid, uidStats);
4182 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004183 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004185 bs = new BroadcastStats(uid, pkgName);
4186 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 }
4188 return bs;
4189 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004190
Christopher Tate21e9f192017-08-08 13:49:11 -07004191 /**
4192 * Canonical count of (operation.send() - onSendFinished()) and
4193 * listener send/complete/timeout invocations.
4194 * Guarded by the usual lock.
4195 */
4196 @GuardedBy("mLock")
4197 private int mSendCount = 0;
4198 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004199 private int mSendFinishCount = 0;
4200 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004201 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004202 @GuardedBy("mLock")
4203 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004204
Christopher Tate14a7bb02015-10-01 10:24:31 -07004205 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004206
Christopher Tate14a7bb02015-10-01 10:24:31 -07004207 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4208 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004209 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004210 return mInFlight.remove(i);
4211 }
4212 }
4213 mLog.w("No in-flight alarm for " + pi + " " + intent);
4214 return null;
4215 }
4216
4217 private InFlight removeLocked(IBinder listener) {
4218 for (int i = 0; i < mInFlight.size(); i++) {
4219 if (mInFlight.get(i).mListener == listener) {
4220 return mInFlight.remove(i);
4221 }
4222 }
4223 mLog.w("No in-flight alarm for listener " + listener);
4224 return null;
4225 }
4226
4227 private void updateStatsLocked(InFlight inflight) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004228 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004229 BroadcastStats bs = inflight.mBroadcastStats;
4230 bs.nesting--;
4231 if (bs.nesting <= 0) {
4232 bs.nesting = 0;
4233 bs.aggregateTime += nowELAPSED - bs.startTime;
4234 }
4235 FilterStats fs = inflight.mFilterStats;
4236 fs.nesting--;
4237 if (fs.nesting <= 0) {
4238 fs.nesting = 0;
4239 fs.aggregateTime += nowELAPSED - fs.startTime;
4240 }
4241 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004242 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4243 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004244 }
4245 }
4246
4247 private void updateTrackingLocked(InFlight inflight) {
4248 if (inflight != null) {
4249 updateStatsLocked(inflight);
4250 }
4251 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004252 if (DEBUG_WAKELOCK) {
4253 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4254 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004255 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004256 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004257 mWakeLock.release();
4258 if (mInFlight.size() > 0) {
4259 mLog.w("Finished all dispatches with " + mInFlight.size()
4260 + " remaining inflights");
4261 for (int i=0; i<mInFlight.size(); i++) {
4262 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4263 }
4264 mInFlight.clear();
4265 }
4266 } else {
4267 // the next of our alarms is now in flight. reattribute the wakelock.
4268 if (mInFlight.size() > 0) {
4269 InFlight inFlight = mInFlight.get(0);
4270 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4271 inFlight.mAlarmType, inFlight.mTag, -1, false);
4272 } else {
4273 // should never happen
4274 mLog.w("Alarm wakelock still held but sent queue empty");
4275 mWakeLock.setWorkSource(null);
4276 }
4277 }
4278 }
4279
4280 /**
4281 * Callback that arrives when a direct-call alarm reports that delivery has finished
4282 */
4283 @Override
4284 public void alarmComplete(IBinder who) {
4285 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004286 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004287 + " pid=" + Binder.getCallingPid());
4288 return;
4289 }
4290
4291 final long ident = Binder.clearCallingIdentity();
4292 try {
4293 synchronized (mLock) {
4294 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4295 InFlight inflight = removeLocked(who);
4296 if (inflight != null) {
4297 if (DEBUG_LISTENER_CALLBACK) {
4298 Slog.i(TAG, "alarmComplete() from " + who);
4299 }
4300 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004301 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004302 } else {
4303 // Delivery timed out, and the timeout handling already took care of
4304 // updating our tracking here, so we needn't do anything further.
4305 if (DEBUG_LISTENER_CALLBACK) {
4306 Slog.i(TAG, "Late alarmComplete() from " + who);
4307 }
4308 }
4309 }
4310 } finally {
4311 Binder.restoreCallingIdentity(ident);
4312 }
4313 }
4314
4315 /**
4316 * Callback that arrives when a PendingIntent alarm has finished delivery
4317 */
4318 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4320 String resultData, Bundle resultExtras) {
4321 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004322 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004323 updateTrackingLocked(removeLocked(pi, intent));
4324 }
4325 }
4326
4327 /**
4328 * Timeout of a direct-call alarm delivery
4329 */
4330 public void alarmTimedOut(IBinder who) {
4331 synchronized (mLock) {
4332 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004333 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004334 // TODO: implement ANR policy for the target
4335 if (DEBUG_LISTENER_CALLBACK) {
4336 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004338 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004339 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004340 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004341 if (DEBUG_LISTENER_CALLBACK) {
4342 Slog.i(TAG, "Spurious timeout of listener " + who);
4343 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004344 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004346 }
4347 }
4348
4349 /**
4350 * Deliver an alarm and set up the post-delivery handling appropriately
4351 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004352 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004353 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4354 if (alarm.operation != null) {
4355 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004356 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004357
Christopher Tate14a7bb02015-10-01 10:24:31 -07004358 try {
4359 alarm.operation.send(getContext(), 0,
4360 mBackgroundIntent.putExtra(
4361 Intent.EXTRA_ALARM_COUNT, alarm.count),
4362 mDeliveryTracker, mHandler, null,
4363 allowWhileIdle ? mIdleOptions : null);
4364 } catch (PendingIntent.CanceledException e) {
4365 if (alarm.repeatInterval > 0) {
4366 // This IntentSender is no longer valid, but this
4367 // is a repeating alarm, so toss it
Christopher Tatec8b7f432018-09-28 16:23:10 -07004368 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004369 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004370 // No actual delivery was possible, so the delivery tracker's
4371 // 'finished' callback won't be invoked. We also don't need
4372 // to do any wakelock or stats tracking, so we have nothing
4373 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004374 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004375 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004376 }
4377 } else {
4378 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004379 mListenerCount++;
Christopher Tatec8b7f432018-09-28 16:23:10 -07004380
4381 if (RECORD_ALARMS_IN_HISTORY) {
4382 if (alarm.listener == mTimeTickTrigger) {
4383 mTickHistory[mNextTickHistory++] = nowELAPSED;
4384 if (mNextTickHistory >= TICK_HISTORY_DEPTH) {
4385 mNextTickHistory = 0;
4386 }
4387 }
4388 }
4389
Christopher Tate14a7bb02015-10-01 10:24:31 -07004390 try {
4391 if (DEBUG_LISTENER_CALLBACK) {
4392 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4393 + " listener=" + alarm.listener.asBinder());
4394 }
4395 alarm.listener.doAlarm(this);
4396 mHandler.sendMessageDelayed(
4397 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4398 alarm.listener.asBinder()),
4399 mConstants.LISTENER_TIMEOUT);
4400 } catch (Exception e) {
4401 if (DEBUG_LISTENER_CALLBACK) {
4402 Slog.i(TAG, "Alarm undeliverable to listener "
4403 + alarm.listener.asBinder(), e);
4404 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004405 // As in the PendingIntent.CanceledException case, delivery of the
4406 // alarm was not possible, so we have no wakelock or timeout or
4407 // stats management to do. It threw before we posted the delayed
4408 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004409 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004410 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004411 }
4412 }
4413
4414 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004415 if (DEBUG_WAKELOCK) {
4416 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4417 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004418 if (mBroadcastRefCount == 0) {
4419 setWakelockWorkSource(alarm.operation, alarm.workSource,
4420 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4421 true);
4422 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004423 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004424 }
4425 final InFlight inflight = new InFlight(AlarmManagerService.this,
4426 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4427 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4428 mInFlight.add(inflight);
4429 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004430 if (allowWhileIdle) {
4431 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004432 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004433 if ((mAppStateTracker == null)
4434 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004435 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4436 } else {
4437 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4438 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004439 if (RECORD_DEVICE_IDLE_ALARMS) {
4440 IdleDispatchEntry ent = new IdleDispatchEntry();
4441 ent.uid = alarm.uid;
4442 ent.pkg = alarm.packageName;
4443 ent.tag = alarm.statsTag;
4444 ent.op = "DELIVER";
4445 ent.elapsedRealtime = nowELAPSED;
4446 mAllowWhileIdleDispatches.add(ent);
4447 }
4448 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004449 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004450 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4451 UserHandle.getUserId(alarm.creatorUid));
4452 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4453 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004454
4455 final BroadcastStats bs = inflight.mBroadcastStats;
4456 bs.count++;
4457 if (bs.nesting == 0) {
4458 bs.nesting = 1;
4459 bs.startTime = nowELAPSED;
4460 } else {
4461 bs.nesting++;
4462 }
4463 final FilterStats fs = inflight.mFilterStats;
4464 fs.count++;
4465 if (fs.nesting == 0) {
4466 fs.nesting = 1;
4467 fs.startTime = nowELAPSED;
4468 } else {
4469 fs.nesting++;
4470 }
4471 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4472 || alarm.type == RTC_WAKEUP) {
4473 bs.numWakeup++;
4474 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004475 ActivityManager.noteWakeupAlarm(
4476 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4477 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 }
4479 }
4480 }
mswest463f4c99d2018-02-01 10:13:10 -08004481
4482 private class ShellCmd extends ShellCommand {
4483
4484 IAlarmManager getBinderService() {
4485 return IAlarmManager.Stub.asInterface(mService);
4486 }
4487
4488 @Override
4489 public int onCommand(String cmd) {
4490 if (cmd == null) {
4491 return handleDefaultCommands(cmd);
4492 }
4493
4494 final PrintWriter pw = getOutPrintWriter();
4495 try {
4496 switch (cmd) {
4497 case "set-time":
4498 final long millis = Long.parseLong(getNextArgRequired());
4499 return (getBinderService().setTime(millis)) ? 0 : -1;
4500 case "set-timezone":
4501 final String tz = getNextArgRequired();
4502 getBinderService().setTimeZone(tz);
4503 return 0;
4504 default:
4505 return handleDefaultCommands(cmd);
4506 }
4507 } catch (Exception e) {
4508 pw.println(e);
4509 }
4510 return -1;
4511 }
4512
4513 @Override
4514 public void onHelp() {
4515 PrintWriter pw = getOutPrintWriter();
4516 pw.println("Alarm manager service (alarm) commands:");
4517 pw.println(" help");
4518 pw.println(" Print this help text.");
4519 pw.println(" set-time TIME");
4520 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4521 pw.println(" since the Epoch.");
4522 pw.println(" set-timezone TZ");
4523 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4524 }
4525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526}