blob: 7ad04728b512d02e8b462d46804f37cbcf075635 [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;
JianYang Liu3eee9432019-12-10 14:32:30 -080059
Dianne Hackborn7299c412010-03-04 18:41:49 -080060import com.android.internal.R;
Jay Aliomer381e3302019-10-24 13:18:06 -040061import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn7299c412010-03-04 18:41:49 -080062import com.android.internal.app.DisableCarModeActivity;
Chris Wren282cfef2017-03-27 15:01:44 -040063import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050064import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060065import com.android.internal.util.DumpUtils;
Adam Lesinski182f73f2013-12-05 16:48:06 -080066import com.android.server.twilight.TwilightListener;
67import com.android.server.twilight.TwilightManager;
68import com.android.server.twilight.TwilightState;
Jay Aliomer381e3302019-10-24 13:18:06 -040069import com.android.server.wm.WindowManagerInternal;
Dianne Hackborn7299c412010-03-04 18:41:49 -080070
Lucas Dupinb1f0c762018-09-18 10:33:38 -070071import java.io.FileDescriptor;
72import java.io.PrintWriter;
Tyler Gunnf05f2c22019-09-30 15:12:24 -070073import java.util.HashMap;
74import java.util.Map;
75import java.util.Set;
Lucas Dupinb1f0c762018-09-18 10:33:38 -070076
Adam Lesinski182f73f2013-12-05 16:48:06 -080077final class UiModeManagerService extends SystemService {
Dianne Hackborn7299c412010-03-04 18:41:49 -080078 private static final String TAG = UiModeManager.class.getSimpleName();
79 private static final boolean LOG = false;
80
Daniel Sandler11ddf532011-11-16 11:10:03 -080081 // Enable launching of applications when entering the dock.
John Spurlock960779d2012-05-29 14:37:05 -040082 private static final boolean ENABLE_LAUNCH_DESK_DOCK_APP = true;
Beverly28e48fb2019-06-14 14:53:09 -040083 private static final String SYSTEM_PROPERTY_DEVICE_THEME = "persist.sys.theme";
Daniel Sandler11ddf532011-11-16 11:10:03 -080084
Dianne Hackborn7299c412010-03-04 18:41:49 -080085 final Object mLock = new Object();
Dianne Hackborn7299c412010-03-04 18:41:49 -080086 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
Bernd Holzheyba9ab182010-03-12 09:30:29 +010087
Adam Lesinski182f73f2013-12-05 16:48:06 -080088 private int mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
Alan Viverette4cc1e9e2015-02-12 11:01:06 -080089 private int mNightMode = UiModeManager.MODE_NIGHT_NO;
Jay Aliomer381e3302019-10-24 13:18:06 -040090 // we use the override auto mode
91 // for example: force night mode off in the night time while in auto mode
92 private int mNightModeOverride = mNightMode;
93 protected static final String OVERRIDE_NIGHT_MODE = Secure.UI_NIGHT_MODE + "_override";
Adam Lesinski182f73f2013-12-05 16:48:06 -080094
Tyler Gunnf05f2c22019-09-30 15:12:24 -070095 private Map<Integer, String> mCarModePackagePriority = new HashMap<>();
Dianne Hackborn7299c412010-03-04 18:41:49 -080096 private boolean mCarModeEnabled = false;
Mike Lockwoode29db6a2010-03-05 13:45:51 -050097 private boolean mCharging = false;
Lucas Dupin53c6e292018-07-12 18:42:53 -070098 private boolean mPowerSave = false;
Jeff Sharkey30b412c2019-12-07 16:15:29 +000099 // Do not change configuration now. wait until screen turns off.
100 // This prevents jank and activity restart when the user
101 // is actively using the device
102 private boolean mWaitForScreenOff = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800103 private int mDefaultUiModeType;
104 private boolean mCarModeKeepsScreenOn;
105 private boolean mDeskModeKeepsScreenOn;
106 private boolean mTelevision;
JianYang Liu3eee9432019-12-10 14:32:30 -0800107 private boolean mCar;
John Spurlock6c191292014-04-03 16:37:27 -0400108 private boolean mWatch;
Zak Cohen1a705732017-01-09 12:54:34 -0800109 private boolean mVrHeadset;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800110 private boolean mComputedNightMode;
keunyoung1d0a7cc2014-07-28 13:12:50 -0700111 private int mCarModeEnableFlags;
Salvador Martinezc500b272019-05-02 14:32:12 -0700112 private boolean mSetupWizardComplete;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113
keunyounga7710492015-09-23 11:33:58 -0700114 // flag set by resource, whether to enable Car dock launch when starting car mode.
115 private boolean mEnableCarDockLaunch = true;
116 // flag set by resource, whether to lock UI mode to the default one or not.
117 private boolean mUiModeLocked = false;
118 // flag set by resource, whether to night mode change for normal all or not.
119 private boolean mNightModeLocked = false;
120
Adam Lesinski182f73f2013-12-05 16:48:06 -0800121 int mCurUiMode = 0;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800122 private int mSetUiMode = 0;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800123 private boolean mHoldingConfiguration = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124
Dianne Hackborn7299c412010-03-04 18:41:49 -0800125 private Configuration mConfiguration = new Configuration();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800126 boolean mSystemReady;
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100127
Adam Lesinski182f73f2013-12-05 16:48:06 -0800128 private final Handler mHandler = new Handler();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800129
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 private TwilightManager mTwilightManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800131 private NotificationManager mNotificationManager;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800132 private StatusBarManager mStatusBarManager;
Jay Aliomer381e3302019-10-24 13:18:06 -0400133 private WindowManagerInternal mWindowManager;
Jeff Brown9fca9e92012-10-05 14:42:56 -0700134
Adam Lesinski182f73f2013-12-05 16:48:06 -0800135 private PowerManager.WakeLock mWakeLock;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800136
Felipe Lemeff9ec382018-09-24 11:07:56 -0700137 private final LocalService mLocalService = new LocalService();
138
Jeff Brownb880d882014-02-10 19:47:07 -0800139 public UiModeManagerService(Context context) {
140 super(context);
141 }
142
Jay Aliomer381e3302019-10-24 13:18:06 -0400143 @VisibleForTesting
144 protected UiModeManagerService(Context context, WindowManagerInternal wm,
145 PowerManager.WakeLock wl, TwilightManager tm,
146 boolean setupWizardComplete) {
147 super(context);
148 mWindowManager = wm;
149 mWakeLock = wl;
150 mTwilightManager = tm;
151 mSetupWizardComplete = setupWizardComplete;
152 }
153
Adam Lesinski182f73f2013-12-05 16:48:06 -0800154 private static Intent buildHomeIntent(String category) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700155 Intent intent = new Intent(Intent.ACTION_MAIN);
156 intent.addCategory(category);
157 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
158 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
159 return intent;
160 }
John Spurlock960779d2012-05-29 14:37:05 -0400161
Dianne Hackborn7299c412010-03-04 18:41:49 -0800162 // The broadcast receiver which receives the result of the ordered broadcast sent when
163 // the dock state changes. The original ordered broadcast is sent with an initial result
164 // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
165 // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
166 private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
167 @Override
168 public void onReceive(Context context, Intent intent) {
169 if (getResultCode() != Activity.RESULT_OK) {
Daniel Sandler69a1da42011-11-04 15:08:30 -0400170 if (LOG) {
John Spurlock960779d2012-05-29 14:37:05 -0400171 Slog.v(TAG, "Handling broadcast result for action " + intent.getAction()
Daniel Sandler69a1da42011-11-04 15:08:30 -0400172 + ": canceled: " + getResultCode());
173 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800174 return;
175 }
176
Jeff Brown62c82e42012-09-26 01:30:41 -0700177 final int enableFlags = intent.getIntExtra("enableFlags", 0);
178 final int disableFlags = intent.getIntExtra("disableFlags", 0);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800179 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -0700180 updateAfterBroadcastLocked(intent.getAction(), enableFlags, disableFlags);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800181 }
182 }
183 };
184
Dianne Hackborn7299c412010-03-04 18:41:49 -0800185 private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
186 @Override
187 public void onReceive(Context context, Intent intent) {
188 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
189 Intent.EXTRA_DOCK_STATE_UNDOCKED);
190 updateDockState(state);
191 }
192 };
193
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500194 private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
195 @Override
196 public void onReceive(Context context, Intent intent) {
Lucas Dupin53c6e292018-07-12 18:42:53 -0700197 switch (intent.getAction()) {
198 case Intent.ACTION_BATTERY_CHANGED:
199 mCharging = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
200 break;
Lucas Dupin53c6e292018-07-12 18:42:53 -0700201 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500202 synchronized (mLock) {
203 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700204 updateLocked(0, 0);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500205 }
206 }
207 }
208 };
209
Adam Lesinski182f73f2013-12-05 16:48:06 -0800210 private final TwilightListener mTwilightListener = new TwilightListener() {
Dianne Hackborn57f45032010-06-17 15:49:33 -0700211 @Override
Justin Klaassen908b86c2016-08-08 09:18:42 -0700212 public void onTwilightStateChanged(@Nullable TwilightState state) {
213 synchronized (mLock) {
214 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
JianYang Liu3eee9432019-12-10 14:32:30 -0800215 if (mCar) {
216 updateLocked(0, 0);
217 } else {
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000218 registerScreenOffEvent();
JianYang Liu3eee9432019-12-10 14:32:30 -0800219 }
Jay Aliomer381e3302019-10-24 13:18:06 -0400220 }
221 }
222 }
223 };
224
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000225 /**
226 * DO NOT USE DIRECTLY
227 * see register registerScreenOffEvent and unregisterScreenOffEvent
228 */
Jay Aliomer381e3302019-10-24 13:18:06 -0400229 private final BroadcastReceiver mOnScreenOffHandler = new BroadcastReceiver() {
230 @Override
231 public void onReceive(Context context, Intent intent) {
232 synchronized (mLock) {
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000233 // must unregister first before updating
234 unregisterScreenOffEvent();
Jay Aliomer381e3302019-10-24 13:18:06 -0400235 updateLocked(0, 0);
Justin Klaassen908b86c2016-08-08 09:18:42 -0700236 }
Dianne Hackborn57f45032010-06-17 15:49:33 -0700237 }
238 };
239
Zak Cohen1a705732017-01-09 12:54:34 -0800240 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
241 @Override
242 public void onVrStateChanged(boolean enabled) {
243 synchronized (mLock) {
244 mVrHeadset = enabled;
245 if (mSystemReady) {
246 updateLocked(0, 0);
247 }
248 }
249 }
250 };
251
Salvador Martinezc500b272019-05-02 14:32:12 -0700252 private final ContentObserver mSetupWizardObserver = new ContentObserver(mHandler) {
253 @Override
254 public void onChange(boolean selfChange, Uri uri) {
255 // setup wizard is done now so we can unblock
256 if (setupWizardCompleteForCurrentUser()) {
257 mSetupWizardComplete = true;
258 getContext().getContentResolver().unregisterContentObserver(mSetupWizardObserver);
259 // update night mode
260 Context context = getContext();
261 updateNightModeFromSettings(context, context.getResources(),
262 UserHandle.getCallingUserId());
263 updateLocked(0, 0);
264 }
265 }
266 };
267
Beverly470d8052019-07-22 17:15:58 -0400268 private final ContentObserver mDarkThemeObserver = new ContentObserver(mHandler) {
269 @Override
270 public void onChange(boolean selfChange, Uri uri) {
Jay Aliomer381e3302019-10-24 13:18:06 -0400271 int mode = Secure.getIntForUser(getContext().getContentResolver(), Secure.UI_NIGHT_MODE,
272 mNightMode, 0);
273 mode = mode == UiModeManager.MODE_NIGHT_AUTO
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000274 ? UiModeManager.MODE_NIGHT_YES : mode;
Beverly470d8052019-07-22 17:15:58 -0400275 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_THEME, Integer.toString(mode));
276 }
277 };
278
Salvador Martinezc500b272019-05-02 14:32:12 -0700279 @Override
280 public void onSwitchUser(int userHandle) {
281 super.onSwitchUser(userHandle);
282 getContext().getContentResolver().unregisterContentObserver(mSetupWizardObserver);
283 verifySetupWizardCompleted();
284 }
285
Adam Lesinski182f73f2013-12-05 16:48:06 -0800286 @Override
287 public void onStart() {
288 final Context context = getContext();
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800289
Adam Lesinski182f73f2013-12-05 16:48:06 -0800290 final PowerManager powerManager =
291 (PowerManager) context.getSystemService(Context.POWER_SERVICE);
292 mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
Jay Aliomer381e3302019-10-24 13:18:06 -0400293 mWindowManager = LocalServices.getService(WindowManagerInternal.class);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800294
Salvador Martinezc500b272019-05-02 14:32:12 -0700295 // If setup isn't complete for this user listen for completion so we can unblock
296 // being able to send a night mode configuration change event
297 verifySetupWizardCompleted();
298
Adam Lesinski182f73f2013-12-05 16:48:06 -0800299 context.registerReceiver(mDockModeReceiver,
Dianne Hackborn7299c412010-03-04 18:41:49 -0800300 new IntentFilter(Intent.ACTION_DOCK_EVENT));
Lucas Dupin53c6e292018-07-12 18:42:53 -0700301 IntentFilter batteryFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Lucas Dupin53c6e292018-07-12 18:42:53 -0700302 context.registerReceiver(mBatteryReceiver, batteryFilter);
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500303
Kweku Adams4db6a3c2019-02-04 16:06:13 -0800304 PowerManagerInternal localPowerManager =
305 LocalServices.getService(PowerManagerInternal.class);
306 mPowerSave = localPowerManager.getLowPowerState(ServiceType.NIGHT_MODE).batterySaverEnabled;
307 localPowerManager.registerLowPowerModeObserver(ServiceType.NIGHT_MODE,
308 state -> {
309 synchronized (mLock) {
310 if (mPowerSave == state.batterySaverEnabled) {
311 return;
312 }
313 mPowerSave = state.batterySaverEnabled;
314 if (mSystemReady) {
315 updateLocked(0, 0);
316 }
317 }
318 });
319
Dianne Hackborn7299c412010-03-04 18:41:49 -0800320 mConfiguration.setToDefaults();
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500321
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800322 final Resources res = context.getResources();
323 mDefaultUiModeType = res.getInteger(
Joe Onorato44fcb832011-12-14 20:59:30 -0800324 com.android.internal.R.integer.config_defaultUiModeType);
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800325 mCarModeKeepsScreenOn = (res.getInteger(
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500326 com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800327 mDeskModeKeepsScreenOn = (res.getInteger(
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500328 com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
keunyounga7710492015-09-23 11:33:58 -0700329 mEnableCarDockLaunch = res.getBoolean(
330 com.android.internal.R.bool.config_enableCarDockHomeLaunch);
331 mUiModeLocked = res.getBoolean(com.android.internal.R.bool.config_lockUiMode);
332 mNightModeLocked = res.getBoolean(com.android.internal.R.bool.config_lockDayNightMode);
Dianne Hackborn0cf2c8a2012-05-17 17:29:49 -0700333
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800334 final PackageManager pm = context.getPackageManager();
335 mTelevision = pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
336 || pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK);
JianYang Liu3eee9432019-12-10 14:32:30 -0800337 mCar = pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800338 mWatch = pm.hasSystemFeature(PackageManager.FEATURE_WATCH);
339
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700340 updateNightModeFromSettings(context, res, UserHandle.getCallingUserId());
Jeff Brown2416e092012-08-21 22:12:20 -0700341
Adam Lesinski05199e82015-03-19 14:37:11 -0700342 // Update the initial, static configurations.
Fyodor Kupolove29a5a12016-12-16 16:14:17 -0800343 SystemServerInitThreadPool.get().submit(() -> {
344 synchronized (mLock) {
345 updateConfigurationLocked();
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000346 applyConfigurationExternallyLocked();
Fyodor Kupolove29a5a12016-12-16 16:14:17 -0800347 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800348
Fyodor Kupolove29a5a12016-12-16 16:14:17 -0800349 }, TAG + ".onStart");
Adam Lesinski182f73f2013-12-05 16:48:06 -0800350 publishBinderService(Context.UI_MODE_SERVICE, mService);
Felipe Lemeff9ec382018-09-24 11:07:56 -0700351 publishLocalService(UiModeManagerInternal.class, mLocalService);
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700352
353 IntentFilter filter = new IntentFilter();
354 filter.addAction(Intent.ACTION_USER_SWITCHED);
355 context.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
Beverly470d8052019-07-22 17:15:58 -0400356
357 context.getContentResolver().registerContentObserver(Secure.getUriFor(Secure.UI_NIGHT_MODE),
358 false, mDarkThemeObserver, 0);
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700359 }
360
Jay Aliomer381e3302019-10-24 13:18:06 -0400361 @VisibleForTesting
362 protected IUiModeManager getService() {
363 return mService;
364 }
365
366 @VisibleForTesting
367 protected Configuration getConfiguration() {
368 return mConfiguration;
369 }
370
Salvador Martinezc500b272019-05-02 14:32:12 -0700371 // Records whether setup wizard has happened or not and adds an observer for this user if not.
372 private void verifySetupWizardCompleted() {
373 final Context context = getContext();
374 final int userId = UserHandle.getCallingUserId();
375 if (!setupWizardCompleteForCurrentUser()) {
376 mSetupWizardComplete = false;
377 context.getContentResolver().registerContentObserver(
378 Secure.getUriFor(
379 Secure.USER_SETUP_COMPLETE), false, mSetupWizardObserver, userId);
380 } else {
381 mSetupWizardComplete = true;
382 }
383 }
384
385 private boolean setupWizardCompleteForCurrentUser() {
386 return Secure.getIntForUser(getContext().getContentResolver(),
387 Secure.USER_SETUP_COMPLETE, 0, UserHandle.getCallingUserId()) == 1;
388 }
389
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700390 /**
391 * Updates the night mode setting in Settings.Global and returns if the value was successfully
392 * changed.
393 * @param context A valid context
394 * @param res A valid resource object
395 * @param userId The user to update the setting for
396 * @return True if the new value is different from the old value. False otherwise.
397 */
398 private boolean updateNightModeFromSettings(Context context, Resources res, int userId) {
399 final int defaultNightMode = res.getInteger(
400 com.android.internal.R.integer.config_defaultNightMode);
401 int oldNightMode = mNightMode;
Salvador Martinezc500b272019-05-02 14:32:12 -0700402 if (mSetupWizardComplete) {
403 mNightMode = Secure.getIntForUser(context.getContentResolver(),
404 Secure.UI_NIGHT_MODE, defaultNightMode, userId);
Jay Aliomer381e3302019-10-24 13:18:06 -0400405 mNightModeOverride = Secure.getIntForUser(context.getContentResolver(),
406 OVERRIDE_NIGHT_MODE, defaultNightMode, userId);
Salvador Martinezc500b272019-05-02 14:32:12 -0700407 } else {
408 mNightMode = defaultNightMode;
Jay Aliomer381e3302019-10-24 13:18:06 -0400409 mNightModeOverride = defaultNightMode;
Salvador Martinezc500b272019-05-02 14:32:12 -0700410 }
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700411
Beverly28e48fb2019-06-14 14:53:09 -0400412 return oldNightMode != mNightMode;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800413 }
414
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000415 private void registerScreenOffEvent() {
416 mWaitForScreenOff = true;
417 final IntentFilter intentFilter =
418 new IntentFilter(Intent.ACTION_SCREEN_OFF);
419 getContext().registerReceiver(mOnScreenOffHandler, intentFilter);
420 }
421
422 private void unregisterScreenOffEvent() {
423 mWaitForScreenOff = false;
424 try {
425 getContext().unregisterReceiver(mOnScreenOffHandler);
426 } catch (IllegalArgumentException e) {
427 // we ignore this exception if the receiver is unregistered already.
428 }
429 }
430
Alan Viveretteba0d98f2017-01-30 10:36:54 -0500431 private final IUiModeManager.Stub mService = new IUiModeManager.Stub() {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800432 @Override
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700433 public void enableCarMode(@UiModeManager.EnableCarMode int flags,
434 @IntRange(from = 0) int priority, String callingPackage) {
keunyounga7710492015-09-23 11:33:58 -0700435 if (isUiModeLocked()) {
436 Slog.e(TAG, "enableCarMode while UI mode is locked");
437 return;
438 }
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700439
440 if (priority != UiModeManager.DEFAULT_PRIORITY
441 && getContext().checkCallingOrSelfPermission(
442 android.Manifest.permission.ENTER_CAR_MODE_PRIORITIZED)
443 != PackageManager.PERMISSION_GRANTED) {
444 throw new SecurityException("Enabling car mode with a priority requires "
445 + "permission ENTER_CAR_MODE_PRIORITIZED");
446 }
447
Adam Lesinski182f73f2013-12-05 16:48:06 -0800448 final long ident = Binder.clearCallingIdentity();
449 try {
450 synchronized (mLock) {
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700451 setCarModeLocked(true, flags, priority, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800452 if (mSystemReady) {
453 updateLocked(flags, 0);
454 }
Jeff Brown487bb6e2012-10-11 13:35:42 -0700455 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800456 } finally {
457 Binder.restoreCallingIdentity(ident);
Mike Lockwood924e1642010-03-05 11:56:53 -0500458 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800459 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800460
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700461 /**
462 * This method is only kept around for the time being; the AIDL has an UnsupportedAppUsage
463 * tag which means this method is technically considered part of the greylist "API".
464 * @param flags
465 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800466 @Override
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700467 public void disableCarMode(@UiModeManager.DisableCarMode int flags) {
468 disableCarModeByCallingPackage(flags, null /* callingPackage */);
469 }
470
471 /**
472 * Handles requests to disable car mode.
473 * @param flags Disable car mode flags
474 * @param callingPackage
475 */
476 @Override
477 public void disableCarModeByCallingPackage(@UiModeManager.DisableCarMode int flags,
478 String callingPackage) {
keunyounga7710492015-09-23 11:33:58 -0700479 if (isUiModeLocked()) {
480 Slog.e(TAG, "disableCarMode while UI mode is locked");
481 return;
482 }
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700483
484 // If the caller is the system, we will allow the DISABLE_CAR_MODE_ALL_PRIORITIES car
485 // mode flag to be specified; this is so that the user can disable car mode at all
486 // priorities using the persistent notification.
487 boolean isSystemCaller = Binder.getCallingUid() == Process.SYSTEM_UID;
488 final int carModeFlags =
489 isSystemCaller ? flags : flags & ~UiModeManager.DISABLE_CAR_MODE_ALL_PRIORITIES;
490
Adam Lesinski182f73f2013-12-05 16:48:06 -0800491 final long ident = Binder.clearCallingIdentity();
492 try {
493 synchronized (mLock) {
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700494 // Determine if the caller has enabled car mode at a priority other than the
495 // default one. If they have, then attempt to disable at that priority.
496 int priority = mCarModePackagePriority.entrySet()
497 .stream()
498 .filter(e -> e.getValue().equals(callingPackage))
499 .findFirst()
500 .map(Map.Entry::getKey)
501 .orElse(UiModeManager.DEFAULT_PRIORITY);
502
503 setCarModeLocked(false, carModeFlags, priority, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800504 if (mSystemReady) {
505 updateLocked(0, flags);
506 }
Jeff Brown487bb6e2012-10-11 13:35:42 -0700507 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800508 } finally {
509 Binder.restoreCallingIdentity(ident);
Mike Lockwood924e1642010-03-05 11:56:53 -0500510 }
Jeff Brown487bb6e2012-10-11 13:35:42 -0700511 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100512
Adam Lesinski182f73f2013-12-05 16:48:06 -0800513 @Override
514 public int getCurrentModeType() {
515 final long ident = Binder.clearCallingIdentity();
516 try {
517 synchronized (mLock) {
518 return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
Jeff Brown487bb6e2012-10-11 13:35:42 -0700519 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800520 } finally {
521 Binder.restoreCallingIdentity(ident);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800522 }
523 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100524
Adam Lesinski182f73f2013-12-05 16:48:06 -0800525 @Override
526 public void setNightMode(int mode) {
Lucas Dupinc5aaf452018-09-20 16:10:07 -0700527 if (isNightModeLocked() && (getContext().checkCallingOrSelfPermission(
keunyounga7710492015-09-23 11:33:58 -0700528 android.Manifest.permission.MODIFY_DAY_NIGHT_MODE)
529 != PackageManager.PERMISSION_GRANTED)) {
Lucas Dupinc5aaf452018-09-20 16:10:07 -0700530 Slog.e(TAG, "Night mode locked, requires MODIFY_DAY_NIGHT_MODE permission");
keunyounga7710492015-09-23 11:33:58 -0700531 return;
532 }
Salvador Martinezc500b272019-05-02 14:32:12 -0700533 if (!mSetupWizardComplete) {
534 Slog.d(TAG, "Night mode cannot be changed before setup wizard completes.");
535 return;
536 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800537 switch (mode) {
538 case UiModeManager.MODE_NIGHT_NO:
539 case UiModeManager.MODE_NIGHT_YES:
540 case UiModeManager.MODE_NIGHT_AUTO:
541 break;
542 default:
543 throw new IllegalArgumentException("Unknown mode: " + mode);
544 }
545
Salvador Martinez2f792ef2018-09-26 17:33:51 -0700546 final int user = UserHandle.getCallingUserId();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800547 final long ident = Binder.clearCallingIdentity();
548 try {
549 synchronized (mLock) {
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800550 if (mNightMode != mode) {
Jay Aliomer381e3302019-10-24 13:18:06 -0400551 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000552 unregisterScreenOffEvent();
Winsonadc69672019-01-28 14:56:12 -0800553 }
554
Adam Lesinski182f73f2013-12-05 16:48:06 -0800555 mNightMode = mode;
Jay Aliomer381e3302019-10-24 13:18:06 -0400556 mNightModeOverride = mode;
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000557
558 // Only persist setting if not in car mode
559 if (!mCarModeEnabled) {
560 persistNightMode(user);
561 }
562 // on screen off will update configuration instead
JianYang Liu3eee9432019-12-10 14:32:30 -0800563 if (mNightMode != UiModeManager.MODE_NIGHT_AUTO || mCar) {
Jay Aliomer381e3302019-10-24 13:18:06 -0400564 updateLocked(0, 0);
565 } else {
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000566 registerScreenOffEvent();
Jay Aliomer381e3302019-10-24 13:18:06 -0400567 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800568 }
569 }
570 } finally {
571 Binder.restoreCallingIdentity(ident);
572 }
573 }
574
575 @Override
576 public int getNightMode() {
577 synchronized (mLock) {
578 return mNightMode;
579 }
580 }
581
582 @Override
keunyounga7710492015-09-23 11:33:58 -0700583 public boolean isUiModeLocked() {
584 synchronized (mLock) {
585 return mUiModeLocked;
586 }
587 }
588
589 @Override
590 public boolean isNightModeLocked() {
591 synchronized (mLock) {
592 return mNightModeLocked;
593 }
594 }
595
596 @Override
Alan Viveretteba0d98f2017-01-30 10:36:54 -0500597 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
598 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
599 new Shell(mService).exec(mService, in, out, err, args, callback, resultReceiver);
600 }
601
602 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -0800603 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600604 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800605 dumpImpl(pw);
606 }
Jay Aliomer381e3302019-10-24 13:18:06 -0400607
608 @Override
609 public boolean setNightModeActivated(boolean active) {
610 synchronized (mLock) {
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000611 final int user = UserHandle.getCallingUserId();
Jay Aliomer381e3302019-10-24 13:18:06 -0400612 final long ident = Binder.clearCallingIdentity();
613 try {
614 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000615 unregisterScreenOffEvent();
Jay Aliomer381e3302019-10-24 13:18:06 -0400616 mNightModeOverride = active
617 ? UiModeManager.MODE_NIGHT_YES : UiModeManager.MODE_NIGHT_NO;
618 } else if (mNightMode == UiModeManager.MODE_NIGHT_NO
619 && active) {
620 mNightMode = UiModeManager.MODE_NIGHT_YES;
621 } else if (mNightMode == UiModeManager.MODE_NIGHT_YES
622 && !active) {
623 mNightMode = UiModeManager.MODE_NIGHT_NO;
624 }
625 updateConfigurationLocked();
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000626 applyConfigurationExternallyLocked();
627 persistNightMode(user);
Jay Aliomer381e3302019-10-24 13:18:06 -0400628 return true;
629 } finally {
630 Binder.restoreCallingIdentity(ident);
631 }
632 }
633 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800634 };
635
636 void dumpImpl(PrintWriter pw) {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700637 synchronized (mLock) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800638 pw.println("Current UI Mode Service state:");
639 pw.print(" mDockState="); pw.print(mDockState);
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700640 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
641
Felipe Lemeff9ec382018-09-24 11:07:56 -0700642 pw.print(" mNightMode="); pw.print(mNightMode); pw.print(" (");
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700643 pw.print(Shell.nightModeToStr(mNightMode)); pw.print(") ");
644 pw.print(" mNightModeLocked="); pw.println(mNightModeLocked);
645
646 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
647 pw.print(" (carModeApps=");
648 for (Map.Entry<Integer, String> entry : mCarModePackagePriority.entrySet()) {
649 pw.print(entry.getKey());
650 pw.print(":");
651 pw.print(entry.getValue());
652 pw.print(" ");
653 }
654 pw.println("");
655 pw.print(" mComputedNightMode="); pw.print(mComputedNightMode);
656 pw.print(" mCarModeEnableFlags="); pw.print(mCarModeEnableFlags);
657 pw.print(" mEnableCarDockLaunch="); pw.println(mEnableCarDockLaunch);
658
Adam Lesinski182f73f2013-12-05 16:48:06 -0800659 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700660 pw.print(" mUiModeLocked="); pw.print(mUiModeLocked);
661 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
662
Adam Lesinski182f73f2013-12-05 16:48:06 -0800663 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700664 pw.print(" mSystemReady="); pw.println(mSystemReady);
665
Adam Lesinski05199e82015-03-19 14:37:11 -0700666 if (mTwilightManager != null) {
667 // We may not have a TwilightManager.
Justin Klaassen908b86c2016-08-08 09:18:42 -0700668 pw.print(" mTwilightService.getLastTwilightState()=");
669 pw.println(mTwilightManager.getLastTwilightState());
Adam Lesinski05199e82015-03-19 14:37:11 -0700670 }
Jeff Brown487bb6e2012-10-11 13:35:42 -0700671 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800672 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100673
Adam Lesinski182f73f2013-12-05 16:48:06 -0800674 @Override
675 public void onBootPhase(int phase) {
676 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
677 synchronized (mLock) {
Adam Lesinski05199e82015-03-19 14:37:11 -0700678 mTwilightManager = getLocalService(TwilightManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800679 mSystemReady = true;
680 mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
681 updateComputedNightModeLocked();
Zak Cohen1a705732017-01-09 12:54:34 -0800682 registerVrStateListener();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800683 updateLocked(0, 0);
684 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800685 }
686 }
687
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700688 /**
689 * Updates the global car mode state.
690 * The device is considered to be in car mode if there exists an app at any priority level which
691 * has entered car mode.
692 *
693 * @param enabled {@code true} if the caller wishes to enable car mode, {@code false} otherwise.
694 * @param flags Flags used when enabling/disabling car mode.
695 * @param priority The priority level for entering or exiting car mode; defaults to
696 * {@link UiModeManager#DEFAULT_PRIORITY} for callers using
697 * {@link UiModeManager#enableCarMode(int)}. Callers using
698 * {@link UiModeManager#enableCarMode(int, int)} may specify a priority.
699 * @param packageName The package name of the app which initiated the request to enable or
700 * disable car mode.
701 */
702 void setCarModeLocked(boolean enabled, int flags, int priority, String packageName) {
703 if (enabled) {
704 enableCarMode(priority, packageName);
705 } else {
706 disableCarMode(flags, priority, packageName);
707 }
708 boolean isCarModeNowEnabled = isCarModeEnabled();
Winsonadc69672019-01-28 14:56:12 -0800709
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700710 if (mCarModeEnabled != isCarModeNowEnabled) {
711 mCarModeEnabled = isCarModeNowEnabled;
Winson3f5ad732019-03-04 15:21:04 -0800712 // When exiting car mode, restore night mode from settings
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700713 if (!isCarModeNowEnabled) {
Winsonadc69672019-01-28 14:56:12 -0800714 Context context = getContext();
715 updateNightModeFromSettings(context,
716 context.getResources(),
717 UserHandle.getCallingUserId());
718 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800719 }
keunyoung1d0a7cc2014-07-28 13:12:50 -0700720 mCarModeEnableFlags = flags;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800721 }
722
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700723 /**
724 * Handles disabling car mode.
725 * <p>
726 * Car mode can be disabled at a priority level if any of the following is true:
727 * 1. The priority being disabled is the {@link UiModeManager#DEFAULT_PRIORITY}.
728 * 2. The priority level is enabled and the caller is the app who originally enabled it.
729 * 3. The {@link UiModeManager#DISABLE_CAR_MODE_ALL_PRIORITIES} flag was specified, meaning all
730 * car mode priorities are disabled.
731 *
732 * @param flags Car mode flags.
733 * @param priority The priority level at which to disable car mode.
734 * @param packageName The calling package which initiated the request.
735 */
736 private void disableCarMode(int flags, int priority, String packageName) {
737 boolean isDisableAll = (flags & UiModeManager.DISABLE_CAR_MODE_ALL_PRIORITIES) != 0;
738 boolean isPriorityTracked = mCarModePackagePriority.keySet().contains(priority);
739 boolean isDefaultPriority = priority == UiModeManager.DEFAULT_PRIORITY;
740 boolean isChangeAllowed =
741 // Anyone can disable the default priority.
742 isDefaultPriority
743 // If priority was enabled, only enabling package can disable it.
744 || isPriorityTracked && mCarModePackagePriority.get(priority).equals(packageName)
745 // Disable all priorities flag can disable all regardless.
746 || isDisableAll;
747 if (isChangeAllowed) {
748 Slog.d(TAG, "disableCarMode: disabling, priority=" + priority
749 + ", packageName=" + packageName);
750 if (isDisableAll) {
751 Set<Map.Entry<Integer, String>> entries =
752 new ArraySet<>(mCarModePackagePriority.entrySet());
753 mCarModePackagePriority.clear();
754
755 for (Map.Entry<Integer, String> entry : entries) {
756 notifyCarModeDisabled(entry.getKey(), entry.getValue());
757 }
758 } else {
759 mCarModePackagePriority.remove(priority);
760 notifyCarModeDisabled(priority, packageName);
761 }
762 }
763 }
764
765 /**
766 * Handles enabling car mode.
767 * <p>
768 * Car mode can be enabled at any priority if it has not already been enabled at that priority.
769 * The calling package is tracked for the first app which enters priority at the
770 * {@link UiModeManager#DEFAULT_PRIORITY}, though any app can disable it at that priority.
771 *
772 * @param priority The priority for enabling car mode.
773 * @param packageName The calling package which initiated the request.
774 */
775 private void enableCarMode(int priority, String packageName) {
776 boolean isPriorityTracked = mCarModePackagePriority.containsKey(priority);
777 boolean isPackagePresent = mCarModePackagePriority.containsValue(packageName);
778 if (!isPriorityTracked && !isPackagePresent) {
779 Slog.d(TAG, "enableCarMode: enabled at priority=" + priority + ", packageName="
780 + packageName);
781 mCarModePackagePriority.put(priority, packageName);
782 notifyCarModeEnabled(priority, packageName);
783 } else {
784 Slog.d(TAG, "enableCarMode: car mode at priority " + priority + " already enabled.");
785 }
786
787 }
788
789 private void notifyCarModeEnabled(int priority, String packageName) {
790 Intent intent = new Intent(UiModeManager.ACTION_ENTER_CAR_MODE_PRIORITIZED);
791 intent.putExtra(UiModeManager.EXTRA_CALLING_PACKAGE, packageName);
792 intent.putExtra(UiModeManager.EXTRA_PRIORITY, priority);
793 getContext().sendBroadcastAsUser(intent, UserHandle.ALL,
794 android.Manifest.permission.HANDLE_CAR_MODE_CHANGES);
795 }
796
797 private void notifyCarModeDisabled(int priority, String packageName) {
798 Intent intent = new Intent(UiModeManager.ACTION_EXIT_CAR_MODE_PRIORITIZED);
799 intent.putExtra(UiModeManager.EXTRA_CALLING_PACKAGE, packageName);
800 intent.putExtra(UiModeManager.EXTRA_PRIORITY, priority);
801 getContext().sendBroadcastAsUser(intent, UserHandle.ALL,
802 android.Manifest.permission.HANDLE_CAR_MODE_CHANGES);
803 }
804
805 /**
806 * Determines if car mode is enabled at any priority level.
807 * @return {@code true} if car mode is enabled, {@code false} otherwise.
808 */
809 private boolean isCarModeEnabled() {
810 return mCarModePackagePriority.size() > 0;
811 }
812
Jeff Brown487bb6e2012-10-11 13:35:42 -0700813 private void updateDockState(int newState) {
Dianne Hackborn7299c412010-03-04 18:41:49 -0800814 synchronized (mLock) {
815 if (newState != mDockState) {
816 mDockState = newState;
Tyler Gunnf05f2c22019-09-30 15:12:24 -0700817 setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR, 0,
818 UiModeManager.DEFAULT_PRIORITY, "" /* packageName */);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800819 if (mSystemReady) {
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700820 updateLocked(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME, 0);
Dianne Hackborn7299c412010-03-04 18:41:49 -0800821 }
822 }
823 }
824 }
Mike Lockwoode29db6a2010-03-05 13:45:51 -0500825
Jeff Brown487bb6e2012-10-11 13:35:42 -0700826 private static boolean isDeskDockState(int state) {
Daniel Sandler69a1da42011-11-04 15:08:30 -0400827 switch (state) {
828 case Intent.EXTRA_DOCK_STATE_DESK:
829 case Intent.EXTRA_DOCK_STATE_LE_DESK:
830 case Intent.EXTRA_DOCK_STATE_HE_DESK:
831 return true;
832 default:
833 return false;
834 }
835 }
836
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000837 private void persistNightMode(int user) {
838 Secure.putIntForUser(getContext().getContentResolver(),
839 Secure.UI_NIGHT_MODE, mNightMode, user);
840 Secure.putIntForUser(getContext().getContentResolver(),
841 OVERRIDE_NIGHT_MODE, mNightModeOverride, user);
842 }
843
Jeff Brown487bb6e2012-10-11 13:35:42 -0700844 private void updateConfigurationLocked() {
John Spurlock6c191292014-04-03 16:37:27 -0400845 int uiMode = mDefaultUiModeType;
keunyounga7710492015-09-23 11:33:58 -0700846 if (mUiModeLocked) {
847 // no-op, keeps default one
848 } else if (mTelevision) {
John Spurlock6c191292014-04-03 16:37:27 -0400849 uiMode = Configuration.UI_MODE_TYPE_TELEVISION;
850 } else if (mWatch) {
851 uiMode = Configuration.UI_MODE_TYPE_WATCH;
852 } else if (mCarModeEnabled) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800853 uiMode = Configuration.UI_MODE_TYPE_CAR;
Daniel Sandler69a1da42011-11-04 15:08:30 -0400854 } else if (isDeskDockState(mDockState)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800855 uiMode = Configuration.UI_MODE_TYPE_DESK;
Zak Cohen1a705732017-01-09 12:54:34 -0800856 } else if (mVrHeadset) {
857 uiMode = Configuration.UI_MODE_TYPE_VR_HEADSET;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800858 }
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800859
860 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
Justin Klaassen908b86c2016-08-08 09:18:42 -0700861 if (mTwilightManager != null) {
862 mTwilightManager.registerListener(mTwilightListener, mHandler);
863 }
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800864 updateComputedNightModeLocked();
865 uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
866 : Configuration.UI_MODE_NIGHT_NO;
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800867 } else {
Justin Klaassen908b86c2016-08-08 09:18:42 -0700868 if (mTwilightManager != null) {
869 mTwilightManager.unregisterListener(mTwilightListener);
870 }
Alan Viverette4cc1e9e2015-02-12 11:01:06 -0800871 uiMode |= mNightMode << 4;
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400872 }
873
Winson3f5ad732019-03-04 15:21:04 -0800874 // Override night mode in power save mode if not in car mode
875 if (mPowerSave && !mCarModeEnabled) {
Lucas Dupin53c6e292018-07-12 18:42:53 -0700876 uiMode &= ~Configuration.UI_MODE_NIGHT_NO;
877 uiMode |= Configuration.UI_MODE_NIGHT_YES;
878 }
879
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400880 if (LOG) {
John Spurlock960779d2012-05-29 14:37:05 -0400881 Slog.d(TAG,
882 "updateConfigurationLocked: mDockState=" + mDockState
Daniel Sandler8daf2a42010-04-02 10:15:09 -0400883 + "; mCarMode=" + mCarModeEnabled
884 + "; mNightMode=" + mNightMode
885 + "; uiMode=" + uiMode);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800886 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100887
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800888 mCurUiMode = uiMode;
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000889 if (!mHoldingConfiguration || !mWaitForScreenOff) {
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -0700890 mConfiguration.uiMode = uiMode;
Jeff Brown62c82e42012-09-26 01:30:41 -0700891 }
892 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100893
Jeff Sharkey30b412c2019-12-07 16:15:29 +0000894 private void applyConfigurationExternallyLocked() {
Jeff Brown62c82e42012-09-26 01:30:41 -0700895 if (mSetUiMode != mConfiguration.uiMode) {
896 mSetUiMode = mConfiguration.uiMode;
Jeff Brown62c82e42012-09-26 01:30:41 -0700897 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700898 ActivityTaskManager.getService().updateConfiguration(mConfiguration);
Jeff Brown62c82e42012-09-26 01:30:41 -0700899 } catch (RemoteException e) {
900 Slog.w(TAG, "Failure communicating with activity manager", e);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -0800901 }
902 }
903 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100904
Adam Lesinski182f73f2013-12-05 16:48:06 -0800905 void updateLocked(int enableFlags, int disableFlags) {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700906 String action = null;
907 String oldAction = null;
908 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
909 adjustStatusBarCarModeLocked();
910 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
911 } else if (isDeskDockState(mLastBroadcastState)) {
912 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
913 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100914
Jeff Brown487bb6e2012-10-11 13:35:42 -0700915 if (mCarModeEnabled) {
916 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
Tobias Haamel780b2602010-03-15 12:54:45 +0100917 adjustStatusBarCarModeLocked();
Jeff Brown487bb6e2012-10-11 13:35:42 -0700918 if (oldAction != null) {
Adrian Roos2fbf4d52016-10-20 14:40:51 -0700919 sendForegroundBroadcastToAllUsers(oldAction);
Jeff Brown487bb6e2012-10-11 13:35:42 -0700920 }
921 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
922 action = UiModeManager.ACTION_ENTER_CAR_MODE;
923 }
924 } else if (isDeskDockState(mDockState)) {
925 if (!isDeskDockState(mLastBroadcastState)) {
926 if (oldAction != null) {
Adrian Roos2fbf4d52016-10-20 14:40:51 -0700927 sendForegroundBroadcastToAllUsers(oldAction);
Jeff Brown487bb6e2012-10-11 13:35:42 -0700928 }
929 mLastBroadcastState = mDockState;
930 action = UiModeManager.ACTION_ENTER_DESK_MODE;
931 }
932 } else {
933 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
934 action = oldAction;
935 }
936
937 if (action != null) {
938 if (LOG) {
939 Slog.v(TAG, String.format(
940 "updateLocked: preparing broadcast: action=%s enable=0x%08x disable=0x%08x",
941 action, enableFlags, disableFlags));
Dianne Hackborn7299c412010-03-04 18:41:49 -0800942 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100943
Jeff Brown487bb6e2012-10-11 13:35:42 -0700944 // Send the ordered broadcast; the result receiver will receive after all
945 // broadcasts have been sent. If any broadcast receiver changes the result
946 // code from the initial value of RESULT_OK, then the result receiver will
947 // not launch the corresponding dock application. This gives apps a chance
948 // to override the behavior and stay in their app even when the device is
949 // placed into a dock.
950 Intent intent = new Intent(action);
951 intent.putExtra("enableFlags", enableFlags);
952 intent.putExtra("disableFlags", disableFlags);
Adrian Roos2fbf4d52016-10-20 14:40:51 -0700953 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800954 getContext().sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null,
Jeff Brown487bb6e2012-10-11 13:35:42 -0700955 mResultReceiver, null, Activity.RESULT_OK, null, null);
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100956
Jeff Brown487bb6e2012-10-11 13:35:42 -0700957 // Attempting to make this transition a little more clean, we are going
958 // to hold off on doing a configuration change until we have finished
959 // the broadcast and started the home activity.
960 mHoldingConfiguration = true;
961 updateConfigurationLocked();
962 } else {
963 String category = null;
964 if (mCarModeEnabled) {
keunyounga7710492015-09-23 11:33:58 -0700965 if (mEnableCarDockLaunch
Jeff Brown487bb6e2012-10-11 13:35:42 -0700966 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
967 category = Intent.CATEGORY_CAR_DOCK;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800968 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400969 } else if (isDeskDockState(mDockState)) {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700970 if (ENABLE_LAUNCH_DESK_DOCK_APP
971 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
972 category = Intent.CATEGORY_DESK_DOCK;
Dianne Hackborn7299c412010-03-04 18:41:49 -0800973 }
974 } else {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700975 if ((disableFlags & UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
976 category = Intent.CATEGORY_HOME;
977 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800978 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +0100979
Jeff Brown487bb6e2012-10-11 13:35:42 -0700980 if (LOG) {
981 Slog.v(TAG, "updateLocked: null action, mDockState="
982 + mDockState +", category=" + category);
983 }
Daniel Sandler69a1da42011-11-04 15:08:30 -0400984
Jeff Brown487bb6e2012-10-11 13:35:42 -0700985 sendConfigurationAndStartDreamOrDockAppLocked(category);
986 }
Jeff Brown62c82e42012-09-26 01:30:41 -0700987
Jeff Brown487bb6e2012-10-11 13:35:42 -0700988 // keep screen on when charging and in car mode
989 boolean keepScreenOn = mCharging &&
keunyoung1d0a7cc2014-07-28 13:12:50 -0700990 ((mCarModeEnabled && mCarModeKeepsScreenOn &&
keunyoungc093bf22014-08-11 18:51:15 -0700991 (mCarModeEnableFlags & UiModeManager.ENABLE_CAR_MODE_ALLOW_SLEEP) == 0) ||
Jeff Brown487bb6e2012-10-11 13:35:42 -0700992 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
993 if (keepScreenOn != mWakeLock.isHeld()) {
994 if (keepScreenOn) {
995 mWakeLock.acquire();
Dianne Hackbornf5c5d222010-04-09 13:14:48 -0700996 } else {
Jeff Brown487bb6e2012-10-11 13:35:42 -0700997 mWakeLock.release();
Dianne Hackborn7299c412010-03-04 18:41:49 -0800998 }
Dianne Hackborn7299c412010-03-04 18:41:49 -0800999 }
1000 }
1001
Adrian Roos2fbf4d52016-10-20 14:40:51 -07001002 private void sendForegroundBroadcastToAllUsers(String action) {
1003 getContext().sendBroadcastAsUser(new Intent(action)
1004 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND), UserHandle.ALL);
1005 }
1006
Jeff Brown62c82e42012-09-26 01:30:41 -07001007 private void updateAfterBroadcastLocked(String action, int enableFlags, int disableFlags) {
1008 // Launch a dock activity
1009 String category = null;
1010 if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(action)) {
1011 // Only launch car home when car mode is enabled and the caller
1012 // has asked us to switch to it.
keunyounga7710492015-09-23 11:33:58 -07001013 if (mEnableCarDockLaunch
Jeff Brown62c82e42012-09-26 01:30:41 -07001014 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
1015 category = Intent.CATEGORY_CAR_DOCK;
1016 }
1017 } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(action)) {
1018 // Only launch car home when desk mode is enabled and the caller
1019 // has asked us to switch to it. Currently re-using the car
1020 // mode flag since we don't have a formal API for "desk mode".
1021 if (ENABLE_LAUNCH_DESK_DOCK_APP
1022 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
1023 category = Intent.CATEGORY_DESK_DOCK;
1024 }
1025 } else {
1026 // Launch the standard home app if requested.
1027 if ((disableFlags & UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
1028 category = Intent.CATEGORY_HOME;
1029 }
1030 }
1031
1032 if (LOG) {
1033 Slog.v(TAG, String.format(
1034 "Handling broadcast result for action %s: enable=0x%08x, disable=0x%08x, "
1035 + "category=%s",
1036 action, enableFlags, disableFlags, category));
1037 }
1038
1039 sendConfigurationAndStartDreamOrDockAppLocked(category);
1040 }
1041
1042 private void sendConfigurationAndStartDreamOrDockAppLocked(String category) {
1043 // Update the configuration but don't send it yet.
1044 mHoldingConfiguration = false;
1045 updateConfigurationLocked();
1046
1047 // Start the dock app, if there is one.
1048 boolean dockAppStarted = false;
1049 if (category != null) {
1050 // Now we are going to be careful about switching the
1051 // configuration and starting the activity -- we need to
1052 // do this in a specific order under control of the
1053 // activity manager, to do it cleanly. So compute the
1054 // new config, but don't set it yet, and let the
1055 // activity manager take care of both the start and config
1056 // change.
1057 Intent homeIntent = buildHomeIntent(category);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001058 if (Sandman.shouldStartDockApp(getContext(), homeIntent)) {
Jeff Brown11159e92012-10-11 15:58:37 -07001059 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001060 int result = ActivityTaskManager.getService().startActivityWithConfig(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001061 null, null, homeIntent, null, null, null, 0, 0,
Jeff Brown11159e92012-10-11 15:58:37 -07001062 mConfiguration, null, UserHandle.USER_CURRENT);
Bryce Lee7f936862017-05-09 15:33:18 -07001063 if (ActivityManager.isStartResultSuccessful(result)) {
Jeff Brown11159e92012-10-11 15:58:37 -07001064 dockAppStarted = true;
1065 } else if (result != ActivityManager.START_INTENT_NOT_RESOLVED) {
1066 Slog.e(TAG, "Could not start dock app: " + homeIntent
1067 + ", startActivityWithConfig result " + result);
1068 }
1069 } catch (RemoteException ex) {
1070 Slog.e(TAG, "Could not start dock app: " + homeIntent, ex);
Jeff Brown62c82e42012-09-26 01:30:41 -07001071 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001072 }
1073 }
1074
1075 // Send the new configuration.
Jeff Sharkey30b412c2019-12-07 16:15:29 +00001076 applyConfigurationExternallyLocked();
Jeff Brown62c82e42012-09-26 01:30:41 -07001077
1078 // If we did not start a dock app, then start dreaming if supported.
Jeff Brown11159e92012-10-11 15:58:37 -07001079 if (category != null && !dockAppStarted) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001080 Sandman.startDreamWhenDockedIfAppropriate(getContext());
Jeff Brown62c82e42012-09-26 01:30:41 -07001081 }
1082 }
1083
Dianne Hackborn7299c412010-03-04 18:41:49 -08001084 private void adjustStatusBarCarModeLocked() {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001085 final Context context = getContext();
Dianne Hackborn7299c412010-03-04 18:41:49 -08001086 if (mStatusBarManager == null) {
Jeff Brown487bb6e2012-10-11 13:35:42 -07001087 mStatusBarManager = (StatusBarManager)
Adam Lesinski182f73f2013-12-05 16:48:06 -08001088 context.getSystemService(Context.STATUS_BAR_SERVICE);
Dianne Hackborn7299c412010-03-04 18:41:49 -08001089 }
1090
Joe Onorato089de882010-04-12 08:18:45 -07001091 // Fear not: StatusBarManagerService manages a list of requests to disable
Dianne Hackborn7299c412010-03-04 18:41:49 -08001092 // features of the status bar; these are ORed together to form the
1093 // active disabled list. So if (for example) the device is locked and
1094 // the status bar should be totally disabled, the calls below will
1095 // have no effect until the device is unlocked.
1096 if (mStatusBarManager != null) {
1097 mStatusBarManager.disable(mCarModeEnabled
1098 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
1099 : StatusBarManager.DISABLE_NONE);
1100 }
1101
1102 if (mNotificationManager == null) {
1103 mNotificationManager = (NotificationManager)
Adam Lesinski182f73f2013-12-05 16:48:06 -08001104 context.getSystemService(Context.NOTIFICATION_SERVICE);
Dianne Hackborn7299c412010-03-04 18:41:49 -08001105 }
1106
1107 if (mNotificationManager != null) {
1108 if (mCarModeEnabled) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001109 Intent carModeOffIntent = new Intent(context, DisableCarModeActivity.class);
Dianne Hackborn7299c412010-03-04 18:41:49 -08001110
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001111 Notification.Builder n =
1112 new Notification.Builder(context, SystemNotificationChannels.CAR_MODE)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04001113 .setSmallIcon(R.drawable.stat_notify_car_mode)
1114 .setDefaults(Notification.DEFAULT_LIGHTS)
1115 .setOngoing(true)
1116 .setWhen(0)
1117 .setColor(context.getColor(
1118 com.android.internal.R.color.system_notification_accent_color))
1119 .setContentTitle(
1120 context.getString(R.string.car_mode_disable_notification_title))
1121 .setContentText(
1122 context.getString(R.string.car_mode_disable_notification_message))
1123 .setContentIntent(
1124 PendingIntent.getActivityAsUser(context, 0, carModeOffIntent, 0,
1125 null, UserHandle.CURRENT));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001126 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001127 SystemMessage.NOTE_CAR_MODE_DISABLE, n.build(), UserHandle.ALL);
Dianne Hackborn7299c412010-03-04 18:41:49 -08001128 } else {
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001129 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001130 SystemMessage.NOTE_CAR_MODE_DISABLE, UserHandle.ALL);
Dianne Hackborn7299c412010-03-04 18:41:49 -08001131 }
1132 }
1133 }
1134
Jeff Brown2416e092012-08-21 22:12:20 -07001135 private void updateComputedNightModeLocked() {
Adam Lesinski05199e82015-03-19 14:37:11 -07001136 if (mTwilightManager != null) {
Justin Klaassen908b86c2016-08-08 09:18:42 -07001137 TwilightState state = mTwilightManager.getLastTwilightState();
Adam Lesinski05199e82015-03-19 14:37:11 -07001138 if (state != null) {
1139 mComputedNightMode = state.isNight();
1140 }
Jay Aliomer381e3302019-10-24 13:18:06 -04001141 if (mNightModeOverride == UiModeManager.MODE_NIGHT_YES && !mComputedNightMode) {
1142 mComputedNightMode = true;
1143 return;
1144 }
1145 if (mNightModeOverride == UiModeManager.MODE_NIGHT_NO && mComputedNightMode) {
1146 mComputedNightMode = false;
1147 return;
1148 }
1149
1150 mNightModeOverride = mNightMode;
1151 final int user = UserHandle.getCallingUserId();
1152 Secure.putIntForUser(getContext().getContentResolver(),
1153 OVERRIDE_NIGHT_MODE, mNightModeOverride, user);
Dianne Hackborn7299c412010-03-04 18:41:49 -08001154 }
Dianne Hackborn7299c412010-03-04 18:41:49 -08001155 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +01001156
Zak Cohen1a705732017-01-09 12:54:34 -08001157 private void registerVrStateListener() {
Craig Donner8deb67c2017-02-07 18:10:32 -08001158 IVrManager vrManager = IVrManager.Stub.asInterface(ServiceManager.getService(
1159 Context.VR_SERVICE));
Zak Cohen1a705732017-01-09 12:54:34 -08001160 try {
1161 if (vrManager != null) {
1162 vrManager.registerListener(mVrStateCallbacks);
1163 }
1164 } catch (RemoteException e) {
1165 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
1166 }
1167 }
Bernd Holzheyba9ab182010-03-12 09:30:29 +01001168
Alan Viveretteba0d98f2017-01-30 10:36:54 -05001169 /**
1170 * Handles "adb shell" commands.
1171 */
1172 private static class Shell extends ShellCommand {
1173 public static final String NIGHT_MODE_STR_YES = "yes";
1174 public static final String NIGHT_MODE_STR_NO = "no";
1175 public static final String NIGHT_MODE_STR_AUTO = "auto";
1176 public static final String NIGHT_MODE_STR_UNKNOWN = "unknown";
1177 private final IUiModeManager mInterface;
1178
1179 Shell(IUiModeManager iface) {
1180 mInterface = iface;
1181 }
1182
1183 @Override
1184 public void onHelp() {
1185 final PrintWriter pw = getOutPrintWriter();
1186 pw.println("UiModeManager service (uimode) commands:");
1187 pw.println(" help");
1188 pw.println(" Print this help text.");
1189 pw.println(" night [yes|no|auto]");
1190 pw.println(" Set or read night mode.");
1191 }
1192
1193 @Override
1194 public int onCommand(String cmd) {
1195 if (cmd == null) {
1196 return handleDefaultCommands(cmd);
1197 }
1198
1199 try {
1200 switch (cmd) {
1201 case "night":
1202 return handleNightMode();
1203 default:
1204 return handleDefaultCommands(cmd);
1205 }
1206 } catch (RemoteException e) {
1207 final PrintWriter err = getErrPrintWriter();
1208 err.println("Remote exception: " + e);
1209 }
1210 return -1;
1211 }
1212
1213 private int handleNightMode() throws RemoteException {
1214 final PrintWriter err = getErrPrintWriter();
1215 final String modeStr = getNextArg();
1216 if (modeStr == null) {
1217 printCurrentNightMode();
1218 return 0;
1219 }
1220
1221 final int mode = strToNightMode(modeStr);
1222 if (mode >= 0) {
1223 mInterface.setNightMode(mode);
1224 printCurrentNightMode();
1225 return 0;
1226 } else {
1227 err.println("Error: mode must be '" + NIGHT_MODE_STR_YES + "', '"
1228 + NIGHT_MODE_STR_NO + "', or '" + NIGHT_MODE_STR_AUTO + "'");
1229 return -1;
1230 }
1231 }
1232
1233 private void printCurrentNightMode() throws RemoteException {
1234 final PrintWriter pw = getOutPrintWriter();
1235 final int currMode = mInterface.getNightMode();
1236 final String currModeStr = nightModeToStr(currMode);
1237 pw.println("Night mode: " + currModeStr);
1238 }
1239
1240 private static String nightModeToStr(int mode) {
1241 switch (mode) {
1242 case UiModeManager.MODE_NIGHT_YES:
1243 return NIGHT_MODE_STR_YES;
1244 case UiModeManager.MODE_NIGHT_NO:
1245 return NIGHT_MODE_STR_NO;
1246 case UiModeManager.MODE_NIGHT_AUTO:
1247 return NIGHT_MODE_STR_AUTO;
1248 default:
1249 return NIGHT_MODE_STR_UNKNOWN;
1250 }
1251 }
1252
1253 private static int strToNightMode(String modeStr) {
1254 switch (modeStr) {
1255 case NIGHT_MODE_STR_YES:
1256 return UiModeManager.MODE_NIGHT_YES;
1257 case NIGHT_MODE_STR_NO:
1258 return UiModeManager.MODE_NIGHT_NO;
1259 case NIGHT_MODE_STR_AUTO:
1260 return UiModeManager.MODE_NIGHT_AUTO;
1261 default:
1262 return -1;
1263 }
1264 }
1265 }
Felipe Lemeff9ec382018-09-24 11:07:56 -07001266
1267 public final class LocalService extends UiModeManagerInternal {
1268
1269 @Override
1270 public boolean isNightMode() {
1271 synchronized (mLock) {
1272 final boolean isIt = (mConfiguration.uiMode & Configuration.UI_MODE_NIGHT_YES) != 0;
1273 if (LOG) {
1274 Slog.d(TAG,
1275 "LocalService.isNightMode(): mNightMode=" + mNightMode
1276 + "; mComputedNightMode=" + mComputedNightMode
1277 + "; uiMode=" + mConfiguration.uiMode
1278 + "; isIt=" + isIt);
1279 }
1280 return isIt;
1281 }
1282 }
1283 }
Salvador Martinez2f792ef2018-09-26 17:33:51 -07001284
1285 private final class UserSwitchedReceiver extends BroadcastReceiver {
1286 @Override
1287 public void onReceive(Context context, Intent intent) {
1288 synchronized (mLock) {
1289 final int currentId = intent.getIntExtra(
1290 Intent.EXTRA_USER_HANDLE, UserHandle.USER_SYSTEM);
1291 // only update if the value is actually changed
1292 if (updateNightModeFromSettings(context, context.getResources(), currentId)) {
1293 updateLocked(0, 0);
1294 }
1295 }
1296 }
1297 }
Dianne Hackborn7299c412010-03-04 18:41:49 -08001298}