blob: 9d71896ef08b13d6951d01c0a733a3256bd35865 [file] [log] [blame]
Dianne Hackborn7299c412010-03-04 18:41:49 -08001/*
2 * Copyright (C) 2008 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
Tyler Gunnf05f2c22019-09-30 15:12:24 -070019import android.annotation.IntRange;
Justin Klaassen908b86c2016-08-08 09:18:42 -070020import android.annotation.Nullable;
Dianne Hackborn7299c412010-03-04 18:41:49 -080021import android.app.Activity;
Jeff Brown62c82e42012-09-26 01:30:41 -070022import android.app.ActivityManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070023import android.app.ActivityTaskManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080024import android.app.IUiModeManager;
25import android.app.Notification;
26import android.app.NotificationManager;
27import android.app.PendingIntent;
28import android.app.StatusBarManager;
29import android.app.UiModeManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080030import android.content.BroadcastReceiver;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
35import android.content.res.Configuration;
Alan Viverette4cc1e9e2015-02-12 11:01:06 -080036import android.content.res.Resources;
Salvador Martinezc500b272019-05-02 14:32:12 -070037import android.database.ContentObserver;
38import android.net.Uri;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050039import android.os.BatteryManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -080040import android.os.Binder;
Dianne Hackborn7299c412010-03-04 18:41:49 -080041import android.os.Handler;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050042import android.os.PowerManager;
Kweku Adams4db6a3c2019-02-04 16:06:13 -080043import android.os.PowerManager.ServiceType;
44import android.os.PowerManagerInternal;
Tyler Gunnf05f2c22019-09-30 15:12:24 -070045import android.os.Process;
Dianne Hackborn7299c412010-03-04 18:41:49 -080046import android.os.RemoteException;
Alan Viveretteba0d98f2017-01-30 10:36:54 -050047import android.os.ResultReceiver;
Zak Cohen1a705732017-01-09 12:54:34 -080048import android.os.ServiceManager;
Alan Viveretteba0d98f2017-01-30 10:36:54 -050049import android.os.ShellCallback;
50import android.os.ShellCommand;
Beverly28e48fb2019-06-14 14:53:09 -040051import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070052import android.os.UserHandle;
Salvador Martinezc500b272019-05-02 14:32:12 -070053import android.provider.Settings.Secure;
Jeff Brown11159e92012-10-11 15:58:37 -070054import android.service.dreams.Sandman;
Zak Cohen1a705732017-01-09 12:54:34 -080055import android.service.vr.IVrManager;
56import android.service.vr.IVrStateCallbacks;
Tyler Gunnf05f2c22019-09-30 15:12:24 -070057import android.util.ArraySet;
Dianne Hackborn7299c412010-03-04 18:41:49 -080058import android.util.Slog;
59
Dianne Hackborn7299c412010-03-04 18:41:49 -080060import com.android.internal.R;
61import com.android.internal.app.DisableCarModeActivity;
Chris Wren282cfef2017-03-27 15:01:44 -040062import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050063import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060064import com.android.internal.util.DumpUtils;
Adam Lesinski182f73f2013-12-05 16:48:06 -080065import com.android.server.twilight.TwilightListener;
66import com.android.server.twilight.TwilightManager;
67import com.android.server.twilight.TwilightState;
Dianne Hackborn7299c412010-03-04 18:41:49 -080068
Lucas Dupinb1f0c762018-09-18 10:33:38 -070069import java.io.FileDescriptor;
70import java.io.PrintWriter;
Tyler Gunnf05f2c22019-09-30 15:12:24 -070071import java.util.HashMap;
72import java.util.Map;
73import java.util.Set;
Lucas Dupinb1f0c762018-09-18 10:33:38 -070074
Adam Lesinski182f73f2013-12-05 16:48:06 -080075final class UiModeManagerService extends SystemService {
Dianne Hackborn7299c412010-03-04 18:41:49 -080076 private static final String TAG = UiModeManager.class.getSimpleName();
77 private static final boolean LOG = false;
78
Daniel Sandler11ddf532011-11-16 11:10:03 -080079 // Enable launching of applications when entering the dock.
John Spurlock960779d2012-05-29 14:37:05 -040080 private static final boolean ENABLE_LAUNCH_DESK_DOCK_APP = true;
Beverly28e48fb2019-06-14 14:53:09 -040081 private static final String SYSTEM_PROPERTY_DEVICE_THEME = "persist.sys.theme";
Daniel Sandler11ddf532011-11-16 11:10:03 -080082
Dianne Hackborn7299c412010-03-04 18:41:49 -080083 final Object mLock = new Object();
Dianne Hackborn7299c412010-03-04 18:41:49 -080084 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010085
Adam Lesinski182f73f2013-12-05 16:48:06 -080086 private int mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
Alan Viverette4cc1e9e2015-02-12 11:01:06 -080087 private int mNightMode = UiModeManager.MODE_NIGHT_NO;
Adam Lesinski182f73f2013-12-05 16:48:06 -080088
Tyler Gunnf05f2c22019-09-30 15:12:24 -070089 private Map<Integer, String> mCarModePackagePriority = new HashMap<>();
Dianne Hackborn7299c412010-03-04 18:41:49 -080090 private boolean mCarModeEnabled = false;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050091 private boolean mCharging = false;
Lucas Dupin53c6e292018-07-12 18:42:53 -070092 private boolean mPowerSave = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -080093 private int mDefaultUiModeType;
94 private boolean mCarModeKeepsScreenOn;
95 private boolean mDeskModeKeepsScreenOn;
96 private boolean mTelevision;
John Spurlock6c191292014-04-03 16:37:27 -040097 private boolean mWatch;
Zak Cohen1a705732017-01-09 12:54:34 -080098 private boolean mVrHeadset;
Dianne Hackborn7299c412010-03-04 18:41:49 -080099 private boolean mComputedNightMode;
keunyoung1d0a7cc2014-07-28 13:12:50 -0700100 private int mCarModeEnableFlags;
Salvador Martinezc500b272019-05-02 14:32:12 -0700101 private boolean mSetupWizardComplete;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800102
keunyounga7710492015-09-23 11:33:58 -0700103 // flag set by resource, whether to enable Car dock launch when starting car mode.
104 private boolean mEnableCarDockLaunch = true;
105 // flag set by resource, whether to lock UI mode to the default one or not.
106 private boolean mUiModeLocked = false;
107 // flag set by resource, whether to night mode change for normal all or not.
108 private boolean mNightModeLocked = false;
109
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 int mCurUiMode = 0;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800111 private int mSetUiMode = 0;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800112 private boolean mHoldingConfiguration = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113
Dianne Hackborn7299c412010-03-04 18:41:49 -0800114 private Configuration mConfiguration = new Configuration();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 boolean mSystemReady;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100116
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 private final Handler mHandler = new Handler();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800118
Adam Lesinski182f73f2013-12-05 16:48:06 -0800119 private TwilightManager mTwilightManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800120 private NotificationManager mNotificationManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800121 private StatusBarManager mStatusBarManager;
Jeff Brown9fca9e92012-10-05 14:42:56 -0700122
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 private PowerManager.WakeLock mWakeLock;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800124
Felipe Lemeff9ec382018-09-24 11:07:56 -0700125 private final LocalService mLocalService = new LocalService();
126
Jeff Brownb880d882014-02-10 19:47:07 -0800127 public UiModeManagerService(Context context) {
128 super(context);
129 }
130
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 private static Intent buildHomeIntent(String category) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700132 Intent intent = new Intent(Intent.ACTION_MAIN);
133 intent.addCategory(category);
134 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
135 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
136 return intent;
137 }
John Spurlock960779d2012-05-29 14:37:05 -0400138
Dianne Hackborn7299c412010-03-04 18:41:49 -0800139 // The broadcast receiver which receives the result of the ordered broadcast sent when
140 // the dock state changes. The original ordered broadcast is sent with an initial result
141 // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
142 // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
143 private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
144 @Override
145 public void onReceive(Context context, Intent intent) {
146 if (getResultCode() != Activity.RESULT_OK) {
Daniel Sandler69a1da42011-11-04 15:08:30 -0400147 if (LOG) {
John Spurlock960779d2012-05-29 14:37:05 -0400148 Slog.v(TAG, "Handling broadcast result for action " + intent.getAction()
Daniel Sandler69a1da42011-11-04 15:08:30 -0400149 + ": canceled: " + getResultCode());
150 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800151 return;
152 }
153
Jeff Brown62c82e42012-09-26 01:30:41 -0700154 final int enableFlags = intent.getIntExtra("enableFlags", 0);
155 final int disableFlags = intent.getIntExtra("disableFlags", 0);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800156 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -0700157 updateAfterBroadcastLocked(intent.getAction(), enableFlags, disableFlags);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800158 }
159 }
160 };
161
Dianne Hackborn7299c412010-03-04 18:41:49 -0800162 private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
163 @Override
164 public void onReceive(Context context, Intent intent) {
165 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
166 Intent.EXTRA_DOCK_STATE_UNDOCKED);
167 updateDockState(state);
168 }
169 };
170
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500171 private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
172 @Override
173 public void onReceive(Context context, Intent intent) {
Lucas Dupin53c6e292018-07-12 18:42:53 -0700174 switch (intent.getAction()) {
175 case Intent.ACTION_BATTERY_CHANGED:
176 mCharging = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
177 break;
Lucas Dupin53c6e292018-07-12 18:42:53 -0700178 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500179 synchronized (mLock) {
180 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700181 updateLocked(0, 0);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500182 }
183 }
184 }
185 };
186
Adam Lesinski182f73f2013-12-05 16:48:06 -0800187 private final TwilightListener mTwilightListener = new TwilightListener() {
Dianne Hackborn57f45032010-06-17 15:49:33 -0700188 @Override
Justin Klaassen908b86c2016-08-08 09:18:42 -0700189 public void onTwilightStateChanged(@Nullable TwilightState state) {
190 synchronized (mLock) {
191 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
192 updateComputedNightModeLocked();
193 updateLocked(0, 0);
194 }
195 }
Dianne Hackborn57f45032010-06-17 15:49:33 -0700196 }
197 };
198
Zak Cohen1a705732017-01-09 12:54:34 -0800199 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
200 @Override
201 public void onVrStateChanged(boolean enabled) {
202 synchronized (mLock) {
203 mVrHeadset = enabled;
204 if (mSystemReady) {
205 updateLocked(0, 0);
206 }
207 }
208 }
209 };
210
Salvador Martinezc500b272019-05-02 14:32:12 -0700211 private final ContentObserver mSetupWizardObserver = new ContentObserver(mHandler) {
212 @Override
213 public void onChange(boolean selfChange, Uri uri) {
214 // setup wizard is done now so we can unblock
215 if (setupWizardCompleteForCurrentUser()) {
216 mSetupWizardComplete = true;
217 getContext().getContentResolver().unregisterContentObserver(mSetupWizardObserver);
218 // update night mode
219 Context context = getContext();
220 updateNightModeFromSettings(context, context.getResources(),
221 UserHandle.getCallingUserId());
222 updateLocked(0, 0);
223 }
224 }
225 };
226
Beverly470d8052019-07-22 17:15:58 -0400227 private final ContentObserver mDarkThemeObserver = new ContentObserver(mHandler) {
228 @Override
229 public void onChange(boolean selfChange, Uri uri) {
230 final int mode = Secure.getIntForUser(getContext().getContentResolver(),
231 Secure.UI_NIGHT_MODE, mNightMode, 0);
232 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_THEME, Integer.toString(mode));
233 }
234 };
235
Salvador Martinezc500b272019-05-02 14:32:12 -0700236 @Override
237 public void onSwitchUser(int userHandle) {
238 super.onSwitchUser(userHandle);
239 getContext().getContentResolver().unregisterContentObserver(mSetupWizardObserver);
240 verifySetupWizardCompleted();
241 }
242
Adam Lesinski182f73f2013-12-05 16:48:06 -0800243 @Override
244 public void onStart() {
245 final Context context = getContext();
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800246
Adam Lesinski182f73f2013-12-05 16:48:06 -0800247 final PowerManager powerManager =
248 (PowerManager) context.getSystemService(Context.POWER_SERVICE);
249 mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800250
Salvador Martinezc500b272019-05-02 14:32:12 -0700251 // If setup isn't complete for this user listen for completion so we can unblock
252 // being able to send a night mode configuration change event
253 verifySetupWizardCompleted();
254
Adam Lesinski182f73f2013-12-05 16:48:06 -0800255 context.registerReceiver(mDockModeReceiver,
Dianne Hackborn7299c412010-03-04 18:41:49 -0800256 new IntentFilter(Intent.ACTION_DOCK_EVENT));
Lucas Dupin53c6e292018-07-12 18:42:53 -0700257 IntentFilter batteryFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Lucas Dupin53c6e292018-07-12 18:42:53 -0700258 context.registerReceiver(mBatteryReceiver, batteryFilter);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500259
Kweku Adams4db6a3c2019-02-04 16:06:13 -0800260 PowerManagerInternal localPowerManager =
261 LocalServices.getService(PowerManagerInternal.class);
262 mPowerSave = localPowerManager.getLowPowerState(ServiceType.NIGHT_MODE).batterySaverEnabled;
263 localPowerManager.registerLowPowerModeObserver(ServiceType.NIGHT_MODE,
264 state -> {
265 synchronized (mLock) {
266 if (mPowerSave == state.batterySaverEnabled) {
267 return;
268 }
269 mPowerSave = state.batterySaverEnabled;
270 if (mSystemReady) {
271 updateLocked(0, 0);
272 }
273 }
274 });
275
Dianne Hackborn7299c412010-03-04 18:41:49 -0800276 mConfiguration.setToDefaults();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500277
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800278 final Resources res = context.getResources();
279 mDefaultUiModeType = res.getInteger(
Joe Onorato44fcb832011-12-14 20:59:30 -0800280 com.android.internal.R.integer.config_defaultUiModeType);
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800281 mCarModeKeepsScreenOn = (res.getInteger(
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500282 com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800283 mDeskModeKeepsScreenOn = (res.getInteger(
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500284 com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
keunyounga7710492015-09-23 11:33:58 -0700285 mEnableCarDockLaunch = res.getBoolean(
286 com.android.internal.R.bool.config_enableCarDockHomeLaunch);
287 mUiModeLocked = res.getBoolean(com.android.internal.R.bool.config_lockUiMode);
288 mNightModeLocked = res.getBoolean(com.android.internal.R.bool.config_lockDayNightMode);
Dianne Hackborn0cf2c8a2012-05-17 17:29:49 -0700289
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800290 final PackageManager pm = context.getPackageManager();
291 mTelevision = pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
292 || pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK);
293 mWatch = pm.hasSystemFeature(PackageManager.FEATURE_WATCH);
294
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700295 updateNightModeFromSettings(context, res, UserHandle.getCallingUserId());
Jeff Brown2416e092012-08-21 22:12:20 -0700296
Adam Lesinski05199e82015-03-19 14:37:11 -0700297 // Update the initial, static configurations.
Fyodor Kupolove29a5a12016-12-16 16:14:17 -0800298 SystemServerInitThreadPool.get().submit(() -> {
299 synchronized (mLock) {
300 updateConfigurationLocked();
301 sendConfigurationLocked();
302 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800303
Fyodor Kupolove29a5a12016-12-16 16:14:17 -0800304 }, TAG + ".onStart");
Adam Lesinski182f73f2013-12-05 16:48:06 -0800305 publishBinderService(Context.UI_MODE_SERVICE, mService);
Felipe Lemeff9ec382018-09-24 11:07:56 -0700306 publishLocalService(UiModeManagerInternal.class, mLocalService);
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700307
308 IntentFilter filter = new IntentFilter();
309 filter.addAction(Intent.ACTION_USER_SWITCHED);
310 context.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
Beverly470d8052019-07-22 17:15:58 -0400311
312 context.getContentResolver().registerContentObserver(Secure.getUriFor(Secure.UI_NIGHT_MODE),
313 false, mDarkThemeObserver, 0);
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700314 }
315
Salvador Martinezc500b272019-05-02 14:32:12 -0700316 // Records whether setup wizard has happened or not and adds an observer for this user if not.
317 private void verifySetupWizardCompleted() {
318 final Context context = getContext();
319 final int userId = UserHandle.getCallingUserId();
320 if (!setupWizardCompleteForCurrentUser()) {
321 mSetupWizardComplete = false;
322 context.getContentResolver().registerContentObserver(
323 Secure.getUriFor(
324 Secure.USER_SETUP_COMPLETE), false, mSetupWizardObserver, userId);
325 } else {
326 mSetupWizardComplete = true;
327 }
328 }
329
330 private boolean setupWizardCompleteForCurrentUser() {
331 return Secure.getIntForUser(getContext().getContentResolver(),
332 Secure.USER_SETUP_COMPLETE, 0, UserHandle.getCallingUserId()) == 1;
333 }
334
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700335 /**
336 * Updates the night mode setting in Settings.Global and returns if the value was successfully
337 * changed.
338 * @param context A valid context
339 * @param res A valid resource object
340 * @param userId The user to update the setting for
341 * @return True if the new value is different from the old value. False otherwise.
342 */
343 private boolean updateNightModeFromSettings(Context context, Resources res, int userId) {
344 final int defaultNightMode = res.getInteger(
345 com.android.internal.R.integer.config_defaultNightMode);
346 int oldNightMode = mNightMode;
Salvador Martinezc500b272019-05-02 14:32:12 -0700347 if (mSetupWizardComplete) {
348 mNightMode = Secure.getIntForUser(context.getContentResolver(),
349 Secure.UI_NIGHT_MODE, defaultNightMode, userId);
350 } else {
351 mNightMode = defaultNightMode;
352 }
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700353
Beverly28e48fb2019-06-14 14:53:09 -0400354 return oldNightMode != mNightMode;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800355 }
356
Alan Viveretteba0d98f2017-01-30 10:36:54 -0500357 private final IUiModeManager.Stub mService = new IUiModeManager.Stub() {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800358 @Override
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700359 public void enableCarMode(@UiModeManager.EnableCarMode int flags,
360 @IntRange(from = 0) int priority, String callingPackage) {
keunyounga7710492015-09-23 11:33:58 -0700361 if (isUiModeLocked()) {
362 Slog.e(TAG, "enableCarMode while UI mode is locked");
363 return;
364 }
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700365
366 if (priority != UiModeManager.DEFAULT_PRIORITY
367 && getContext().checkCallingOrSelfPermission(
368 android.Manifest.permission.ENTER_CAR_MODE_PRIORITIZED)
369 != PackageManager.PERMISSION_GRANTED) {
370 throw new SecurityException("Enabling car mode with a priority requires "
371 + "permission ENTER_CAR_MODE_PRIORITIZED");
372 }
373
Adam Lesinski182f73f2013-12-05 16:48:06 -0800374 final long ident = Binder.clearCallingIdentity();
375 try {
376 synchronized (mLock) {
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700377 setCarModeLocked(true, flags, priority, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800378 if (mSystemReady) {
379 updateLocked(flags, 0);
380 }
Jeff Brown487bb6e2012-10-11 13:35:42 -0700381 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800382 } finally {
383 Binder.restoreCallingIdentity(ident);
Mike Lockwood924e1642010-03-05 11:56:53 -0500384 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800385 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800386
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700387 /**
388 * This method is only kept around for the time being; the AIDL has an UnsupportedAppUsage
389 * tag which means this method is technically considered part of the greylist "API".
390 * @param flags
391 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800392 @Override
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700393 public void disableCarMode(@UiModeManager.DisableCarMode int flags) {
394 disableCarModeByCallingPackage(flags, null /* callingPackage */);
395 }
396
397 /**
398 * Handles requests to disable car mode.
399 * @param flags Disable car mode flags
400 * @param callingPackage
401 */
402 @Override
403 public void disableCarModeByCallingPackage(@UiModeManager.DisableCarMode int flags,
404 String callingPackage) {
keunyounga7710492015-09-23 11:33:58 -0700405 if (isUiModeLocked()) {
406 Slog.e(TAG, "disableCarMode while UI mode is locked");
407 return;
408 }
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700409
410 // If the caller is the system, we will allow the DISABLE_CAR_MODE_ALL_PRIORITIES car
411 // mode flag to be specified; this is so that the user can disable car mode at all
412 // priorities using the persistent notification.
413 boolean isSystemCaller = Binder.getCallingUid() == Process.SYSTEM_UID;
414 final int carModeFlags =
415 isSystemCaller ? flags : flags & ~UiModeManager.DISABLE_CAR_MODE_ALL_PRIORITIES;
416
Adam Lesinski182f73f2013-12-05 16:48:06 -0800417 final long ident = Binder.clearCallingIdentity();
418 try {
419 synchronized (mLock) {
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700420 // Determine if the caller has enabled car mode at a priority other than the
421 // default one. If they have, then attempt to disable at that priority.
422 int priority = mCarModePackagePriority.entrySet()
423 .stream()
424 .filter(e -> e.getValue().equals(callingPackage))
425 .findFirst()
426 .map(Map.Entry::getKey)
427 .orElse(UiModeManager.DEFAULT_PRIORITY);
428
429 setCarModeLocked(false, carModeFlags, priority, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800430 if (mSystemReady) {
431 updateLocked(0, flags);
432 }
Jeff Brown487bb6e2012-10-11 13:35:42 -0700433 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800434 } finally {
435 Binder.restoreCallingIdentity(ident);
Mike Lockwood924e1642010-03-05 11:56:53 -0500436 }
Jeff Brown487bb6e2012-10-11 13:35:42 -0700437 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100438
Adam Lesinski182f73f2013-12-05 16:48:06 -0800439 @Override
440 public int getCurrentModeType() {
441 final long ident = Binder.clearCallingIdentity();
442 try {
443 synchronized (mLock) {
444 return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
Jeff Brown487bb6e2012-10-11 13:35:42 -0700445 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800446 } finally {
447 Binder.restoreCallingIdentity(ident);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800448 }
449 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100450
Adam Lesinski182f73f2013-12-05 16:48:06 -0800451 @Override
452 public void setNightMode(int mode) {
Lucas Dupinc5aaf452018-09-20 16:10:07 -0700453 if (isNightModeLocked() && (getContext().checkCallingOrSelfPermission(
keunyounga7710492015-09-23 11:33:58 -0700454 android.Manifest.permission.MODIFY_DAY_NIGHT_MODE)
455 != PackageManager.PERMISSION_GRANTED)) {
Lucas Dupinc5aaf452018-09-20 16:10:07 -0700456 Slog.e(TAG, "Night mode locked, requires MODIFY_DAY_NIGHT_MODE permission");
keunyounga7710492015-09-23 11:33:58 -0700457 return;
458 }
Salvador Martinezc500b272019-05-02 14:32:12 -0700459 if (!mSetupWizardComplete) {
460 Slog.d(TAG, "Night mode cannot be changed before setup wizard completes.");
461 return;
462 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800463 switch (mode) {
464 case UiModeManager.MODE_NIGHT_NO:
465 case UiModeManager.MODE_NIGHT_YES:
466 case UiModeManager.MODE_NIGHT_AUTO:
467 break;
468 default:
469 throw new IllegalArgumentException("Unknown mode: " + mode);
470 }
471
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700472 final int user = UserHandle.getCallingUserId();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800473 final long ident = Binder.clearCallingIdentity();
474 try {
475 synchronized (mLock) {
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800476 if (mNightMode != mode) {
Winson3f5ad732019-03-04 15:21:04 -0800477 // Only persist setting if not in car mode
478 if (!mCarModeEnabled) {
Salvador Martinezc500b272019-05-02 14:32:12 -0700479 Secure.putIntForUser(getContext().getContentResolver(),
480 Secure.UI_NIGHT_MODE, mode, user);
Winsonadc69672019-01-28 14:56:12 -0800481 }
482
Adam Lesinski182f73f2013-12-05 16:48:06 -0800483 mNightMode = mode;
484 updateLocked(0, 0);
485 }
486 }
487 } finally {
488 Binder.restoreCallingIdentity(ident);
489 }
490 }
491
492 @Override
493 public int getNightMode() {
494 synchronized (mLock) {
495 return mNightMode;
496 }
497 }
498
499 @Override
keunyounga7710492015-09-23 11:33:58 -0700500 public boolean isUiModeLocked() {
501 synchronized (mLock) {
502 return mUiModeLocked;
503 }
504 }
505
506 @Override
507 public boolean isNightModeLocked() {
508 synchronized (mLock) {
509 return mNightModeLocked;
510 }
511 }
512
513 @Override
Alan Viveretteba0d98f2017-01-30 10:36:54 -0500514 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
515 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
516 new Shell(mService).exec(mService, in, out, err, args, callback, resultReceiver);
517 }
518
519 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -0800520 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600521 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800522 dumpImpl(pw);
523 }
524 };
525
526 void dumpImpl(PrintWriter pw) {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700527 synchronized (mLock) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800528 pw.println("Current UI Mode Service state:");
529 pw.print(" mDockState="); pw.print(mDockState);
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700530 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
531
Felipe Lemeff9ec382018-09-24 11:07:56 -0700532 pw.print(" mNightMode="); pw.print(mNightMode); pw.print(" (");
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700533 pw.print(Shell.nightModeToStr(mNightMode)); pw.print(") ");
534 pw.print(" mNightModeLocked="); pw.println(mNightModeLocked);
535
536 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
537 pw.print(" (carModeApps=");
538 for (Map.Entry<Integer, String> entry : mCarModePackagePriority.entrySet()) {
539 pw.print(entry.getKey());
540 pw.print(":");
541 pw.print(entry.getValue());
542 pw.print(" ");
543 }
544 pw.println("");
545 pw.print(" mComputedNightMode="); pw.print(mComputedNightMode);
546 pw.print(" mCarModeEnableFlags="); pw.print(mCarModeEnableFlags);
547 pw.print(" mEnableCarDockLaunch="); pw.println(mEnableCarDockLaunch);
548
Adam Lesinski182f73f2013-12-05 16:48:06 -0800549 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700550 pw.print(" mUiModeLocked="); pw.print(mUiModeLocked);
551 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
552
Adam Lesinski182f73f2013-12-05 16:48:06 -0800553 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700554 pw.print(" mSystemReady="); pw.println(mSystemReady);
555
Adam Lesinski05199e82015-03-19 14:37:11 -0700556 if (mTwilightManager != null) {
557 // We may not have a TwilightManager.
Justin Klaassen908b86c2016-08-08 09:18:42 -0700558 pw.print(" mTwilightService.getLastTwilightState()=");
559 pw.println(mTwilightManager.getLastTwilightState());
Adam Lesinski05199e82015-03-19 14:37:11 -0700560 }
Jeff Brown487bb6e2012-10-11 13:35:42 -0700561 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800562 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100563
Adam Lesinski182f73f2013-12-05 16:48:06 -0800564 @Override
565 public void onBootPhase(int phase) {
566 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
567 synchronized (mLock) {
Adam Lesinski05199e82015-03-19 14:37:11 -0700568 mTwilightManager = getLocalService(TwilightManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800569 mSystemReady = true;
570 mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
571 updateComputedNightModeLocked();
Zak Cohen1a705732017-01-09 12:54:34 -0800572 registerVrStateListener();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800573 updateLocked(0, 0);
574 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800575 }
576 }
577
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700578 /**
579 * Updates the global car mode state.
580 * The device is considered to be in car mode if there exists an app at any priority level which
581 * has entered car mode.
582 *
583 * @param enabled {@code true} if the caller wishes to enable car mode, {@code false} otherwise.
584 * @param flags Flags used when enabling/disabling car mode.
585 * @param priority The priority level for entering or exiting car mode; defaults to
586 * {@link UiModeManager#DEFAULT_PRIORITY} for callers using
587 * {@link UiModeManager#enableCarMode(int)}. Callers using
588 * {@link UiModeManager#enableCarMode(int, int)} may specify a priority.
589 * @param packageName The package name of the app which initiated the request to enable or
590 * disable car mode.
591 */
592 void setCarModeLocked(boolean enabled, int flags, int priority, String packageName) {
593 if (enabled) {
594 enableCarMode(priority, packageName);
595 } else {
596 disableCarMode(flags, priority, packageName);
597 }
598 boolean isCarModeNowEnabled = isCarModeEnabled();
Winsonadc69672019-01-28 14:56:12 -0800599
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700600 if (mCarModeEnabled != isCarModeNowEnabled) {
601 mCarModeEnabled = isCarModeNowEnabled;
Winson3f5ad732019-03-04 15:21:04 -0800602 // When exiting car mode, restore night mode from settings
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700603 if (!isCarModeNowEnabled) {
Winsonadc69672019-01-28 14:56:12 -0800604 Context context = getContext();
605 updateNightModeFromSettings(context,
606 context.getResources(),
607 UserHandle.getCallingUserId());
608 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800609 }
keunyoung1d0a7cc2014-07-28 13:12:50 -0700610 mCarModeEnableFlags = flags;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800611 }
612
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700613 /**
614 * Handles disabling car mode.
615 * <p>
616 * Car mode can be disabled at a priority level if any of the following is true:
617 * 1. The priority being disabled is the {@link UiModeManager#DEFAULT_PRIORITY}.
618 * 2. The priority level is enabled and the caller is the app who originally enabled it.
619 * 3. The {@link UiModeManager#DISABLE_CAR_MODE_ALL_PRIORITIES} flag was specified, meaning all
620 * car mode priorities are disabled.
621 *
622 * @param flags Car mode flags.
623 * @param priority The priority level at which to disable car mode.
624 * @param packageName The calling package which initiated the request.
625 */
626 private void disableCarMode(int flags, int priority, String packageName) {
627 boolean isDisableAll = (flags & UiModeManager.DISABLE_CAR_MODE_ALL_PRIORITIES) != 0;
628 boolean isPriorityTracked = mCarModePackagePriority.keySet().contains(priority);
629 boolean isDefaultPriority = priority == UiModeManager.DEFAULT_PRIORITY;
630 boolean isChangeAllowed =
631 // Anyone can disable the default priority.
632 isDefaultPriority
633 // If priority was enabled, only enabling package can disable it.
634 || isPriorityTracked && mCarModePackagePriority.get(priority).equals(packageName)
635 // Disable all priorities flag can disable all regardless.
636 || isDisableAll;
637 if (isChangeAllowed) {
638 Slog.d(TAG, "disableCarMode: disabling, priority=" + priority
639 + ", packageName=" + packageName);
640 if (isDisableAll) {
641 Set<Map.Entry<Integer, String>> entries =
642 new ArraySet<>(mCarModePackagePriority.entrySet());
643 mCarModePackagePriority.clear();
644
645 for (Map.Entry<Integer, String> entry : entries) {
646 notifyCarModeDisabled(entry.getKey(), entry.getValue());
647 }
648 } else {
649 mCarModePackagePriority.remove(priority);
650 notifyCarModeDisabled(priority, packageName);
651 }
652 }
653 }
654
655 /**
656 * Handles enabling car mode.
657 * <p>
658 * Car mode can be enabled at any priority if it has not already been enabled at that priority.
659 * The calling package is tracked for the first app which enters priority at the
660 * {@link UiModeManager#DEFAULT_PRIORITY}, though any app can disable it at that priority.
661 *
662 * @param priority The priority for enabling car mode.
663 * @param packageName The calling package which initiated the request.
664 */
665 private void enableCarMode(int priority, String packageName) {
666 boolean isPriorityTracked = mCarModePackagePriority.containsKey(priority);
667 boolean isPackagePresent = mCarModePackagePriority.containsValue(packageName);
668 if (!isPriorityTracked && !isPackagePresent) {
669 Slog.d(TAG, "enableCarMode: enabled at priority=" + priority + ", packageName="
670 + packageName);
671 mCarModePackagePriority.put(priority, packageName);
672 notifyCarModeEnabled(priority, packageName);
673 } else {
674 Slog.d(TAG, "enableCarMode: car mode at priority " + priority + " already enabled.");
675 }
676
677 }
678
679 private void notifyCarModeEnabled(int priority, String packageName) {
680 Intent intent = new Intent(UiModeManager.ACTION_ENTER_CAR_MODE_PRIORITIZED);
681 intent.putExtra(UiModeManager.EXTRA_CALLING_PACKAGE, packageName);
682 intent.putExtra(UiModeManager.EXTRA_PRIORITY, priority);
683 getContext().sendBroadcastAsUser(intent, UserHandle.ALL,
684 android.Manifest.permission.HANDLE_CAR_MODE_CHANGES);
685 }
686
687 private void notifyCarModeDisabled(int priority, String packageName) {
688 Intent intent = new Intent(UiModeManager.ACTION_EXIT_CAR_MODE_PRIORITIZED);
689 intent.putExtra(UiModeManager.EXTRA_CALLING_PACKAGE, packageName);
690 intent.putExtra(UiModeManager.EXTRA_PRIORITY, priority);
691 getContext().sendBroadcastAsUser(intent, UserHandle.ALL,
692 android.Manifest.permission.HANDLE_CAR_MODE_CHANGES);
693 }
694
695 /**
696 * Determines if car mode is enabled at any priority level.
697 * @return {@code true} if car mode is enabled, {@code false} otherwise.
698 */
699 private boolean isCarModeEnabled() {
700 return mCarModePackagePriority.size() > 0;
701 }
702
Jeff Brown487bb6e2012-10-11 13:35:42 -0700703 private void updateDockState(int newState) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800704 synchronized (mLock) {
705 if (newState != mDockState) {
706 mDockState = newState;
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700707 setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR, 0,
708 UiModeManager.DEFAULT_PRIORITY, "" /* packageName */);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800709 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700710 updateLocked(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800711 }
712 }
713 }
714 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500715
Jeff Brown487bb6e2012-10-11 13:35:42 -0700716 private static boolean isDeskDockState(int state) {
Daniel Sandler69a1da42011-11-04 15:08:30 -0400717 switch (state) {
718 case Intent.EXTRA_DOCK_STATE_DESK:
719 case Intent.EXTRA_DOCK_STATE_LE_DESK:
720 case Intent.EXTRA_DOCK_STATE_HE_DESK:
721 return true;
722 default:
723 return false;
724 }
725 }
726
Jeff Brown487bb6e2012-10-11 13:35:42 -0700727 private void updateConfigurationLocked() {
John Spurlock6c191292014-04-03 16:37:27 -0400728 int uiMode = mDefaultUiModeType;
keunyounga7710492015-09-23 11:33:58 -0700729 if (mUiModeLocked) {
730 // no-op, keeps default one
731 } else if (mTelevision) {
John Spurlock6c191292014-04-03 16:37:27 -0400732 uiMode = Configuration.UI_MODE_TYPE_TELEVISION;
733 } else if (mWatch) {
734 uiMode = Configuration.UI_MODE_TYPE_WATCH;
735 } else if (mCarModeEnabled) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800736 uiMode = Configuration.UI_MODE_TYPE_CAR;
Daniel Sandler69a1da42011-11-04 15:08:30 -0400737 } else if (isDeskDockState(mDockState)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800738 uiMode = Configuration.UI_MODE_TYPE_DESK;
Zak Cohen1a705732017-01-09 12:54:34 -0800739 } else if (mVrHeadset) {
740 uiMode = Configuration.UI_MODE_TYPE_VR_HEADSET;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800741 }
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800742
743 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
Justin Klaassen908b86c2016-08-08 09:18:42 -0700744 if (mTwilightManager != null) {
745 mTwilightManager.registerListener(mTwilightListener, mHandler);
746 }
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800747 updateComputedNightModeLocked();
748 uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
749 : Configuration.UI_MODE_NIGHT_NO;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800750 } else {
Justin Klaassen908b86c2016-08-08 09:18:42 -0700751 if (mTwilightManager != null) {
752 mTwilightManager.unregisterListener(mTwilightListener);
753 }
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800754 uiMode |= mNightMode << 4;
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400755 }
756
Winson3f5ad732019-03-04 15:21:04 -0800757 // Override night mode in power save mode if not in car mode
758 if (mPowerSave && !mCarModeEnabled) {
Lucas Dupin53c6e292018-07-12 18:42:53 -0700759 uiMode &= ~Configuration.UI_MODE_NIGHT_NO;
760 uiMode |= Configuration.UI_MODE_NIGHT_YES;
761 }
762
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400763 if (LOG) {
John Spurlock960779d2012-05-29 14:37:05 -0400764 Slog.d(TAG,
765 "updateConfigurationLocked: mDockState=" + mDockState
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400766 + "; mCarMode=" + mCarModeEnabled
767 + "; mNightMode=" + mNightMode
768 + "; uiMode=" + uiMode);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800769 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100770
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800771 mCurUiMode = uiMode;
Jeff Brown62c82e42012-09-26 01:30:41 -0700772 if (!mHoldingConfiguration) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700773 mConfiguration.uiMode = uiMode;
Jeff Brown62c82e42012-09-26 01:30:41 -0700774 }
775 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100776
Jeff Brown487bb6e2012-10-11 13:35:42 -0700777 private void sendConfigurationLocked() {
Jeff Brown62c82e42012-09-26 01:30:41 -0700778 if (mSetUiMode != mConfiguration.uiMode) {
779 mSetUiMode = mConfiguration.uiMode;
780
781 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700782 ActivityTaskManager.getService().updateConfiguration(mConfiguration);
Jeff Brown62c82e42012-09-26 01:30:41 -0700783 } catch (RemoteException e) {
784 Slog.w(TAG, "Failure communicating with activity manager", e);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800785 }
786 }
787 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100788
Adam Lesinski182f73f2013-12-05 16:48:06 -0800789 void updateLocked(int enableFlags, int disableFlags) {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700790 String action = null;
791 String oldAction = null;
792 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
793 adjustStatusBarCarModeLocked();
794 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
795 } else if (isDeskDockState(mLastBroadcastState)) {
796 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
797 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100798
Jeff Brown487bb6e2012-10-11 13:35:42 -0700799 if (mCarModeEnabled) {
800 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
Tobias Haamel780b2602010-03-15 12:54:45 +0100801 adjustStatusBarCarModeLocked();
Jeff Brown487bb6e2012-10-11 13:35:42 -0700802 if (oldAction != null) {
Adrian Roos2fbf4d52016-10-20 14:40:51 -0700803 sendForegroundBroadcastToAllUsers(oldAction);
Jeff Brown487bb6e2012-10-11 13:35:42 -0700804 }
805 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
806 action = UiModeManager.ACTION_ENTER_CAR_MODE;
807 }
808 } else if (isDeskDockState(mDockState)) {
809 if (!isDeskDockState(mLastBroadcastState)) {
810 if (oldAction != null) {
Adrian Roos2fbf4d52016-10-20 14:40:51 -0700811 sendForegroundBroadcastToAllUsers(oldAction);
Jeff Brown487bb6e2012-10-11 13:35:42 -0700812 }
813 mLastBroadcastState = mDockState;
814 action = UiModeManager.ACTION_ENTER_DESK_MODE;
815 }
816 } else {
817 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
818 action = oldAction;
819 }
820
821 if (action != null) {
822 if (LOG) {
823 Slog.v(TAG, String.format(
824 "updateLocked: preparing broadcast: action=%s enable=0x%08x disable=0x%08x",
825 action, enableFlags, disableFlags));
Dianne Hackborn7299c412010-03-04 18:41:49 -0800826 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100827
Jeff Brown487bb6e2012-10-11 13:35:42 -0700828 // Send the ordered broadcast; the result receiver will receive after all
829 // broadcasts have been sent. If any broadcast receiver changes the result
830 // code from the initial value of RESULT_OK, then the result receiver will
831 // not launch the corresponding dock application. This gives apps a chance
832 // to override the behavior and stay in their app even when the device is
833 // placed into a dock.
834 Intent intent = new Intent(action);
835 intent.putExtra("enableFlags", enableFlags);
836 intent.putExtra("disableFlags", disableFlags);
Adrian Roos2fbf4d52016-10-20 14:40:51 -0700837 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800838 getContext().sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null,
Jeff Brown487bb6e2012-10-11 13:35:42 -0700839 mResultReceiver, null, Activity.RESULT_OK, null, null);
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100840
Jeff Brown487bb6e2012-10-11 13:35:42 -0700841 // Attempting to make this transition a little more clean, we are going
842 // to hold off on doing a configuration change until we have finished
843 // the broadcast and started the home activity.
844 mHoldingConfiguration = true;
845 updateConfigurationLocked();
846 } else {
847 String category = null;
848 if (mCarModeEnabled) {
keunyounga7710492015-09-23 11:33:58 -0700849 if (mEnableCarDockLaunch
Jeff Brown487bb6e2012-10-11 13:35:42 -0700850 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
851 category = Intent.CATEGORY_CAR_DOCK;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800852 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400853 } else if (isDeskDockState(mDockState)) {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700854 if (ENABLE_LAUNCH_DESK_DOCK_APP
855 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
856 category = Intent.CATEGORY_DESK_DOCK;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800857 }
858 } else {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700859 if ((disableFlags & UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
860 category = Intent.CATEGORY_HOME;
861 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800862 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100863
Jeff Brown487bb6e2012-10-11 13:35:42 -0700864 if (LOG) {
865 Slog.v(TAG, "updateLocked: null action, mDockState="
866 + mDockState +", category=" + category);
867 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400868
Jeff Brown487bb6e2012-10-11 13:35:42 -0700869 sendConfigurationAndStartDreamOrDockAppLocked(category);
870 }
Jeff Brown62c82e42012-09-26 01:30:41 -0700871
Jeff Brown487bb6e2012-10-11 13:35:42 -0700872 // keep screen on when charging and in car mode
873 boolean keepScreenOn = mCharging &&
keunyoung1d0a7cc2014-07-28 13:12:50 -0700874 ((mCarModeEnabled && mCarModeKeepsScreenOn &&
keunyoungc093bf22014-08-11 18:51:15 -0700875 (mCarModeEnableFlags & UiModeManager.ENABLE_CAR_MODE_ALLOW_SLEEP) == 0) ||
Jeff Brown487bb6e2012-10-11 13:35:42 -0700876 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
877 if (keepScreenOn != mWakeLock.isHeld()) {
878 if (keepScreenOn) {
879 mWakeLock.acquire();
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700880 } else {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700881 mWakeLock.release();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800882 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800883 }
884 }
885
Adrian Roos2fbf4d52016-10-20 14:40:51 -0700886 private void sendForegroundBroadcastToAllUsers(String action) {
887 getContext().sendBroadcastAsUser(new Intent(action)
888 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND), UserHandle.ALL);
889 }
890
Jeff Brown62c82e42012-09-26 01:30:41 -0700891 private void updateAfterBroadcastLocked(String action, int enableFlags, int disableFlags) {
892 // Launch a dock activity
893 String category = null;
894 if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(action)) {
895 // Only launch car home when car mode is enabled and the caller
896 // has asked us to switch to it.
keunyounga7710492015-09-23 11:33:58 -0700897 if (mEnableCarDockLaunch
Jeff Brown62c82e42012-09-26 01:30:41 -0700898 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
899 category = Intent.CATEGORY_CAR_DOCK;
900 }
901 } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(action)) {
902 // Only launch car home when desk mode is enabled and the caller
903 // has asked us to switch to it. Currently re-using the car
904 // mode flag since we don't have a formal API for "desk mode".
905 if (ENABLE_LAUNCH_DESK_DOCK_APP
906 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
907 category = Intent.CATEGORY_DESK_DOCK;
908 }
909 } else {
910 // Launch the standard home app if requested.
911 if ((disableFlags & UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
912 category = Intent.CATEGORY_HOME;
913 }
914 }
915
916 if (LOG) {
917 Slog.v(TAG, String.format(
918 "Handling broadcast result for action %s: enable=0x%08x, disable=0x%08x, "
919 + "category=%s",
920 action, enableFlags, disableFlags, category));
921 }
922
923 sendConfigurationAndStartDreamOrDockAppLocked(category);
924 }
925
926 private void sendConfigurationAndStartDreamOrDockAppLocked(String category) {
927 // Update the configuration but don't send it yet.
928 mHoldingConfiguration = false;
929 updateConfigurationLocked();
930
931 // Start the dock app, if there is one.
932 boolean dockAppStarted = false;
933 if (category != null) {
934 // Now we are going to be careful about switching the
935 // configuration and starting the activity -- we need to
936 // do this in a specific order under control of the
937 // activity manager, to do it cleanly. So compute the
938 // new config, but don't set it yet, and let the
939 // activity manager take care of both the start and config
940 // change.
941 Intent homeIntent = buildHomeIntent(category);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800942 if (Sandman.shouldStartDockApp(getContext(), homeIntent)) {
Jeff Brown11159e92012-10-11 15:58:37 -0700943 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700944 int result = ActivityTaskManager.getService().startActivityWithConfig(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800945 null, null, homeIntent, null, null, null, 0, 0,
Jeff Brown11159e92012-10-11 15:58:37 -0700946 mConfiguration, null, UserHandle.USER_CURRENT);
Bryce Lee7f936862017-05-09 15:33:18 -0700947 if (ActivityManager.isStartResultSuccessful(result)) {
Jeff Brown11159e92012-10-11 15:58:37 -0700948 dockAppStarted = true;
949 } else if (result != ActivityManager.START_INTENT_NOT_RESOLVED) {
950 Slog.e(TAG, "Could not start dock app: " + homeIntent
951 + ", startActivityWithConfig result " + result);
952 }
953 } catch (RemoteException ex) {
954 Slog.e(TAG, "Could not start dock app: " + homeIntent, ex);
Jeff Brown62c82e42012-09-26 01:30:41 -0700955 }
Jeff Brown62c82e42012-09-26 01:30:41 -0700956 }
957 }
958
959 // Send the new configuration.
960 sendConfigurationLocked();
961
962 // If we did not start a dock app, then start dreaming if supported.
Jeff Brown11159e92012-10-11 15:58:37 -0700963 if (category != null && !dockAppStarted) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800964 Sandman.startDreamWhenDockedIfAppropriate(getContext());
Jeff Brown62c82e42012-09-26 01:30:41 -0700965 }
966 }
967
Dianne Hackborn7299c412010-03-04 18:41:49 -0800968 private void adjustStatusBarCarModeLocked() {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800969 final Context context = getContext();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800970 if (mStatusBarManager == null) {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700971 mStatusBarManager = (StatusBarManager)
Adam Lesinski182f73f2013-12-05 16:48:06 -0800972 context.getSystemService(Context.STATUS_BAR_SERVICE);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800973 }
974
Joe Onorato089de882010-04-12 08:18:45 -0700975 // Fear not: StatusBarManagerService manages a list of requests to disable
Dianne Hackborn7299c412010-03-04 18:41:49 -0800976 // features of the status bar; these are ORed together to form the
977 // active disabled list. So if (for example) the device is locked and
978 // the status bar should be totally disabled, the calls below will
979 // have no effect until the device is unlocked.
980 if (mStatusBarManager != null) {
981 mStatusBarManager.disable(mCarModeEnabled
982 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
983 : StatusBarManager.DISABLE_NONE);
984 }
985
986 if (mNotificationManager == null) {
987 mNotificationManager = (NotificationManager)
Adam Lesinski182f73f2013-12-05 16:48:06 -0800988 context.getSystemService(Context.NOTIFICATION_SERVICE);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800989 }
990
991 if (mNotificationManager != null) {
992 if (mCarModeEnabled) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800993 Intent carModeOffIntent = new Intent(context, DisableCarModeActivity.class);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800994
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500995 Notification.Builder n =
996 new Notification.Builder(context, SystemNotificationChannels.CAR_MODE)
Chris Wren1ce4b6d2015-06-11 10:19:43 -0400997 .setSmallIcon(R.drawable.stat_notify_car_mode)
998 .setDefaults(Notification.DEFAULT_LIGHTS)
999 .setOngoing(true)
1000 .setWhen(0)
1001 .setColor(context.getColor(
1002 com.android.internal.R.color.system_notification_accent_color))
1003 .setContentTitle(
1004 context.getString(R.string.car_mode_disable_notification_title))
1005 .setContentText(
1006 context.getString(R.string.car_mode_disable_notification_message))
1007 .setContentIntent(
1008 PendingIntent.getActivityAsUser(context, 0, carModeOffIntent, 0,
1009 null, UserHandle.CURRENT));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001010 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001011 SystemMessage.NOTE_CAR_MODE_DISABLE, n.build(), UserHandle.ALL);
Dianne Hackborn7299c412010-03-04 18:41:49 -08001012 } else {
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001013 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001014 SystemMessage.NOTE_CAR_MODE_DISABLE, UserHandle.ALL);
Dianne Hackborn7299c412010-03-04 18:41:49 -08001015 }
1016 }
1017 }
1018
Jeff Brown2416e092012-08-21 22:12:20 -07001019 private void updateComputedNightModeLocked() {
Adam Lesinski05199e82015-03-19 14:37:11 -07001020 if (mTwilightManager != null) {
Justin Klaassen908b86c2016-08-08 09:18:42 -07001021 TwilightState state = mTwilightManager.getLastTwilightState();
Adam Lesinski05199e82015-03-19 14:37:11 -07001022 if (state != null) {
1023 mComputedNightMode = state.isNight();
1024 }
Dianne Hackborn7299c412010-03-04 18:41:49 -08001025 }
Dianne Hackborn7299c412010-03-04 18:41:49 -08001026 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +01001027
Zak Cohen1a705732017-01-09 12:54:34 -08001028 private void registerVrStateListener() {
Craig Donner8deb67c2017-02-07 18:10:32 -08001029 IVrManager vrManager = IVrManager.Stub.asInterface(ServiceManager.getService(
1030 Context.VR_SERVICE));
Zak Cohen1a705732017-01-09 12:54:34 -08001031 try {
1032 if (vrManager != null) {
1033 vrManager.registerListener(mVrStateCallbacks);
1034 }
1035 } catch (RemoteException e) {
1036 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
1037 }
1038 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +01001039
Alan Viveretteba0d98f2017-01-30 10:36:54 -05001040 /**
1041 * Handles "adb shell" commands.
1042 */
1043 private static class Shell extends ShellCommand {
1044 public static final String NIGHT_MODE_STR_YES = "yes";
1045 public static final String NIGHT_MODE_STR_NO = "no";
1046 public static final String NIGHT_MODE_STR_AUTO = "auto";
1047 public static final String NIGHT_MODE_STR_UNKNOWN = "unknown";
1048 private final IUiModeManager mInterface;
1049
1050 Shell(IUiModeManager iface) {
1051 mInterface = iface;
1052 }
1053
1054 @Override
1055 public void onHelp() {
1056 final PrintWriter pw = getOutPrintWriter();
1057 pw.println("UiModeManager service (uimode) commands:");
1058 pw.println(" help");
1059 pw.println(" Print this help text.");
1060 pw.println(" night [yes|no|auto]");
1061 pw.println(" Set or read night mode.");
1062 }
1063
1064 @Override
1065 public int onCommand(String cmd) {
1066 if (cmd == null) {
1067 return handleDefaultCommands(cmd);
1068 }
1069
1070 try {
1071 switch (cmd) {
1072 case "night":
1073 return handleNightMode();
1074 default:
1075 return handleDefaultCommands(cmd);
1076 }
1077 } catch (RemoteException e) {
1078 final PrintWriter err = getErrPrintWriter();
1079 err.println("Remote exception: " + e);
1080 }
1081 return -1;
1082 }
1083
1084 private int handleNightMode() throws RemoteException {
1085 final PrintWriter err = getErrPrintWriter();
1086 final String modeStr = getNextArg();
1087 if (modeStr == null) {
1088 printCurrentNightMode();
1089 return 0;
1090 }
1091
1092 final int mode = strToNightMode(modeStr);
1093 if (mode >= 0) {
1094 mInterface.setNightMode(mode);
1095 printCurrentNightMode();
1096 return 0;
1097 } else {
1098 err.println("Error: mode must be '" + NIGHT_MODE_STR_YES + "', '"
1099 + NIGHT_MODE_STR_NO + "', or '" + NIGHT_MODE_STR_AUTO + "'");
1100 return -1;
1101 }
1102 }
1103
1104 private void printCurrentNightMode() throws RemoteException {
1105 final PrintWriter pw = getOutPrintWriter();
1106 final int currMode = mInterface.getNightMode();
1107 final String currModeStr = nightModeToStr(currMode);
1108 pw.println("Night mode: " + currModeStr);
1109 }
1110
1111 private static String nightModeToStr(int mode) {
1112 switch (mode) {
1113 case UiModeManager.MODE_NIGHT_YES:
1114 return NIGHT_MODE_STR_YES;
1115 case UiModeManager.MODE_NIGHT_NO:
1116 return NIGHT_MODE_STR_NO;
1117 case UiModeManager.MODE_NIGHT_AUTO:
1118 return NIGHT_MODE_STR_AUTO;
1119 default:
1120 return NIGHT_MODE_STR_UNKNOWN;
1121 }
1122 }
1123
1124 private static int strToNightMode(String modeStr) {
1125 switch (modeStr) {
1126 case NIGHT_MODE_STR_YES:
1127 return UiModeManager.MODE_NIGHT_YES;
1128 case NIGHT_MODE_STR_NO:
1129 return UiModeManager.MODE_NIGHT_NO;
1130 case NIGHT_MODE_STR_AUTO:
1131 return UiModeManager.MODE_NIGHT_AUTO;
1132 default:
1133 return -1;
1134 }
1135 }
1136 }
Felipe Lemeff9ec382018-09-24 11:07:56 -07001137
1138 public final class LocalService extends UiModeManagerInternal {
1139
1140 @Override
1141 public boolean isNightMode() {
1142 synchronized (mLock) {
1143 final boolean isIt = (mConfiguration.uiMode & Configuration.UI_MODE_NIGHT_YES) != 0;
1144 if (LOG) {
1145 Slog.d(TAG,
1146 "LocalService.isNightMode(): mNightMode=" + mNightMode
1147 + "; mComputedNightMode=" + mComputedNightMode
1148 + "; uiMode=" + mConfiguration.uiMode
1149 + "; isIt=" + isIt);
1150 }
1151 return isIt;
1152 }
1153 }
1154 }
Salvador Martinez2f792ef2018-09-26 17:33:51 -07001155
1156 private final class UserSwitchedReceiver extends BroadcastReceiver {
1157 @Override
1158 public void onReceive(Context context, Intent intent) {
1159 synchronized (mLock) {
1160 final int currentId = intent.getIntExtra(
1161 Intent.EXTRA_USER_HANDLE, UserHandle.USER_SYSTEM);
1162 // only update if the value is actually changed
1163 if (updateNightModeFromSettings(context, context.getResources(), currentId)) {
1164 updateLocked(0, 0);
1165 }
1166 }
1167 }
1168 }
Dianne Hackborn7299c412010-03-04 18:41:49 -08001169}