blob: 622b5fe028af17fe6a0cc2843d53c15274fedcbb [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) {
Christopher Tatea4618b02018-10-11 16:22:55 -07001458 // Don't wait for broadcasts to update our midnight alarm
1459 mClockReceiver.scheduleDateChangedEvent();
1460
1461 // And now let everyone else know
Adam Lesinski182f73f2013-12-05 16:48:06 -08001462 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001463 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001464 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001465 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001466 intent.putExtra("time-zone", zone.getID());
1467 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001470
Christopher Tatec8b7f432018-09-28 16:23:10 -07001471 void removeImpl(PendingIntent operation, IAlarmListener listener) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001472 synchronized (mLock) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07001473 removeLocked(operation, listener);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001474 }
1475 }
1476
1477 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001478 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1479 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1480 int callingUid, String callingPackage) {
1481 // must be *either* PendingIntent or AlarmReceiver, but not both
1482 if ((operation == null && directReceiver == null)
1483 || (operation != null && directReceiver != null)) {
1484 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1485 // NB: previous releases failed silently here, so we are continuing to do the same
1486 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 return;
1488 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001489
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001490 // Sanity check the window length. This will catch people mistakenly
1491 // trying to pass an end-of-window timestamp rather than a duration.
1492 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1493 Slog.w(TAG, "Window length " + windowLength
1494 + "ms suspiciously long; limiting to 1 hour");
1495 windowLength = AlarmManager.INTERVAL_HOUR;
1496 }
1497
Christopher Tate498c6cb2014-11-17 16:09:27 -08001498 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001499 // seconds when the API expects milliseconds, or apps trying shenanigans
1500 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001501 final long minInterval = mConstants.MIN_INTERVAL;
1502 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001503 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001504 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001505 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001506 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001507 } else if (interval > mConstants.MAX_INTERVAL) {
1508 Slog.w(TAG, "Suspiciously long interval " + interval
1509 + " millis; clamping");
1510 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001511 }
1512
Christopher Tatee0a22b32013-07-11 14:43:13 -07001513 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1514 throw new IllegalArgumentException("Invalid alarm type " + type);
1515 }
1516
Christopher Tate5f221e82013-07-30 17:13:15 -07001517 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001518 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001519 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001520 + " pid=" + what);
1521 triggerAtTime = 0;
1522 }
1523
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001524 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001525 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1526 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001527 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001528 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1529
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001530 final long maxElapsed;
1531 if (windowLength == AlarmManager.WINDOW_EXACT) {
1532 maxElapsed = triggerElapsed;
1533 } else if (windowLength < 0) {
1534 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001535 // Fix this window in place, so that as time approaches we don't collapse it.
1536 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001537 } else {
1538 maxElapsed = triggerElapsed + windowLength;
1539 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001542 if (DEBUG_BATCH) {
1543 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001544 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001545 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001546 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001548 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001549 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1550 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 }
1552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553
Christopher Tate3e04b472013-10-21 17:51:31 -07001554 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001555 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1556 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1557 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001558 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001559 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1560 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001561 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001562 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001563 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1564 + " -- package not allowed to start");
1565 return;
1566 }
1567 } catch (RemoteException e) {
1568 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001569 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001570 setImplLocked(a, false, doValidate);
1571 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001572
Christopher Tatef2159712018-03-27 16:04:14 -07001573 /**
1574 * Return the minimum time that should elapse before an app in the specified bucket
1575 * can receive alarms again
1576 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001577 @VisibleForTesting
1578 long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001579 // UsageStats bucket values are treated as floors of their behavioral range.
1580 // In other words, a bucket value between WORKING and ACTIVE is treated as
1581 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1582 // values.
1583 final int index;
1584
1585 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1586 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1587 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1588 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1589 else index = ACTIVE_INDEX;
1590
1591 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001592 }
1593
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001594 /**
1595 * Adjusts the alarm delivery time based on the current app standby bucket.
1596 * @param alarm The alarm to adjust
1597 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001598 */
1599 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001600 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001601 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001602 }
1603 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001604 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001605 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001606 alarm.whenElapsed = alarm.expectedWhenElapsed;
1607 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1608 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001609 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001610 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001611 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001612 final long oldWhenElapsed = alarm.whenElapsed;
1613 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1614
Suprabh Shukla75edab12018-01-29 14:09:06 -08001615 final String sourcePackage = alarm.sourcePackage;
1616 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1617 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001618 sourcePackage, sourceUserId, mInjector.getElapsedRealtime());
Suprabh Shukla75edab12018-01-29 14:09:06 -08001619
1620 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1621 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1622 if (lastElapsed > 0) {
1623 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001624 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001625 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001626 } else {
1627 // app is now eligible to run alarms at the originally requested window.
1628 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001629 alarm.whenElapsed = alarm.expectedWhenElapsed;
1630 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001631 }
1632 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001633 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001634 }
1635
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001636 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1637 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001638 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001639 // The caller has given the time they want this to happen at, however we need
1640 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001641 // bring us out of idle at an earlier time.
1642 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001643 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001644 }
1645 // Add fuzz to make the alarm go off some time before the actual desired time.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001646 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001647 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001648 if (fuzz > 0) {
1649 if (mRandom == null) {
1650 mRandom = new Random();
1651 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001652 final int delta = mRandom.nextInt(fuzz);
1653 a.whenElapsed -= delta;
1654 if (false) {
1655 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1656 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1657 Slog.d(TAG, "Applied fuzz: " + fuzz);
1658 Slog.d(TAG, "Final delta: " + delta);
1659 Slog.d(TAG, "Final when: " + a.whenElapsed);
1660 }
1661 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001662 }
1663
1664 } else if (mPendingIdleUntil != null) {
1665 // We currently have an idle until alarm scheduled; if the new alarm has
1666 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001667 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1668 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1669 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001670 == 0) {
1671 mPendingWhileIdleAlarms.add(a);
1672 return;
1673 }
1674 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001675 if (RECORD_DEVICE_IDLE_ALARMS) {
1676 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1677 IdleDispatchEntry ent = new IdleDispatchEntry();
1678 ent.uid = a.uid;
1679 ent.pkg = a.operation.getCreatorPackage();
1680 ent.tag = a.operation.getTag("");
1681 ent.op = "SET";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001682 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001683 ent.argRealtime = a.whenElapsed;
1684 mAllowWhileIdleDispatches.add(ent);
1685 }
1686 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001687 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001688 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001690 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001691 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001692 }
1693
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001694 boolean needRebatch = false;
1695
1696 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001697 if (RECORD_DEVICE_IDLE_ALARMS) {
1698 if (mPendingIdleUntil == null) {
1699 IdleDispatchEntry ent = new IdleDispatchEntry();
1700 ent.uid = 0;
1701 ent.pkg = "START IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001702 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001703 mAllowWhileIdleDispatches.add(ent);
1704 }
1705 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001706 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1707 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1708 + " to " + a);
1709 }
1710
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001711 mPendingIdleUntil = a;
1712 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001713 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1714 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1715 mNextWakeFromIdle = a;
1716 // If this wake from idle is earlier than whatever was previously scheduled,
1717 // and we are currently idling, then we need to rebatch alarms in case the idle
1718 // until time needs to be updated.
1719 if (mPendingIdleUntil != null) {
1720 needRebatch = true;
1721 }
1722 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001723 }
1724
1725 if (!rebatching) {
1726 if (DEBUG_VALIDATE) {
1727 if (doValidate && !validateConsistencyLocked()) {
1728 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1729 + " when(hex)=" + Long.toHexString(a.when)
1730 + " whenElapsed=" + a.whenElapsed
1731 + " maxWhenElapsed=" + a.maxWhenElapsed
1732 + " interval=" + a.repeatInterval + " op=" + a.operation
1733 + " flags=0x" + Integer.toHexString(a.flags));
1734 rebatchAllAlarmsLocked(false);
1735 needRebatch = false;
1736 }
1737 }
1738
1739 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001740 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001741 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001742
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001743 rescheduleKernelAlarmsLocked();
1744 updateNextAlarmClockLocked();
1745 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001746 }
1747
Christopher Tate1d99c392017-12-07 16:54:04 -08001748 /**
1749 * System-process internal API
1750 */
1751 private final class LocalService implements AlarmManagerInternal {
1752 @Override
1753 public void removeAlarmsForUid(int uid) {
1754 synchronized (mLock) {
1755 removeLocked(uid);
1756 }
1757 }
1758 }
1759
1760 /**
1761 * Public-facing binder interface
1762 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001763 private final IBinder mService = new IAlarmManager.Stub() {
1764 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001765 public void set(String callingPackage,
1766 int type, long triggerAtTime, long windowLength, long interval, int flags,
1767 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1768 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001769 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001770
1771 // make sure the caller is not lying about which package should be blamed for
1772 // wakelock time spent in alarm delivery
1773 mAppOps.checkPackage(callingUid, callingPackage);
1774
1775 // Repeating alarms must use PendingIntent, not direct listener
1776 if (interval != 0) {
1777 if (directReceiver != null) {
1778 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1779 }
1780 }
1781
Adam Lesinski182f73f2013-12-05 16:48:06 -08001782 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001783 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001784 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001785 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001786 }
1787
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001788 // No incoming callers can request either WAKE_FROM_IDLE or
1789 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1790 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1791 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1792
1793 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1794 // manager when to come out of idle mode, which is only for DeviceIdleController.
1795 if (callingUid != Process.SYSTEM_UID) {
1796 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1797 }
1798
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001799 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001800 if (windowLength == AlarmManager.WINDOW_EXACT) {
1801 flags |= AlarmManager.FLAG_STANDALONE;
1802 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001803
1804 // If this alarm is for an alarm clock, then it must be standalone and we will
1805 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001806 if (alarmClock != null) {
1807 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001808
1809 // If the caller is a core system component or on the user's whitelist, and not calling
1810 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1811 // This means we will allow these alarms to go off as normal even while idle, with no
1812 // timing restrictions.
1813 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001814 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001815 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001816 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001817 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1818 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001819 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001820
Christopher Tate14a7bb02015-10-01 10:24:31 -07001821 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1822 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001823 }
Christopher Tate89779822012-08-31 14:40:03 -07001824
Adam Lesinski182f73f2013-12-05 16:48:06 -08001825 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001826 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001827 getContext().enforceCallingOrSelfPermission(
1828 "android.permission.SET_TIME",
1829 "setTime");
1830
mswest463f4c99d2018-02-01 10:13:10 -08001831 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001833
1834 @Override
1835 public void setTimeZone(String tz) {
1836 getContext().enforceCallingOrSelfPermission(
1837 "android.permission.SET_TIME_ZONE",
1838 "setTimeZone");
1839
1840 final long oldId = Binder.clearCallingIdentity();
1841 try {
1842 setTimeZoneImpl(tz);
1843 } finally {
1844 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001847
Adam Lesinski182f73f2013-12-05 16:48:06 -08001848 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001849 public void remove(PendingIntent operation, IAlarmListener listener) {
1850 if (operation == null && listener == null) {
1851 Slog.w(TAG, "remove() with no intent or listener");
1852 return;
1853 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001854
Christopher Tate14a7bb02015-10-01 10:24:31 -07001855 synchronized (mLock) {
1856 removeLocked(operation, listener);
1857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001859
Adam Lesinski182f73f2013-12-05 16:48:06 -08001860 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001861 public long getNextWakeFromIdleTime() {
1862 return getNextWakeFromIdleTimeImpl();
1863 }
1864
1865 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001866 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001867 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1868 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1869 "getNextAlarmClock", null);
1870
1871 return getNextAlarmClockImpl(userId);
1872 }
1873
1874 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001875 public long currentNetworkTimeMillis() {
1876 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1877 if (time.hasCache()) {
1878 return time.currentTimeMillis();
1879 } else {
1880 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1881 }
1882 }
1883
1884 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001885 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001886 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001887
1888 if (args.length > 0 && "--proto".equals(args[0])) {
1889 dumpProto(fd);
1890 } else {
1891 dumpImpl(pw);
1892 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001893 }
mswest463f4c99d2018-02-01 10:13:10 -08001894
1895 @Override
1896 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1897 FileDescriptor err, String[] args, ShellCallback callback,
1898 ResultReceiver resultReceiver) {
1899 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
1900 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001901 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001902
Adam Lesinski182f73f2013-12-05 16:48:06 -08001903 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 synchronized (mLock) {
1905 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001906 mConstants.dump(pw);
1907 pw.println();
1908
Makoto Onukie4918212018-02-06 11:30:15 -08001909 if (mAppStateTracker != null) {
1910 mAppStateTracker.dump(pw, " ");
1911 pw.println();
1912 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001913
Suprabh Shukla75edab12018-01-29 14:09:06 -08001914 pw.println(" App Standby Parole: " + mAppStandbyParole);
1915 pw.println();
1916
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001917 final long nowELAPSED = mInjector.getElapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001918 final long nowUPTIME = SystemClock.uptimeMillis();
Christopher Tatec8b7f432018-09-28 16:23:10 -07001919 final long nowRTC = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001920 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001921
Dianne Hackborna750a632015-06-16 17:18:23 -07001922 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001923 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001924 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001925 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001926 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001927 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001928 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
Christopher Tate12cf0b62018-01-05 18:40:14 -08001929 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1930 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001931 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1932 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001933
Christopher Tatec8b7f432018-09-28 16:23:10 -07001934 if (RECORD_ALARMS_IN_HISTORY) {
1935 pw.println();
1936 pw.println(" Recent TIME_TICK history:");
1937 int i = mNextTickHistory;
1938 do {
1939 i--;
1940 if (i < 0) i = TICK_HISTORY_DEPTH - 1;
1941 final long time = mTickHistory[i];
1942 pw.print(" ");
1943 pw.println((time > 0)
1944 ? sdf.format(new Date(nowRTC - (nowELAPSED - time)))
1945 : "-");
1946 } while (i != mNextTickHistory);
1947 pw.println();
1948 }
1949
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001950 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
1951 if (ssm != null) {
1952 pw.println();
1953 pw.print(" RuntimeStarted=");
1954 pw.print(sdf.format(
1955 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
1956 if (ssm.isRuntimeRestarted()) {
1957 pw.print(" (Runtime restarted)");
1958 }
1959 pw.println();
1960 pw.print(" Runtime uptime (elapsed): ");
1961 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
1962 pw.println();
1963 pw.print(" Runtime uptime (uptime): ");
1964 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
1965 pw.println();
1966 }
1967
Dianne Hackbornc3527222015-05-13 14:03:20 -07001968 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001969 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001970 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001971 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1972 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001973 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001974 pw.print(" Max wakeup delay: ");
1975 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1976 pw.println();
1977 pw.print(" Time since last dispatch: ");
1978 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1979 pw.println();
1980 pw.print(" Next non-wakeup delivery time: ");
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001981 TimeUtils.formatDuration(mNextNonWakeupDeliveryTime, nowELAPSED, pw);
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001982 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001983
1984 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1985 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001986 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001987 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001988 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001989 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001990 pw.print(" set at "); TimeUtils.formatDuration(mNextNonWakeUpSetAt, nowELAPSED, pw);
1991 pw.println();
Christopher Tate8b98ade2018-02-09 11:13:19 -08001992 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1993 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001994 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001995 pw.print(" set at "); TimeUtils.formatDuration(mNextWakeUpSetAt, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001996 pw.println();
Suprabh Shukla2324e982018-06-05 21:06:22 -07001997
1998 pw.print(" Next kernel non-wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001999 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002000 pw.println();
2001 pw.print(" Next kernel wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002002 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002003 pw.println();
2004
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002005 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002006 pw.print(" = "); pw.println(mLastWakeup);
2007 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
2008 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07002009 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002010
John Spurlock604a5ee2015-06-01 12:27:22 -04002011 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002012 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04002013 final TreeSet<Integer> users = new TreeSet<>();
2014 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
2015 users.add(mNextAlarmClockForUser.keyAt(i));
2016 }
2017 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
2018 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2019 }
2020 for (int user : users) {
2021 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2022 final long time = next != null ? next.getTriggerTime() : 0;
2023 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07002024 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04002025 pw.print(" pendingSend:"); pw.print(pendingSend);
2026 pw.print(" time:"); pw.print(time);
2027 if (time > 0) {
2028 pw.print(" = "); pw.print(sdf.format(new Date(time)));
2029 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
2030 }
2031 pw.println();
2032 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002033 if (mAlarmBatches.size() > 0) {
2034 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002035 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07002036 pw.println(mAlarmBatches.size());
2037 for (Batch b : mAlarmBatches) {
2038 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07002039 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002042 pw.println();
2043 pw.println(" Pending user blocked background alarms: ");
2044 boolean blocked = false;
2045 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2046 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2047 if (blockedAlarms != null && blockedAlarms.size() > 0) {
2048 blocked = true;
2049 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
2050 }
2051 }
2052 if (!blocked) {
2053 pw.println(" none");
2054 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002055
Suprabh Shukla75edab12018-01-29 14:09:06 -08002056 pw.println(" mLastAlarmDeliveredForPackage:");
2057 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
2058 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
2059 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
2060 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
2061 pw.println();
2062 }
2063 pw.println();
2064
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002065 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002066 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002067 pw.println(" Idle mode state:");
2068 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002069 if (mPendingIdleUntil != null) {
2070 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002071 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002072 } else {
2073 pw.println("null");
2074 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002075 pw.println(" Pending alarms:");
2076 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002077 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002078 if (mNextWakeFromIdle != null) {
2079 pw.println();
2080 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002081 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002082 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002083
2084 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002085 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002086 if (mPendingNonWakeupAlarms.size() > 0) {
2087 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002088 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002089 } else {
2090 pw.println("(none)");
2091 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002092 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002093 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2094 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002095 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002096 pw.print(", max non-interactive time: ");
2097 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2098 pw.println();
2099
2100 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002101 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002102 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2103 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2104 pw.print(" Listener send count: "); pw.println(mListenerCount);
2105 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002106 pw.println();
2107
Christopher Tate7f2a0352015-12-08 10:24:33 -08002108 if (mInFlight.size() > 0) {
2109 pw.println("Outstanding deliveries:");
2110 for (int i = 0; i < mInFlight.size(); i++) {
2111 pw.print(" #"); pw.print(i); pw.print(": ");
2112 pw.println(mInFlight.get(i));
2113 }
2114 pw.println();
2115 }
2116
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002117 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002118 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002119 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002120 pw.print(" UID ");
2121 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2122 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002123 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002124 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2125 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2126
2127 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2128 pw.print(" Next allowed:");
2129 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2130 pw.print(" (");
2131 TimeUtils.formatDuration(minInterval, 0, pw);
2132 pw.print(")");
2133
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002134 pw.println();
2135 }
2136 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002137
2138 pw.print(" mUseAllowWhileIdleShortTime: [");
2139 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2140 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2141 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2142 pw.print(" ");
2143 }
2144 }
2145 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002146 pw.println();
2147
Dianne Hackborn81038902012-11-26 17:04:09 -08002148 if (mLog.dump(pw, " Recent problems", " ")) {
2149 pw.println();
2150 }
2151
2152 final FilterStats[] topFilters = new FilterStats[10];
2153 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2154 @Override
2155 public int compare(FilterStats lhs, FilterStats rhs) {
2156 if (lhs.aggregateTime < rhs.aggregateTime) {
2157 return 1;
2158 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2159 return -1;
2160 }
2161 return 0;
2162 }
2163 };
2164 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002165 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002166 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2167 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2168 for (int ip=0; ip<uidStats.size(); ip++) {
2169 BroadcastStats bs = uidStats.valueAt(ip);
2170 for (int is=0; is<bs.filterStats.size(); is++) {
2171 FilterStats fs = bs.filterStats.valueAt(is);
2172 int pos = len > 0
2173 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2174 if (pos < 0) {
2175 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002176 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002177 if (pos < topFilters.length) {
2178 int copylen = topFilters.length - pos - 1;
2179 if (copylen > 0) {
2180 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2181 }
2182 topFilters[pos] = fs;
2183 if (len < topFilters.length) {
2184 len++;
2185 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002186 }
2187 }
2188 }
2189 }
2190 if (len > 0) {
2191 pw.println(" Top Alarms:");
2192 for (int i=0; i<len; i++) {
2193 FilterStats fs = topFilters[i];
2194 pw.print(" ");
2195 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2196 TimeUtils.formatDuration(fs.aggregateTime, pw);
2197 pw.print(" running, "); pw.print(fs.numWakeup);
2198 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002199 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2200 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002201 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002202 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002203 pw.println();
2204 }
2205 }
2206
2207 pw.println(" ");
2208 pw.println(" Alarm Stats:");
2209 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002210 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2211 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2212 for (int ip=0; ip<uidStats.size(); ip++) {
2213 BroadcastStats bs = uidStats.valueAt(ip);
2214 pw.print(" ");
2215 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2216 UserHandle.formatUid(pw, bs.mUid);
2217 pw.print(":");
2218 pw.print(bs.mPackageName);
2219 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2220 pw.print(" running, "); pw.print(bs.numWakeup);
2221 pw.println(" wakeups:");
2222 tmpFilters.clear();
2223 for (int is=0; is<bs.filterStats.size(); is++) {
2224 tmpFilters.add(bs.filterStats.valueAt(is));
2225 }
2226 Collections.sort(tmpFilters, comparator);
2227 for (int i=0; i<tmpFilters.size(); i++) {
2228 FilterStats fs = tmpFilters.get(i);
2229 pw.print(" ");
2230 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2231 TimeUtils.formatDuration(fs.aggregateTime, pw);
2232 pw.print(" "); pw.print(fs.numWakeup);
2233 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002234 pw.print(" alarms, last ");
2235 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2236 pw.println(":");
2237 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002238 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002239 pw.println();
2240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 }
2242 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002243 pw.println();
2244 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002245
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002246 if (RECORD_DEVICE_IDLE_ALARMS) {
2247 pw.println();
2248 pw.println(" Allow while idle dispatches:");
2249 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2250 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2251 pw.print(" ");
2252 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2253 pw.print(": ");
2254 UserHandle.formatUid(pw, ent.uid);
2255 pw.print(":");
2256 pw.println(ent.pkg);
2257 if (ent.op != null) {
2258 pw.print(" ");
2259 pw.print(ent.op);
2260 pw.print(" / ");
2261 pw.print(ent.tag);
2262 if (ent.argRealtime != 0) {
2263 pw.print(" (");
2264 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2265 pw.print(")");
2266 }
2267 pw.println();
2268 }
2269 }
2270 }
2271
Christopher Tate18a75f12013-07-01 18:18:59 -07002272 if (WAKEUP_STATS) {
2273 pw.println();
2274 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002275 long last = -1;
2276 for (WakeupEvent event : mRecentWakeups) {
2277 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2278 pw.print('|');
2279 if (last < 0) {
2280 pw.print('0');
2281 } else {
2282 pw.print(event.when - last);
2283 }
2284 last = event.when;
2285 pw.print('|'); pw.print(event.uid);
2286 pw.print('|'); pw.print(event.action);
2287 pw.println();
2288 }
2289 pw.println();
2290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 }
2292 }
2293
Kweku Adams61e03292017-10-19 14:27:12 -07002294 void dumpProto(FileDescriptor fd) {
2295 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2296
2297 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002298 final long nowRTC = mInjector.getCurrentTimeMillis();
2299 final long nowElapsed = mInjector.getElapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002300 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2301 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2302 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002303 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002304 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002305 mLastTimeChangeRealtime);
2306
Yi Jin2b30f322018-02-20 15:41:47 -08002307 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002308
Makoto Onukie4918212018-02-06 11:30:15 -08002309 if (mAppStateTracker != null) {
2310 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002311 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002312 }
Kweku Adams61e03292017-10-19 14:27:12 -07002313
Yi Jin2b30f322018-02-20 15:41:47 -08002314 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002315 if (!mInteractive) {
2316 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002317 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002318 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002319 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002320 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002321 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002322 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002323 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002324 nowElapsed - mNextNonWakeupDeliveryTime);
2325 }
2326
Yi Jin2b30f322018-02-20 15:41:47 -08002327 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002328 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002329 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002330 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002331 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002332 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002333 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002334 nowElapsed - mNextWakeUpSetAt);
Yi Jin2b30f322018-02-20 15:41:47 -08002335 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002336
2337 final TreeSet<Integer> users = new TreeSet<>();
2338 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2339 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2340 users.add(mNextAlarmClockForUser.keyAt(i));
2341 }
2342 final int pendingSendNextAlarmClockChangedForUserSize =
2343 mPendingSendNextAlarmClockChangedForUser.size();
2344 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2345 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2346 }
2347 for (int user : users) {
2348 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2349 final long time = next != null ? next.getTriggerTime() : 0;
2350 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002351 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002352 proto.write(AlarmClockMetadataProto.USER, user);
2353 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2354 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2355 proto.end(aToken);
2356 }
2357 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002358 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002359 nowElapsed, nowRTC);
2360 }
2361 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2362 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2363 if (blockedAlarms != null) {
2364 for (Alarm a : blockedAlarms) {
2365 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002366 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002367 nowElapsed, nowRTC);
2368 }
2369 }
2370 }
2371 if (mPendingIdleUntil != null) {
2372 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002373 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002374 }
2375 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002376 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002377 nowElapsed, nowRTC);
2378 }
2379 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002380 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002381 nowElapsed, nowRTC);
2382 }
2383
2384 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002385 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002386 nowElapsed, nowRTC);
2387 }
2388
Yi Jin2b30f322018-02-20 15:41:47 -08002389 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2390 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2391 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2392 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002393 mNonInteractiveTime);
2394
Yi Jin2b30f322018-02-20 15:41:47 -08002395 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2396 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2397 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2398 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2399 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002400
2401 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002402 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002403 }
2404
Kweku Adams61e03292017-10-19 14:27:12 -07002405 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2406 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002407 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002408 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2409 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2410
Yi Jin2b30f322018-02-20 15:41:47 -08002411 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2412 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2413 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002414 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002415 proto.end(token);
2416 }
2417
Makoto Onukiadb50d82018-01-29 16:20:30 -08002418 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2419 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002420 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002421 mUseAllowWhileIdleShortTime.keyAt(i));
2422 }
2423 }
2424
Yi Jin2b30f322018-02-20 15:41:47 -08002425 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002426
2427 final FilterStats[] topFilters = new FilterStats[10];
2428 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2429 @Override
2430 public int compare(FilterStats lhs, FilterStats rhs) {
2431 if (lhs.aggregateTime < rhs.aggregateTime) {
2432 return 1;
2433 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2434 return -1;
2435 }
2436 return 0;
2437 }
2438 };
2439 int len = 0;
2440 // Get the top 10 FilterStats, ordered by aggregateTime.
2441 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2442 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2443 for (int ip = 0; ip < uidStats.size(); ++ip) {
2444 BroadcastStats bs = uidStats.valueAt(ip);
2445 for (int is = 0; is < bs.filterStats.size(); ++is) {
2446 FilterStats fs = bs.filterStats.valueAt(is);
2447 int pos = len > 0
2448 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2449 if (pos < 0) {
2450 pos = -pos - 1;
2451 }
2452 if (pos < topFilters.length) {
2453 int copylen = topFilters.length - pos - 1;
2454 if (copylen > 0) {
2455 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2456 }
2457 topFilters[pos] = fs;
2458 if (len < topFilters.length) {
2459 len++;
2460 }
2461 }
2462 }
2463 }
2464 }
2465 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002466 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002467 FilterStats fs = topFilters[i];
2468
Yi Jin2b30f322018-02-20 15:41:47 -08002469 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2470 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002471 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002472 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002473
2474 proto.end(token);
2475 }
2476
2477 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2478 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2479 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2480 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002481 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002482
2483 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002484 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002485
2486 // uidStats is an ArrayMap, which we can't sort.
2487 tmpFilters.clear();
2488 for (int is = 0; is < bs.filterStats.size(); ++is) {
2489 tmpFilters.add(bs.filterStats.valueAt(is));
2490 }
2491 Collections.sort(tmpFilters, comparator);
2492 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002493 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002494 }
2495
2496 proto.end(token);
2497 }
2498 }
2499
2500 if (RECORD_DEVICE_IDLE_ALARMS) {
2501 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2502 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2503 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002504 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002505
2506 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2507 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2508 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2509 proto.write(IdleDispatchEntryProto.OP, ent.op);
2510 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2511 ent.elapsedRealtime);
2512 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2513
2514 proto.end(token);
2515 }
2516 }
2517
2518 if (WAKEUP_STATS) {
2519 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002520 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002521 proto.write(WakeupEventProto.UID, event.uid);
2522 proto.write(WakeupEventProto.ACTION, event.action);
2523 proto.write(WakeupEventProto.WHEN, event.when);
2524 proto.end(token);
2525 }
2526 }
2527 }
2528
2529 proto.flush();
2530 }
2531
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002532 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002533 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2534 PrintWriter pw = new PrintWriter(bs);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002535 final long nowRTC = mInjector.getCurrentTimeMillis();
2536 final long nowELAPSED = mInjector.getElapsedRealtime();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002537 final int NZ = mAlarmBatches.size();
2538 for (int iz = 0; iz < NZ; iz++) {
2539 Batch bz = mAlarmBatches.get(iz);
2540 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002541 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002542 pw.flush();
2543 Slog.v(TAG, bs.toString());
2544 bs.reset();
2545 }
2546 }
2547
2548 private boolean validateConsistencyLocked() {
2549 if (DEBUG_VALIDATE) {
2550 long lastTime = Long.MIN_VALUE;
2551 final int N = mAlarmBatches.size();
2552 for (int i = 0; i < N; i++) {
2553 Batch b = mAlarmBatches.get(i);
2554 if (b.start >= lastTime) {
2555 // duplicate start times are okay because of standalone batches
2556 lastTime = b.start;
2557 } else {
2558 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002559 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2560 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002561 return false;
2562 }
2563 }
2564 }
2565 return true;
2566 }
2567
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002568 private Batch findFirstWakeupBatchLocked() {
2569 final int N = mAlarmBatches.size();
2570 for (int i = 0; i < N; i++) {
2571 Batch b = mAlarmBatches.get(i);
2572 if (b.hasWakeups()) {
2573 return b;
2574 }
2575 }
2576 return null;
2577 }
2578
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002579 long getNextWakeFromIdleTimeImpl() {
2580 synchronized (mLock) {
2581 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2582 }
2583 }
2584
2585 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002586 synchronized (mLock) {
2587 return mNextAlarmClockForUser.get(userId);
2588 }
2589 }
2590
2591 /**
2592 * Recomputes the next alarm clock for all users.
2593 */
2594 private void updateNextAlarmClockLocked() {
2595 if (!mNextAlarmClockMayChange) {
2596 return;
2597 }
2598 mNextAlarmClockMayChange = false;
2599
Jose Lima235510e2014-08-13 12:50:01 -07002600 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002601 nextForUser.clear();
2602
2603 final int N = mAlarmBatches.size();
2604 for (int i = 0; i < N; i++) {
2605 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2606 final int M = alarms.size();
2607
2608 for (int j = 0; j < M; j++) {
2609 Alarm a = alarms.get(j);
2610 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002611 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002612 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002613
2614 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002615 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002616 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002617 " for user " + userId);
2618 }
2619
2620 // Alarms and batches are sorted by time, no need to compare times here.
2621 if (nextForUser.get(userId) == null) {
2622 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002623 } else if (a.alarmClock.equals(current)
2624 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2625 // same/earlier time and it's the one we cited before, so stick with it
2626 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002627 }
2628 }
2629 }
2630 }
2631
2632 // Update mNextAlarmForUser with new values.
2633 final int NN = nextForUser.size();
2634 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002635 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002636 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002637 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002638 if (!newAlarm.equals(currentAlarm)) {
2639 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2640 }
2641 }
2642
2643 // Remove users without any alarm clocks scheduled.
2644 final int NNN = mNextAlarmClockForUser.size();
2645 for (int i = NNN - 1; i >= 0; i--) {
2646 int userId = mNextAlarmClockForUser.keyAt(i);
2647 if (nextForUser.get(userId) == null) {
2648 updateNextAlarmInfoForUserLocked(userId, null);
2649 }
2650 }
2651 }
2652
Jose Lima235510e2014-08-13 12:50:01 -07002653 private void updateNextAlarmInfoForUserLocked(int userId,
2654 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002655 if (alarmClock != null) {
2656 if (DEBUG_ALARM_CLOCK) {
2657 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002658 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002659 }
2660 mNextAlarmClockForUser.put(userId, alarmClock);
2661 } else {
2662 if (DEBUG_ALARM_CLOCK) {
2663 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2664 }
2665 mNextAlarmClockForUser.remove(userId);
2666 }
2667
2668 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2669 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2670 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2671 }
2672
2673 /**
2674 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2675 * for which alarm clocks have changed since the last call to this.
2676 *
2677 * Do not call with a lock held. Only call from mHandler's thread.
2678 *
2679 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2680 */
2681 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002682 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002683 pendingUsers.clear();
2684
2685 synchronized (mLock) {
2686 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2687 for (int i = 0; i < N; i++) {
2688 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2689 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2690 }
2691 mPendingSendNextAlarmClockChangedForUser.clear();
2692 }
2693
2694 final int N = pendingUsers.size();
2695 for (int i = 0; i < N; i++) {
2696 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002697 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002698 Settings.System.putStringForUser(getContext().getContentResolver(),
2699 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002700 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002701 userId);
2702
2703 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2704 new UserHandle(userId));
2705 }
2706 }
2707
2708 /**
2709 * Formats an alarm like platform/packages/apps/DeskClock used to.
2710 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002711 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2712 int userId) {
2713 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002714 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2715 return (info == null) ? "" :
2716 DateFormat.format(pattern, info.getTriggerTime()).toString();
2717 }
2718
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002719 /**
2720 * If the last time AlarmThread woke up precedes any due wakeup or non-wakeup alarm that we set
2721 * by more than half a minute, log a wtf.
2722 */
2723 private void validateLastAlarmExpiredLocked(long nowElapsed) {
2724 final StringBuilder errorMsg = new StringBuilder();
2725 boolean stuck = false;
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002726 if (mNextNonWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextNonWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002727 stuck = true;
2728 errorMsg.append("[mNextNonWakeup=");
2729 TimeUtils.formatDuration(mNextNonWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002730 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002731 TimeUtils.formatDuration(mNextNonWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002732 errorMsg.append(", mLastWakeup=");
2733 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002734 errorMsg.append(", timerfd_gettime=" + mInjector.getNextAlarm(ELAPSED_REALTIME));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002735 errorMsg.append("];");
2736 }
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002737 if (mNextWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002738 stuck = true;
2739 errorMsg.append("[mNextWakeup=");
2740 TimeUtils.formatDuration(mNextWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002741 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002742 TimeUtils.formatDuration(mNextWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002743 errorMsg.append(", mLastWakeup=");
2744 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2745 errorMsg.append(", timerfd_gettime="
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002746 + mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002747 errorMsg.append("];");
2748 }
2749 if (stuck) {
2750 Slog.wtf(TAG, "Alarm delivery stuck: " + errorMsg.toString());
2751 }
2752 }
2753
Adam Lesinski182f73f2013-12-05 16:48:06 -08002754 void rescheduleKernelAlarmsLocked() {
2755 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2756 // prior to that which contains no wakeups, we schedule that as well.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002757 final long nowElapsed = mInjector.getElapsedRealtime();
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002758 validateLastAlarmExpiredLocked(nowElapsed);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002759 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002760 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002761 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002762 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002763 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002764 mNextWakeup = firstWakeup.start;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002765 mNextWakeUpSetAt = nowElapsed;
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002766 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002767 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002768 if (firstBatch != firstWakeup) {
2769 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002770 }
2771 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002772 if (mPendingNonWakeupAlarms.size() > 0) {
2773 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2774 nextNonWakeup = mNextNonWakeupDeliveryTime;
2775 }
2776 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002777 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002778 mNextNonWakeup = nextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002779 mNextNonWakeUpSetAt = nowElapsed;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002780 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2781 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002782 }
2783
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002784 void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002785 if (operation == null && directReceiver == null) {
2786 if (localLOGV) {
2787 Slog.w(TAG, "requested remove() of null operation",
2788 new RuntimeException("here"));
2789 }
2790 return;
2791 }
2792
Adam Lesinski182f73f2013-12-05 16:48:06 -08002793 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002794 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002795 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2796 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002797 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002798 if (b.size() == 0) {
2799 mAlarmBatches.remove(i);
2800 }
2801 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002802 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002803 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002804 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2805 mPendingWhileIdleAlarms.remove(i);
2806 }
2807 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002808 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2809 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2810 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2811 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2812 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2813 alarmsForUid.remove(j);
2814 }
2815 }
2816 if (alarmsForUid.size() == 0) {
2817 mPendingBackgroundAlarms.removeAt(i);
2818 }
2819 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002820 if (didRemove) {
2821 if (DEBUG_BATCH) {
2822 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2823 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002824 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002825 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002826 mPendingIdleUntil = null;
2827 restorePending = true;
2828 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002829 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002830 mNextWakeFromIdle = null;
2831 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002832 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002833 if (restorePending) {
2834 restorePendingWhileIdleAlarmsLocked();
2835 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002836 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002837 }
2838 }
2839
Christopher Tate1d99c392017-12-07 16:54:04 -08002840 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002841 if (uid == Process.SYSTEM_UID) {
2842 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2843 return;
2844 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002845 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002846 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002847 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2848 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002849 didRemove |= b.remove(whichAlarms);
2850 if (b.size() == 0) {
2851 mAlarmBatches.remove(i);
2852 }
2853 }
2854 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2855 final Alarm a = mPendingWhileIdleAlarms.get(i);
2856 if (a.uid == uid) {
2857 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2858 mPendingWhileIdleAlarms.remove(i);
2859 }
2860 }
2861 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2862 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2863 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2864 if (alarmsForUid.get(j).uid == uid) {
2865 alarmsForUid.remove(j);
2866 }
2867 }
2868 if (alarmsForUid.size() == 0) {
2869 mPendingBackgroundAlarms.removeAt(i);
2870 }
2871 }
2872 if (didRemove) {
2873 if (DEBUG_BATCH) {
2874 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2875 }
2876 rebatchAllAlarmsLocked(true);
2877 rescheduleKernelAlarmsLocked();
2878 updateNextAlarmClockLocked();
2879 }
2880 }
2881
2882 void removeLocked(final String packageName) {
2883 if (packageName == null) {
2884 if (localLOGV) {
2885 Slog.w(TAG, "requested remove() of null packageName",
2886 new RuntimeException("here"));
2887 }
2888 return;
2889 }
2890
2891 boolean didRemove = false;
2892 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002893 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002894 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2895 Batch b = mAlarmBatches.get(i);
2896 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002897 if (b.size() == 0) {
2898 mAlarmBatches.remove(i);
2899 }
2900 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002901 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2902 if (oldHasTick != newHasTick) {
2903 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2904 }
2905
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002906 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002907 final Alarm a = mPendingWhileIdleAlarms.get(i);
2908 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002909 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2910 mPendingWhileIdleAlarms.remove(i);
2911 }
2912 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002913 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2914 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2915 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2916 if (alarmsForUid.get(j).matches(packageName)) {
2917 alarmsForUid.remove(j);
2918 }
2919 }
2920 if (alarmsForUid.size() == 0) {
2921 mPendingBackgroundAlarms.removeAt(i);
2922 }
2923 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002924 if (didRemove) {
2925 if (DEBUG_BATCH) {
2926 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2927 }
2928 rebatchAllAlarmsLocked(true);
2929 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002930 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002931 }
2932 }
2933
Christopher Tate1d99c392017-12-07 16:54:04 -08002934 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002935 if (uid == Process.SYSTEM_UID) {
2936 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2937 return;
2938 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002939 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002940 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2941 try {
2942 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2943 uid, a.packageName)) {
2944 return true;
2945 }
2946 } catch (RemoteException e) { /* fall through */}
2947 return false;
2948 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002949 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2950 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002951 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002952 if (b.size() == 0) {
2953 mAlarmBatches.remove(i);
2954 }
2955 }
2956 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2957 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002958 if (a.uid == uid) {
2959 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2960 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002961 }
2962 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002963 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2964 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2965 mPendingBackgroundAlarms.removeAt(i);
2966 }
2967 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002968 if (didRemove) {
2969 if (DEBUG_BATCH) {
2970 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2971 }
2972 rebatchAllAlarmsLocked(true);
2973 rescheduleKernelAlarmsLocked();
2974 updateNextAlarmClockLocked();
2975 }
2976 }
2977
Adam Lesinski182f73f2013-12-05 16:48:06 -08002978 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002979 if (userHandle == UserHandle.USER_SYSTEM) {
2980 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2981 return;
2982 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002983 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002984 final Predicate<Alarm> whichAlarms =
2985 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002986 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2987 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002988 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002989 if (b.size() == 0) {
2990 mAlarmBatches.remove(i);
2991 }
2992 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002993 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002994 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002995 == userHandle) {
2996 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2997 mPendingWhileIdleAlarms.remove(i);
2998 }
2999 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003000 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3001 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
3002 mPendingBackgroundAlarms.removeAt(i);
3003 }
3004 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003005 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
3006 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
3007 mLastAllowWhileIdleDispatch.removeAt(i);
3008 }
3009 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003010
3011 if (didRemove) {
3012 if (DEBUG_BATCH) {
3013 Slog.v(TAG, "remove(user) changed bounds; rebatching");
3014 }
3015 rebatchAllAlarmsLocked(true);
3016 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02003017 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003018 }
3019 }
3020
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003021 void interactiveStateChangedLocked(boolean interactive) {
3022 if (mInteractive != interactive) {
3023 mInteractive = interactive;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003024 final long nowELAPSED = mInjector.getElapsedRealtime();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003025 if (interactive) {
3026 if (mPendingNonWakeupAlarms.size() > 0) {
3027 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3028 mTotalDelayTime += thisDelayTime;
3029 if (mMaxDelayTime < thisDelayTime) {
3030 mMaxDelayTime = thisDelayTime;
3031 }
3032 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
3033 mPendingNonWakeupAlarms.clear();
3034 }
3035 if (mNonInteractiveStartTime > 0) {
3036 long dur = nowELAPSED - mNonInteractiveStartTime;
3037 if (dur > mNonInteractiveTime) {
3038 mNonInteractiveTime = dur;
3039 }
3040 }
3041 } else {
3042 mNonInteractiveStartTime = nowELAPSED;
3043 }
3044 }
3045 }
3046
Adam Lesinski182f73f2013-12-05 16:48:06 -08003047 boolean lookForPackageLocked(String packageName) {
3048 for (int i = 0; i < mAlarmBatches.size(); i++) {
3049 Batch b = mAlarmBatches.get(i);
3050 if (b.hasPackage(packageName)) {
3051 return true;
3052 }
3053 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003054 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003055 final Alarm a = mPendingWhileIdleAlarms.get(i);
3056 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003057 return true;
3058 }
3059 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003060 return false;
3061 }
3062
3063 private void setLocked(int type, long when) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003064 if (mInjector.isAlarmDriverPresent()) {
3065 mInjector.setAlarm(type, when);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003066 } else {
3067 Message msg = Message.obtain();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003068 msg.what = AlarmHandler.ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07003069
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003070 mHandler.removeMessages(msg.what);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003071 mHandler.sendMessageAtTime(msg, when);
3072 }
3073 }
3074
Dianne Hackborn043fcd92010-10-06 14:27:34 -07003075 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003076 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 for (int i=list.size()-1; i>=0; i--) {
3078 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003079 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3080 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003081 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 }
3083 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003084
3085 private static final String labelForType(int type) {
3086 switch (type) {
3087 case RTC: return "RTC";
3088 case RTC_WAKEUP : return "RTC_WAKEUP";
3089 case ELAPSED_REALTIME : return "ELAPSED";
3090 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003091 }
3092 return "--unknown--";
3093 }
3094
3095 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003096 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003097 for (int i=list.size()-1; i>=0; i--) {
3098 Alarm a = list.get(i);
3099 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003100 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3101 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003102 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003103 }
3104 }
3105
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003106 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003107 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003108 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003109 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003110 return false;
3111 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003112 if (alarm.operation != null) {
3113 if (alarm.operation.isActivity()) {
3114 // Don't defer starting actual UI
3115 return false;
3116 }
3117 if (alarm.operation.isForegroundService()) {
3118 // FG service alarms are nearly as important; consult AST policy
3119 exemptOnBatterySaver = true;
3120 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003121 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003122 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003123 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003124 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003125 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3126 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003127 }
3128
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003129 private static native long init();
3130 private static native void close(long nativeData);
3131 private static native int set(long nativeData, int type, long seconds, long nanoseconds);
3132 private static native int waitForAlarm(long nativeData);
3133 private static native int setKernelTime(long nativeData, long millis);
3134 private static native int setKernelTimezone(long nativeData, int minuteswest);
3135 private static native long getNextAlarm(long nativeData, int type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136
Makoto Onukiadb50d82018-01-29 16:20:30 -08003137 private long getWhileIdleMinIntervalLocked(int uid) {
3138 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003139 final boolean ebs = (mAppStateTracker != null)
3140 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003141 if (!dozing && !ebs) {
3142 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3143 }
3144 if (dozing) {
3145 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3146 }
3147 if (mUseAllowWhileIdleShortTime.get(uid)) {
3148 // if the last allow-while-idle went off while uid was fg, or the uid
3149 // recently came into fg, don't block the alarm for long.
3150 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3151 }
3152 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3153 }
3154
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003155 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003156 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003157 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003158 // batches are temporally sorted, so we need only pull from the
3159 // start of the list until we either empty it or hit a batch
3160 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003161 while (mAlarmBatches.size() > 0) {
3162 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003163 if (batch.start > nowELAPSED) {
3164 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 break;
3166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167
Christopher Tatee0a22b32013-07-11 14:43:13 -07003168 // We will (re)schedule some alarms now; don't let that interfere
3169 // with delivery of this current batch
3170 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003171
Christopher Tatee0a22b32013-07-11 14:43:13 -07003172 final int N = batch.size();
3173 for (int i = 0; i < N; i++) {
3174 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003175
3176 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3177 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003178 // schedule such alarms. The first such alarm from an app is always delivered.
3179 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003180 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003181 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003182 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3183 // alarm went off for this app. Reschedule the alarm to be in the
3184 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003185 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003186 if (alarm.maxWhenElapsed < minTime) {
3187 alarm.maxWhenElapsed = minTime;
3188 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003189 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003190 if (RECORD_DEVICE_IDLE_ALARMS) {
3191 IdleDispatchEntry ent = new IdleDispatchEntry();
3192 ent.uid = alarm.uid;
3193 ent.pkg = alarm.operation.getCreatorPackage();
3194 ent.tag = alarm.operation.getTag("");
3195 ent.op = "RESCHEDULE";
3196 ent.elapsedRealtime = nowELAPSED;
3197 ent.argRealtime = lastTime;
3198 mAllowWhileIdleDispatches.add(ent);
3199 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003200 setImplLocked(alarm, true, false);
3201 continue;
3202 }
3203 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003204 if (isBackgroundRestricted(alarm)) {
3205 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3206 if (DEBUG_BG_LIMIT) {
3207 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3208 }
3209 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3210 if (alarmsForUid == null) {
3211 alarmsForUid = new ArrayList<>();
3212 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3213 }
3214 alarmsForUid.add(alarm);
3215 continue;
3216 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003217
Christopher Tatee0a22b32013-07-11 14:43:13 -07003218 alarm.count = 1;
3219 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003220 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3221 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003222 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003223 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003224 if (mPendingIdleUntil == alarm) {
3225 mPendingIdleUntil = null;
3226 rebatchAllAlarmsLocked(false);
3227 restorePendingWhileIdleAlarmsLocked();
3228 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003229 if (mNextWakeFromIdle == alarm) {
3230 mNextWakeFromIdle = null;
3231 rebatchAllAlarmsLocked(false);
3232 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003233
3234 // Recurring alarms may have passed several alarm intervals while the
3235 // phone was asleep or off, so pass a trigger count when sending them.
3236 if (alarm.repeatInterval > 0) {
3237 // this adjustment will be zero if we're late by
3238 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003239 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003240
3241 // Also schedule its next recurrence
3242 final long delta = alarm.count * alarm.repeatInterval;
3243 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003244 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003245 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003246 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3247 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249
Christopher Tate864d42e2014-12-02 11:48:53 -08003250 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003251 hasWakeup = true;
3252 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003253
3254 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3255 if (alarm.alarmClock != null) {
3256 mNextAlarmClockMayChange = true;
3257 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003260
Christopher Tate1590f1e2014-10-02 17:27:57 -07003261 // This is a new alarm delivery set; bump the sequence number to indicate that
3262 // all apps' alarm delivery classes should be recalculated.
3263 mCurrentSeq++;
3264 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003265 Collections.sort(triggerList, mAlarmDispatchComparator);
3266
3267 if (localLOGV) {
3268 for (int i=0; i<triggerList.size(); i++) {
3269 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3270 }
3271 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003272
3273 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 /**
3277 * This Comparator sorts Alarms into increasing time order.
3278 */
3279 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3280 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003281 long when1 = a1.whenElapsed;
3282 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003283 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 return 1;
3285 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003286 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 return -1;
3288 }
3289 return 0;
3290 }
3291 }
Kweku Adams61e03292017-10-19 14:27:12 -07003292
Makoto Onuki2206af32017-11-21 16:25:35 -08003293 @VisibleForTesting
3294 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003295 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003296 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003297 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003298 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003299 public final IAlarmListener listener;
3300 public final String listenerTag;
3301 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003302 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003303 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003304 public final AlarmManager.AlarmClockInfo alarmClock;
3305 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003306 public final int creatorUid;
3307 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003308 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 public int count;
3310 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003311 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003312 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003313 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003314 // Expected alarm expiry time before app standby deferring is applied.
3315 public long expectedWhenElapsed;
3316 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003318 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003319
Christopher Tate3e04b472013-10-21 17:51:31 -07003320 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003321 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3322 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3323 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003324 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003325 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003326 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3327 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003328 when = _when;
3329 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003330 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003331 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003332 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003333 repeatInterval = _interval;
3334 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003335 listener = _rec;
3336 listenerTag = _listenerTag;
3337 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003338 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003339 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003340 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003341 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003342 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003343 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003344 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003346
Christopher Tate14a7bb02015-10-01 10:24:31 -07003347 public static String makeTag(PendingIntent pi, String tag, int type) {
3348 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3349 ? "*walarm*:" : "*alarm*:";
3350 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3351 }
3352
3353 public WakeupEvent makeWakeupEvent(long nowRTC) {
3354 return new WakeupEvent(nowRTC, creatorUid,
3355 (operation != null)
3356 ? operation.getIntent().getAction()
3357 : ("<listener>:" + listenerTag));
3358 }
3359
3360 // Returns true if either matches
3361 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3362 return (operation != null)
3363 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003364 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003365 }
3366
3367 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003368 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003369 }
3370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003372 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003373 StringBuilder sb = new StringBuilder(128);
3374 sb.append("Alarm{");
3375 sb.append(Integer.toHexString(System.identityHashCode(this)));
3376 sb.append(" type ");
3377 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003378 sb.append(" when ");
3379 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003380 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003381 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003382 sb.append('}');
3383 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 }
3385
Kweku Adams61e03292017-10-19 14:27:12 -07003386 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003387 SimpleDateFormat sdf) {
3388 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003389 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003390 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003391 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3392 expectedWhenElapsed, nowELAPSED, pw);
3393 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3394 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003395 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3396 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003397 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3398 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003399 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003400 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003401 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003402 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003403 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003404 }
3405 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003406 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003407 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003408 pw.print(" count="); pw.print(count);
3409 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003410 if (alarmClock != null) {
3411 pw.print(prefix); pw.println("Alarm clock:");
3412 pw.print(prefix); pw.print(" triggerTime=");
3413 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3414 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3415 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003416 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003417 if (listener != null) {
3418 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 }
Kweku Adams61e03292017-10-19 14:27:12 -07003421
3422 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3423 long nowRTC) {
3424 final long token = proto.start(fieldId);
3425
3426 proto.write(AlarmProto.TAG, statsTag);
3427 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003428 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003429 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3430 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3431 proto.write(AlarmProto.COUNT, count);
3432 proto.write(AlarmProto.FLAGS, flags);
3433 if (alarmClock != null) {
3434 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3435 }
3436 if (operation != null) {
3437 operation.writeToProto(proto, AlarmProto.OPERATION);
3438 }
3439 if (listener != null) {
3440 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3441 }
3442
3443 proto.end(token);
3444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003446
Christopher Tatee0a22b32013-07-11 14:43:13 -07003447 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3448 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003449 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3450 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003451 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003452 break;
3453 }
3454
Christopher Tatee0a22b32013-07-11 14:43:13 -07003455 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003456 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3457 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003458 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003459 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003460 }
3461 }
3462
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003463 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3464 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3465 if (timeSinceOn < 5*60*1000) {
3466 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3467 return 2*60*1000;
3468 } else if (timeSinceOn < 30*60*1000) {
3469 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3470 return 15*60*1000;
3471 } else {
3472 // Otherwise, we will delay by at most an hour.
3473 return 60*60*1000;
3474 }
3475 }
3476
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003477 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003478 if (duration < 15*60*1000) {
3479 // If the duration until the time is less than 15 minutes, the maximum fuzz
3480 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003481 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003482 } else if (duration < 90*60*1000) {
3483 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3484 return 15*60*1000;
3485 } else {
3486 // Otherwise, we will fuzz by at most half an hour.
3487 return 30*60*1000;
3488 }
3489 }
3490
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003491 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3492 if (mInteractive) {
3493 return false;
3494 }
3495 if (mLastAlarmDeliveryTime <= 0) {
3496 return false;
3497 }
minho.choo649acab2014-12-12 16:13:55 +09003498 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003499 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3500 // and the next delivery time is in the past, then just deliver them all. This
3501 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3502 return false;
3503 }
3504 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3505 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3506 }
3507
3508 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3509 mLastAlarmDeliveryTime = nowELAPSED;
3510 for (int i=0; i<triggerList.size(); i++) {
3511 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003512 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003513 if (alarm.wakeup) {
3514 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3515 } else {
3516 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3517 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003518 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003519 if (localLOGV) {
3520 Slog.v(TAG, "sending alarm " + alarm);
3521 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003522 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003523 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3524 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003525 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003526 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003527 } catch (RuntimeException e) {
3528 Slog.w(TAG, "Failure sending alarm.", e);
3529 }
Tim Murray175c0f92017-11-28 15:01:04 -08003530 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003531 }
3532 }
3533
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003534 private boolean isExemptFromAppStandby(Alarm a) {
3535 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3536 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3537 }
3538
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003539 @VisibleForTesting
3540 static class Injector {
3541 private long mNativeData;
3542 private Context mContext;
3543
3544 Injector(Context context) {
3545 mContext = context;
3546 }
3547
3548 void init() {
3549 mNativeData = AlarmManagerService.init();
3550 }
3551
3552 int waitForAlarm() {
3553 return AlarmManagerService.waitForAlarm(mNativeData);
3554 }
3555
3556 boolean isAlarmDriverPresent() {
3557 return mNativeData != 0;
3558 }
3559
3560 void setAlarm(int type, long millis) {
3561 // The kernel never triggers alarms with negative wakeup times
3562 // so we ensure they are positive.
3563 final long alarmSeconds, alarmNanoseconds;
3564 if (millis < 0) {
3565 alarmSeconds = 0;
3566 alarmNanoseconds = 0;
3567 } else {
3568 alarmSeconds = millis / 1000;
3569 alarmNanoseconds = (millis % 1000) * 1000 * 1000;
3570 }
3571
3572 final int result = AlarmManagerService.set(mNativeData, type, alarmSeconds,
3573 alarmNanoseconds);
3574 if (result != 0) {
3575 final long nowElapsed = SystemClock.elapsedRealtime();
3576 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
3577 + " type=" + type + " @ (" + alarmSeconds + "," + alarmNanoseconds
3578 + "), ret = " + result + " = " + Os.strerror(result));
3579 }
3580 }
3581
3582 long getNextAlarm(int type) {
3583 return AlarmManagerService.getNextAlarm(mNativeData, type);
3584 }
3585
3586 void setKernelTimezone(int minutesWest) {
3587 AlarmManagerService.setKernelTimezone(mNativeData, minutesWest);
3588 }
3589
3590 void setKernelTime(long millis) {
3591 if (mNativeData != 0) {
3592 AlarmManagerService.setKernelTime(mNativeData, millis);
3593 }
3594 }
3595
3596 void close() {
3597 AlarmManagerService.close(mNativeData);
3598 }
3599
3600 long getElapsedRealtime() {
3601 return SystemClock.elapsedRealtime();
3602 }
3603
3604 long getCurrentTimeMillis() {
3605 return System.currentTimeMillis();
3606 }
3607
3608 PowerManager.WakeLock getAlarmWakeLock() {
3609 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
3610 return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
3611 }
3612
3613 int getSystemUiUid() {
3614 int sysUiUid = -1;
3615 final PackageManager pm = mContext.getPackageManager();
3616 try {
3617 PermissionInfo sysUiPerm = pm.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
3618 ApplicationInfo sysUi = pm.getApplicationInfo(sysUiPerm.packageName, 0);
3619 if ((sysUi.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
3620 sysUiUid = sysUi.uid;
3621 } else {
3622 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
3623 + " defined by non-privileged app " + sysUi.packageName
3624 + " - ignoring");
3625 }
3626 } catch (NameNotFoundException e) {
3627 }
3628 return sysUiUid;
3629 }
3630
3631 ClockReceiver getClockReceiver(AlarmManagerService service) {
3632 return service.new ClockReceiver();
3633 }
3634 }
3635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 private class AlarmThread extends Thread
3637 {
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003638 private int mFalseWakeups;
3639 private int mWtfThreshold;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 public AlarmThread()
3641 {
3642 super("AlarmManager");
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003643 mFalseWakeups = 0;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003644 mWtfThreshold = 100;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 }
Kweku Adams61e03292017-10-19 14:27:12 -07003646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 public void run()
3648 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003649 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 while (true)
3652 {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003653 int result = mInjector.waitForAlarm();
3654 final long nowRTC = mInjector.getCurrentTimeMillis();
3655 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003656 synchronized (mLock) {
3657 mLastWakeup = nowELAPSED;
3658 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003659 if (result == 0) {
3660 Slog.wtf(TAG, "waitForAlarm returned 0, nowRTC = " + nowRTC
3661 + ", nowElapsed = " + nowELAPSED);
3662 }
Christopher Tate8b98ade2018-02-09 11:13:19 -08003663 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003666 // The kernel can give us spurious time change notifications due to
3667 // small adjustments it makes internally; we want to filter those out.
3668 final long lastTimeChangeClockTime;
3669 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003670 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003671 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3672 expectedClockTime = lastTimeChangeClockTime
3673 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003674 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003675 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3676 || nowRTC > (expectedClockTime+1000)) {
3677 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003678 // let's do it!
3679 if (DEBUG_BATCH) {
3680 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3681 }
Bookatz7948c872018-09-04 12:58:33 -07003682 // StatsLog requires currentTimeMillis(), which == nowRTC to within usecs.
3683 StatsLog.write(StatsLog.WALL_CLOCK_TIME_SHIFTED, nowRTC);
Christopher Tatec8b7f432018-09-28 16:23:10 -07003684 removeImpl(null, mTimeTickTrigger);
3685 removeImpl(mDateChangeSender, null);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003686 rebatchAllAlarms();
3687 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003688 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003689 synchronized (mLock) {
3690 mNumTimeChanged++;
3691 mLastTimeChangeClockTime = nowRTC;
3692 mLastTimeChangeRealtime = nowELAPSED;
3693 }
3694 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3695 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003696 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003697 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3698 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003699 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3700
3701 // The world has changed on us, so we need to re-evaluate alarms
3702 // regardless of whether the kernel has told us one went off.
3703 result |= IS_WAKEUP_MASK;
3704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706
Dianne Hackbornc3527222015-05-13 14:03:20 -07003707 if (result != TIME_CHANGED_MASK) {
3708 // If this was anything besides just a time change, then figure what if
3709 // anything to do about alarms.
3710 synchronized (mLock) {
3711 if (localLOGV) Slog.v(
3712 TAG, "Checking for alarms... rtc=" + nowRTC
3713 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003714
Dianne Hackbornc3527222015-05-13 14:03:20 -07003715 if (WAKEUP_STATS) {
3716 if ((result & IS_WAKEUP_MASK) != 0) {
3717 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3718 int n = 0;
3719 for (WakeupEvent event : mRecentWakeups) {
3720 if (event.when > newEarliest) break;
3721 n++; // number of now-stale entries at the list head
3722 }
3723 for (int i = 0; i < n; i++) {
3724 mRecentWakeups.remove();
3725 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003726
Dianne Hackbornc3527222015-05-13 14:03:20 -07003727 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003728 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003729 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003730
Christopher Tate8b98ade2018-02-09 11:13:19 -08003731 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003732 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3733 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3734 // if there are no wakeup alarms and the screen is off, we can
3735 // delay what we have so far until the future.
3736 if (mPendingNonWakeupAlarms.size() == 0) {
3737 mStartCurrentDelayTime = nowELAPSED;
3738 mNextNonWakeupDeliveryTime = nowELAPSED
3739 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3740 }
3741 mPendingNonWakeupAlarms.addAll(triggerList);
3742 mNumDelayedAlarms += triggerList.size();
3743 rescheduleKernelAlarmsLocked();
3744 updateNextAlarmClockLocked();
3745 } else {
3746 // now deliver the alarm intents; if there are pending non-wakeup
3747 // alarms, we need to merge them in to the list. note we don't
3748 // just deliver them first because we generally want non-wakeup
3749 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003750 if (mPendingNonWakeupAlarms.size() > 0) {
3751 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3752 triggerList.addAll(mPendingNonWakeupAlarms);
3753 Collections.sort(triggerList, mAlarmDispatchComparator);
3754 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3755 mTotalDelayTime += thisDelayTime;
3756 if (mMaxDelayTime < thisDelayTime) {
3757 mMaxDelayTime = thisDelayTime;
3758 }
3759 mPendingNonWakeupAlarms.clear();
3760 }
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003761 if (mLastTimeChangeRealtime != nowELAPSED && triggerList.isEmpty()) {
3762 if (++mFalseWakeups >= mWtfThreshold) {
3763 Slog.wtf(TAG, "Too many (" + mFalseWakeups
3764 + ") false wakeups, nowElapsed=" + nowELAPSED);
3765 if (mWtfThreshold < 100_000) {
3766 mWtfThreshold *= 10;
3767 } else {
3768 mFalseWakeups = 0;
3769 }
3770 }
3771 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003772 final ArraySet<Pair<String, Integer>> triggerPackages =
3773 new ArraySet<>();
3774 for (int i = 0; i < triggerList.size(); i++) {
3775 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003776 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003777 triggerPackages.add(Pair.create(
3778 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003779 }
3780 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003781 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003782 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3783 rescheduleKernelAlarmsLocked();
3784 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003787
3788 } else {
3789 // Just in case -- even though no wakeup flag was set, make sure
3790 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003791 synchronized (mLock) {
3792 rescheduleKernelAlarmsLocked();
3793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 }
3795 }
3796 }
3797 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003798
David Christieebe51fc2013-07-26 13:23:29 -07003799 /**
3800 * Attribute blame for a WakeLock.
3801 * @param pi PendingIntent to attribute blame to if ws is null.
3802 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003803 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003804 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003805 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003806 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003807 try {
Christopher Tatec8b7f432018-09-28 16:23:10 -07003808 mWakeLock.setHistoryTag(first ? tag : null);
3809
David Christieebe51fc2013-07-26 13:23:29 -07003810 if (ws != null) {
3811 mWakeLock.setWorkSource(ws);
3812 return;
3813 }
3814
Christopher Tate14a7bb02015-10-01 10:24:31 -07003815 final int uid = (knownUid >= 0)
3816 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003817 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003818 if (uid >= 0) {
3819 mWakeLock.setWorkSource(new WorkSource(uid));
3820 return;
3821 }
3822 } catch (Exception e) {
3823 }
3824
3825 // Something went wrong; fall back to attributing the lock to the OS
3826 mWakeLock.setWorkSource(null);
3827 }
3828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 private class AlarmHandler extends Handler {
3830 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003831 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3832 public static final int LISTENER_TIMEOUT = 3;
3833 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003834 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3835 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003836 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003837
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003838 AlarmHandler(Looper looper) {
3839 super(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 }
Kweku Adams61e03292017-10-19 14:27:12 -07003841
Makoto Onuki4d298b52018-02-05 10:54:58 -08003842 public void postRemoveForStopped(int uid) {
3843 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3844 }
3845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003847 switch (msg.what) {
3848 case ALARM_EVENT: {
3849 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3850 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003851 final long nowRTC = mInjector.getCurrentTimeMillis();
3852 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003853 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3854 updateNextAlarmClockLocked();
3855 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003856
Christopher Tate14a7bb02015-10-01 10:24:31 -07003857 // now trigger the alarms without the lock held
3858 for (int i=0; i<triggerList.size(); i++) {
3859 Alarm alarm = triggerList.get(i);
3860 try {
3861 alarm.operation.send();
3862 } catch (PendingIntent.CanceledException e) {
3863 if (alarm.repeatInterval > 0) {
3864 // This IntentSender is no longer valid, but this
3865 // is a repeating alarm, so toss the hoser.
Christopher Tatec8b7f432018-09-28 16:23:10 -07003866 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 }
3869 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003870 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003872
3873 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3874 sendNextAlarmClockChanged();
3875 break;
3876
3877 case LISTENER_TIMEOUT:
3878 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3879 break;
3880
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003881 case REPORT_ALARMS_ACTIVE:
3882 if (mLocalDeviceIdleController != null) {
3883 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3884 }
3885 break;
3886
Suprabh Shukla75edab12018-01-29 14:09:06 -08003887 case APP_STANDBY_PAROLE_CHANGED:
3888 synchronized (mLock) {
3889 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003890 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3891 rescheduleKernelAlarmsLocked();
3892 updateNextAlarmClockLocked();
3893 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003894 }
3895 break;
3896
3897 case APP_STANDBY_BUCKET_CHANGED:
3898 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003899 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3900 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3901 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3902 rescheduleKernelAlarmsLocked();
3903 updateNextAlarmClockLocked();
3904 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003905 }
3906 break;
3907
Makoto Onuki4d298b52018-02-05 10:54:58 -08003908 case REMOVE_FOR_STOPPED:
3909 synchronized (mLock) {
3910 removeForStoppedLocked(msg.arg1);
3911 }
3912 break;
3913
Christopher Tate14a7bb02015-10-01 10:24:31 -07003914 default:
3915 // nope, just ignore it
3916 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 }
3918 }
3919 }
Kweku Adams61e03292017-10-19 14:27:12 -07003920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 class ClockReceiver extends BroadcastReceiver {
3922 public ClockReceiver() {
3923 IntentFilter filter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003925 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 }
Kweku Adams61e03292017-10-19 14:27:12 -07003927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 @Override
3929 public void onReceive(Context context, Intent intent) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07003930 if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 // Since the kernel does not keep track of DST, we need to
3932 // reset the TZ information at the beginning of each day
3933 // based off of the current Zone gmt offset + userspace tracked
3934 // daylight savings information.
3935 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003936 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
3937 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003938 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 }
3940 }
Kweku Adams61e03292017-10-19 14:27:12 -07003941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 public void scheduleTimeTickEvent() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003943 final long currentTime = mInjector.getCurrentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003944 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003945
3946 // Schedule this event for the amount of time that it would take to get to
3947 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003948 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003949
David Christieebe51fc2013-07-26 13:23:29 -07003950 final WorkSource workSource = null; // Let system take blame for time tick events.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003951 setImpl(ELAPSED_REALTIME, mInjector.getElapsedRealtime() + tickEventDelay, 0,
Christopher Tatec8b7f432018-09-28 16:23:10 -07003952 0, null, mTimeTickTrigger, null, AlarmManager.FLAG_STANDALONE, workSource,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003953 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003954
3955 // Finally, remember when we set the tick alarm
3956 synchronized (mLock) {
3957 mLastTickSet = currentTime;
3958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 }
Christopher Tate385e4982013-07-23 18:22:29 -07003960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 public void scheduleDateChangedEvent() {
3962 Calendar calendar = Calendar.getInstance();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003963 calendar.setTimeInMillis(mInjector.getCurrentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003964 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003965 calendar.set(Calendar.MINUTE, 0);
3966 calendar.set(Calendar.SECOND, 0);
3967 calendar.set(Calendar.MILLISECOND, 0);
3968 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003969
3970 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003971 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3972 AlarmManager.FLAG_STANDALONE, workSource, null,
3973 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 }
3975 }
Kweku Adams61e03292017-10-19 14:27:12 -07003976
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003977 class InteractiveStateReceiver extends BroadcastReceiver {
3978 public InteractiveStateReceiver() {
3979 IntentFilter filter = new IntentFilter();
3980 filter.addAction(Intent.ACTION_SCREEN_OFF);
3981 filter.addAction(Intent.ACTION_SCREEN_ON);
3982 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3983 getContext().registerReceiver(this, filter);
3984 }
3985
3986 @Override
3987 public void onReceive(Context context, Intent intent) {
3988 synchronized (mLock) {
3989 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3990 }
3991 }
3992 }
3993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 class UninstallReceiver extends BroadcastReceiver {
3995 public UninstallReceiver() {
3996 IntentFilter filter = new IntentFilter();
3997 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3998 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003999 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08004001 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004002 // Register for events related to sdcard installation.
4003 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004004 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004005 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004006 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08004007 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 }
Kweku Adams61e03292017-10-19 14:27:12 -07004009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 @Override
4011 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004012 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004014 String action = intent.getAction();
4015 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004016 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
4017 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4018 for (String packageName : pkgList) {
4019 if (lookForPackageLocked(packageName)) {
4020 setResultCode(Activity.RESULT_OK);
4021 return;
4022 }
4023 }
4024 return;
4025 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004026 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004027 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
4028 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
4029 if (userHandle >= 0) {
4030 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08004031 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
4032 final Pair<String, Integer> packageUser =
4033 mLastAlarmDeliveredForPackage.keyAt(i);
4034 if (packageUser.second == userHandle) {
4035 mLastAlarmDeliveredForPackage.removeAt(i);
4036 }
4037 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004038 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004039 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004040 if (uid >= 0) {
4041 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08004042 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004043 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004044 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08004045 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
4046 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
4047 // This package is being updated; don't kill its alarms.
4048 return;
4049 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004050 Uri data = intent.getData();
4051 if (data != null) {
4052 String pkg = data.getSchemeSpecificPart();
4053 if (pkg != null) {
4054 pkgList = new String[]{pkg};
4055 }
4056 }
4057 }
4058 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004059 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
4060 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
4061 if (ArrayUtils.contains(pkgList, packageUser.first)
4062 && packageUser.second == UserHandle.getUserId(uid)) {
4063 mLastAlarmDeliveredForPackage.removeAt(i);
4064 }
4065 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004066 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004067 if (uid >= 0) {
4068 // package-removed case
4069 removeLocked(uid);
4070 } else {
4071 // external-applications-unavailable etc case
4072 removeLocked(pkg);
4073 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07004074 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004075 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
4076 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
4077 if (uidStats.remove(pkg) != null) {
4078 if (uidStats.size() <= 0) {
4079 mBroadcastStats.removeAt(i);
4080 }
4081 }
4082 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 }
4085 }
4086 }
4087 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004088
4089 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004090 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004091 }
4092
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004093 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004094 if (disabled) {
4095 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08004096 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004097 }
4098
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004099 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004100 }
4101
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004102 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004103 if (disabled) {
4104 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08004105 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004106 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004107
4108 @Override public void onUidCachedChanged(int uid, boolean cached) {
4109 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004110 };
4111
Suprabh Shukla75edab12018-01-29 14:09:06 -08004112 /**
4113 * Tracking of app assignments to standby buckets
4114 */
4115 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4116 @Override
4117 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08004118 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004119 if (DEBUG_STANDBY) {
4120 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
4121 bucket);
4122 }
4123 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004124 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
4125 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08004126 }
4127
4128 @Override
4129 public void onParoleStateChanged(boolean isParoleOn) {
4130 if (DEBUG_STANDBY) {
4131 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
4132 }
4133 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
4134 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
4135 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
4136 Boolean.valueOf(isParoleOn)).sendToTarget();
4137 }
4138 };
4139
Makoto Onuki2206af32017-11-21 16:25:35 -08004140 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004141 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08004142 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004143 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08004144 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004145 }
4146 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004147
4148 @Override
4149 public void unblockAlarmsForUid(int uid) {
4150 synchronized (mLock) {
4151 sendPendingBackgroundAlarmsLocked(uid, null);
4152 }
4153 }
4154
4155 @Override
4156 public void unblockAlarmsForUidPackage(int uid, String packageName) {
4157 synchronized (mLock) {
4158 sendPendingBackgroundAlarmsLocked(uid, packageName);
4159 }
4160 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08004161
4162 @Override
4163 public void onUidForeground(int uid, boolean foreground) {
4164 synchronized (mLock) {
4165 if (foreground) {
4166 mUseAllowWhileIdleShortTime.put(uid, true);
4167
4168 // Note we don't have to drain the pending while-idle alarms here, because
4169 // this event should coincide with unblockAlarmsForUid().
4170 }
4171 }
4172 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004173 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004176 String pkg = pi.getCreatorPackage();
4177 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004178 return getStatsLocked(uid, pkg);
4179 }
4180
4181 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004182 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4183 if (uidStats == null) {
4184 uidStats = new ArrayMap<String, BroadcastStats>();
4185 mBroadcastStats.put(uid, uidStats);
4186 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004187 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004189 bs = new BroadcastStats(uid, pkgName);
4190 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 }
4192 return bs;
4193 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004194
Christopher Tate21e9f192017-08-08 13:49:11 -07004195 /**
4196 * Canonical count of (operation.send() - onSendFinished()) and
4197 * listener send/complete/timeout invocations.
4198 * Guarded by the usual lock.
4199 */
4200 @GuardedBy("mLock")
4201 private int mSendCount = 0;
4202 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004203 private int mSendFinishCount = 0;
4204 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004205 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004206 @GuardedBy("mLock")
4207 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004208
Christopher Tate14a7bb02015-10-01 10:24:31 -07004209 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004210
Christopher Tate14a7bb02015-10-01 10:24:31 -07004211 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4212 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004213 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004214 return mInFlight.remove(i);
4215 }
4216 }
4217 mLog.w("No in-flight alarm for " + pi + " " + intent);
4218 return null;
4219 }
4220
4221 private InFlight removeLocked(IBinder listener) {
4222 for (int i = 0; i < mInFlight.size(); i++) {
4223 if (mInFlight.get(i).mListener == listener) {
4224 return mInFlight.remove(i);
4225 }
4226 }
4227 mLog.w("No in-flight alarm for listener " + listener);
4228 return null;
4229 }
4230
4231 private void updateStatsLocked(InFlight inflight) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004232 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004233 BroadcastStats bs = inflight.mBroadcastStats;
4234 bs.nesting--;
4235 if (bs.nesting <= 0) {
4236 bs.nesting = 0;
4237 bs.aggregateTime += nowELAPSED - bs.startTime;
4238 }
4239 FilterStats fs = inflight.mFilterStats;
4240 fs.nesting--;
4241 if (fs.nesting <= 0) {
4242 fs.nesting = 0;
4243 fs.aggregateTime += nowELAPSED - fs.startTime;
4244 }
4245 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004246 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4247 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004248 }
4249 }
4250
4251 private void updateTrackingLocked(InFlight inflight) {
4252 if (inflight != null) {
4253 updateStatsLocked(inflight);
4254 }
4255 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004256 if (DEBUG_WAKELOCK) {
4257 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4258 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004259 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004260 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004261 mWakeLock.release();
4262 if (mInFlight.size() > 0) {
4263 mLog.w("Finished all dispatches with " + mInFlight.size()
4264 + " remaining inflights");
4265 for (int i=0; i<mInFlight.size(); i++) {
4266 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4267 }
4268 mInFlight.clear();
4269 }
4270 } else {
4271 // the next of our alarms is now in flight. reattribute the wakelock.
4272 if (mInFlight.size() > 0) {
4273 InFlight inFlight = mInFlight.get(0);
4274 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4275 inFlight.mAlarmType, inFlight.mTag, -1, false);
4276 } else {
4277 // should never happen
4278 mLog.w("Alarm wakelock still held but sent queue empty");
4279 mWakeLock.setWorkSource(null);
4280 }
4281 }
4282 }
4283
4284 /**
4285 * Callback that arrives when a direct-call alarm reports that delivery has finished
4286 */
4287 @Override
4288 public void alarmComplete(IBinder who) {
4289 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004290 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004291 + " pid=" + Binder.getCallingPid());
4292 return;
4293 }
4294
4295 final long ident = Binder.clearCallingIdentity();
4296 try {
4297 synchronized (mLock) {
4298 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4299 InFlight inflight = removeLocked(who);
4300 if (inflight != null) {
4301 if (DEBUG_LISTENER_CALLBACK) {
4302 Slog.i(TAG, "alarmComplete() from " + who);
4303 }
4304 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004305 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004306 } else {
4307 // Delivery timed out, and the timeout handling already took care of
4308 // updating our tracking here, so we needn't do anything further.
4309 if (DEBUG_LISTENER_CALLBACK) {
4310 Slog.i(TAG, "Late alarmComplete() from " + who);
4311 }
4312 }
4313 }
4314 } finally {
4315 Binder.restoreCallingIdentity(ident);
4316 }
4317 }
4318
4319 /**
4320 * Callback that arrives when a PendingIntent alarm has finished delivery
4321 */
4322 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004323 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4324 String resultData, Bundle resultExtras) {
4325 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004326 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004327 updateTrackingLocked(removeLocked(pi, intent));
4328 }
4329 }
4330
4331 /**
4332 * Timeout of a direct-call alarm delivery
4333 */
4334 public void alarmTimedOut(IBinder who) {
4335 synchronized (mLock) {
4336 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004337 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004338 // TODO: implement ANR policy for the target
4339 if (DEBUG_LISTENER_CALLBACK) {
4340 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004342 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004343 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004344 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004345 if (DEBUG_LISTENER_CALLBACK) {
4346 Slog.i(TAG, "Spurious timeout of listener " + who);
4347 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004348 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004350 }
4351 }
4352
4353 /**
4354 * Deliver an alarm and set up the post-delivery handling appropriately
4355 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004356 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004357 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4358 if (alarm.operation != null) {
4359 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004360 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004361
Christopher Tate14a7bb02015-10-01 10:24:31 -07004362 try {
4363 alarm.operation.send(getContext(), 0,
4364 mBackgroundIntent.putExtra(
4365 Intent.EXTRA_ALARM_COUNT, alarm.count),
4366 mDeliveryTracker, mHandler, null,
4367 allowWhileIdle ? mIdleOptions : null);
4368 } catch (PendingIntent.CanceledException e) {
4369 if (alarm.repeatInterval > 0) {
4370 // This IntentSender is no longer valid, but this
4371 // is a repeating alarm, so toss it
Christopher Tatec8b7f432018-09-28 16:23:10 -07004372 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004373 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004374 // No actual delivery was possible, so the delivery tracker's
4375 // 'finished' callback won't be invoked. We also don't need
4376 // to do any wakelock or stats tracking, so we have nothing
4377 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004378 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004379 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004380 }
4381 } else {
4382 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004383 mListenerCount++;
Christopher Tatec8b7f432018-09-28 16:23:10 -07004384
4385 if (RECORD_ALARMS_IN_HISTORY) {
4386 if (alarm.listener == mTimeTickTrigger) {
4387 mTickHistory[mNextTickHistory++] = nowELAPSED;
4388 if (mNextTickHistory >= TICK_HISTORY_DEPTH) {
4389 mNextTickHistory = 0;
4390 }
4391 }
4392 }
4393
Christopher Tate14a7bb02015-10-01 10:24:31 -07004394 try {
4395 if (DEBUG_LISTENER_CALLBACK) {
4396 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4397 + " listener=" + alarm.listener.asBinder());
4398 }
4399 alarm.listener.doAlarm(this);
4400 mHandler.sendMessageDelayed(
4401 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4402 alarm.listener.asBinder()),
4403 mConstants.LISTENER_TIMEOUT);
4404 } catch (Exception e) {
4405 if (DEBUG_LISTENER_CALLBACK) {
4406 Slog.i(TAG, "Alarm undeliverable to listener "
4407 + alarm.listener.asBinder(), e);
4408 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004409 // As in the PendingIntent.CanceledException case, delivery of the
4410 // alarm was not possible, so we have no wakelock or timeout or
4411 // stats management to do. It threw before we posted the delayed
4412 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004413 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004414 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004415 }
4416 }
4417
4418 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004419 if (DEBUG_WAKELOCK) {
4420 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4421 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004422 if (mBroadcastRefCount == 0) {
4423 setWakelockWorkSource(alarm.operation, alarm.workSource,
4424 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4425 true);
4426 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004427 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004428 }
4429 final InFlight inflight = new InFlight(AlarmManagerService.this,
4430 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4431 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4432 mInFlight.add(inflight);
4433 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004434 if (allowWhileIdle) {
4435 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004436 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004437 if ((mAppStateTracker == null)
4438 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004439 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4440 } else {
4441 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4442 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004443 if (RECORD_DEVICE_IDLE_ALARMS) {
4444 IdleDispatchEntry ent = new IdleDispatchEntry();
4445 ent.uid = alarm.uid;
4446 ent.pkg = alarm.packageName;
4447 ent.tag = alarm.statsTag;
4448 ent.op = "DELIVER";
4449 ent.elapsedRealtime = nowELAPSED;
4450 mAllowWhileIdleDispatches.add(ent);
4451 }
4452 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004453 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004454 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4455 UserHandle.getUserId(alarm.creatorUid));
4456 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4457 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004458
4459 final BroadcastStats bs = inflight.mBroadcastStats;
4460 bs.count++;
4461 if (bs.nesting == 0) {
4462 bs.nesting = 1;
4463 bs.startTime = nowELAPSED;
4464 } else {
4465 bs.nesting++;
4466 }
4467 final FilterStats fs = inflight.mFilterStats;
4468 fs.count++;
4469 if (fs.nesting == 0) {
4470 fs.nesting = 1;
4471 fs.startTime = nowELAPSED;
4472 } else {
4473 fs.nesting++;
4474 }
4475 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4476 || alarm.type == RTC_WAKEUP) {
4477 bs.numWakeup++;
4478 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004479 ActivityManager.noteWakeupAlarm(
4480 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4481 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 }
4483 }
4484 }
mswest463f4c99d2018-02-01 10:13:10 -08004485
4486 private class ShellCmd extends ShellCommand {
4487
4488 IAlarmManager getBinderService() {
4489 return IAlarmManager.Stub.asInterface(mService);
4490 }
4491
4492 @Override
4493 public int onCommand(String cmd) {
4494 if (cmd == null) {
4495 return handleDefaultCommands(cmd);
4496 }
4497
4498 final PrintWriter pw = getOutPrintWriter();
4499 try {
4500 switch (cmd) {
4501 case "set-time":
4502 final long millis = Long.parseLong(getNextArgRequired());
4503 return (getBinderService().setTime(millis)) ? 0 : -1;
4504 case "set-timezone":
4505 final String tz = getNextArgRequired();
4506 getBinderService().setTimeZone(tz);
4507 return 0;
4508 default:
4509 return handleDefaultCommands(cmd);
4510 }
4511 } catch (Exception e) {
4512 pw.println(e);
4513 }
4514 return -1;
4515 }
4516
4517 @Override
4518 public void onHelp() {
4519 PrintWriter pw = getOutPrintWriter();
4520 pw.println("Alarm manager service (alarm) commands:");
4521 pw.println(" help");
4522 pw.println(" Print this help text.");
4523 pw.println(" set-time TIME");
4524 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4525 pw.println(" since the Epoch.");
4526 pw.println(" set-timezone TZ");
4527 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4528 }
4529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530}