2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server;
19 import android.annotation.Nullable;
20 import android.app.Activity;
21 import android.app.ActivityManager;
22 import android.app.ActivityManagerNative;
23 import android.app.IUiModeManager;
24 import android.app.Notification;
25 import android.app.NotificationManager;
26 import android.app.PendingIntent;
27 import android.app.StatusBarManager;
28 import android.app.UiModeManager;
29 import android.content.BroadcastReceiver;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.pm.PackageManager;
34 import android.content.res.Configuration;
35 import android.content.res.Resources;
36 import android.os.BatteryManager;
37 import android.os.Binder;
38 import android.os.Handler;
39 import android.os.IBinder;
40 import android.os.PowerManager;
41 import android.os.RemoteException;
42 import android.os.UserHandle;
43 import android.provider.Settings;
44 import android.service.dreams.Sandman;
45 import android.util.Slog;
47 import java.io.FileDescriptor;
48 import java.io.PrintWriter;
50 import com.android.internal.R;
51 import com.android.internal.app.DisableCarModeActivity;
52 import com.android.server.twilight.TwilightListener;
53 import com.android.server.twilight.TwilightManager;
54 import com.android.server.twilight.TwilightState;
56 final class UiModeManagerService extends SystemService {
57 private static final String TAG = UiModeManager.class.getSimpleName();
58 private static final boolean LOG = false;
60 // Enable launching of applications when entering the dock.
61 private static final boolean ENABLE_LAUNCH_DESK_DOCK_APP = true;
63 final Object mLock = new Object();
64 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
66 private int mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
67 private int mNightMode = UiModeManager.MODE_NIGHT_NO;
69 private boolean mCarModeEnabled = false;
70 private boolean mCharging = false;
71 private int mDefaultUiModeType;
72 private boolean mCarModeKeepsScreenOn;
73 private boolean mDeskModeKeepsScreenOn;
74 private boolean mTelevision;
75 private boolean mWatch;
76 private boolean mComputedNightMode;
77 private int mCarModeEnableFlags;
79 // flag set by resource, whether to enable Car dock launch when starting car mode.
80 private boolean mEnableCarDockLaunch = true;
81 // flag set by resource, whether to lock UI mode to the default one or not.
82 private boolean mUiModeLocked = false;
83 // flag set by resource, whether to night mode change for normal all or not.
84 private boolean mNightModeLocked = false;
87 private int mSetUiMode = 0;
88 private boolean mHoldingConfiguration = false;
90 private Configuration mConfiguration = new Configuration();
93 private final Handler mHandler = new Handler();
95 private TwilightManager mTwilightManager;
96 private NotificationManager mNotificationManager;
97 private StatusBarManager mStatusBarManager;
99 private PowerManager.WakeLock mWakeLock;
101 public UiModeManagerService(Context context) {
105 private static Intent buildHomeIntent(String category) {
106 Intent intent = new Intent(Intent.ACTION_MAIN);
107 intent.addCategory(category);
108 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
109 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
113 // The broadcast receiver which receives the result of the ordered broadcast sent when
114 // the dock state changes. The original ordered broadcast is sent with an initial result
115 // code of RESULT_OK. If any of the registered broadcast receivers changes this value, e.g.,
116 // to RESULT_CANCELED, then the intent to start a dock app will not be sent.
117 private final BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
119 public void onReceive(Context context, Intent intent) {
120 if (getResultCode() != Activity.RESULT_OK) {
122 Slog.v(TAG, "Handling broadcast result for action " + intent.getAction()
123 + ": canceled: " + getResultCode());
128 final int enableFlags = intent.getIntExtra("enableFlags", 0);
129 final int disableFlags = intent.getIntExtra("disableFlags", 0);
130 synchronized (mLock) {
131 updateAfterBroadcastLocked(intent.getAction(), enableFlags, disableFlags);
136 private final BroadcastReceiver mDockModeReceiver = new BroadcastReceiver() {
138 public void onReceive(Context context, Intent intent) {
139 int state = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
140 Intent.EXTRA_DOCK_STATE_UNDOCKED);
141 updateDockState(state);
145 private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
147 public void onReceive(Context context, Intent intent) {
148 mCharging = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
149 synchronized (mLock) {
157 private final TwilightListener mTwilightListener = new TwilightListener() {
159 public void onTwilightStateChanged(@Nullable TwilightState state) {
160 synchronized (mLock) {
161 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
162 updateComputedNightModeLocked();
170 public void onStart() {
171 final Context context = getContext();
173 final PowerManager powerManager =
174 (PowerManager) context.getSystemService(Context.POWER_SERVICE);
175 mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
177 context.registerReceiver(mDockModeReceiver,
178 new IntentFilter(Intent.ACTION_DOCK_EVENT));
179 context.registerReceiver(mBatteryReceiver,
180 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
182 mConfiguration.setToDefaults();
184 final Resources res = context.getResources();
185 mDefaultUiModeType = res.getInteger(
186 com.android.internal.R.integer.config_defaultUiModeType);
187 mCarModeKeepsScreenOn = (res.getInteger(
188 com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
189 mDeskModeKeepsScreenOn = (res.getInteger(
190 com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
191 mEnableCarDockLaunch = res.getBoolean(
192 com.android.internal.R.bool.config_enableCarDockHomeLaunch);
193 mUiModeLocked = res.getBoolean(com.android.internal.R.bool.config_lockUiMode);
194 mNightModeLocked = res.getBoolean(com.android.internal.R.bool.config_lockDayNightMode);
196 final PackageManager pm = context.getPackageManager();
197 mTelevision = pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
198 || pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK);
199 mWatch = pm.hasSystemFeature(PackageManager.FEATURE_WATCH);
201 final int defaultNightMode = res.getInteger(
202 com.android.internal.R.integer.config_defaultNightMode);
203 mNightMode = Settings.Secure.getInt(context.getContentResolver(),
204 Settings.Secure.UI_NIGHT_MODE, defaultNightMode);
206 // Update the initial, static configurations.
207 synchronized (this) {
208 updateConfigurationLocked();
209 sendConfigurationLocked();
212 publishBinderService(Context.UI_MODE_SERVICE, mService);
215 private final IBinder mService = new IUiModeManager.Stub() {
217 public void enableCarMode(int flags) {
218 if (isUiModeLocked()) {
219 Slog.e(TAG, "enableCarMode while UI mode is locked");
222 final long ident = Binder.clearCallingIdentity();
224 synchronized (mLock) {
225 setCarModeLocked(true, flags);
227 updateLocked(flags, 0);
231 Binder.restoreCallingIdentity(ident);
236 public void disableCarMode(int flags) {
237 if (isUiModeLocked()) {
238 Slog.e(TAG, "disableCarMode while UI mode is locked");
241 final long ident = Binder.clearCallingIdentity();
243 synchronized (mLock) {
244 setCarModeLocked(false, 0);
246 updateLocked(0, flags);
250 Binder.restoreCallingIdentity(ident);
255 public int getCurrentModeType() {
256 final long ident = Binder.clearCallingIdentity();
258 synchronized (mLock) {
259 return mCurUiMode & Configuration.UI_MODE_TYPE_MASK;
262 Binder.restoreCallingIdentity(ident);
267 public void setNightMode(int mode) {
268 if (isNightModeLocked() && (getContext().checkCallingOrSelfPermission(
269 android.Manifest.permission.MODIFY_DAY_NIGHT_MODE)
270 != PackageManager.PERMISSION_GRANTED)) {
272 "Night mode locked, requires MODIFY_DAY_NIGHT_MODE permission");
276 case UiModeManager.MODE_NIGHT_NO:
277 case UiModeManager.MODE_NIGHT_YES:
278 case UiModeManager.MODE_NIGHT_AUTO:
281 throw new IllegalArgumentException("Unknown mode: " + mode);
284 final long ident = Binder.clearCallingIdentity();
286 synchronized (mLock) {
287 if (mNightMode != mode) {
288 Settings.Secure.putInt(getContext().getContentResolver(),
289 Settings.Secure.UI_NIGHT_MODE, mode);
295 Binder.restoreCallingIdentity(ident);
300 public int getNightMode() {
301 synchronized (mLock) {
307 public boolean isUiModeLocked() {
308 synchronized (mLock) {
309 return mUiModeLocked;
314 public boolean isNightModeLocked() {
315 synchronized (mLock) {
316 return mNightModeLocked;
321 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
322 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
323 != PackageManager.PERMISSION_GRANTED) {
325 pw.println("Permission Denial: can't dump uimode service from from pid="
326 + Binder.getCallingPid()
327 + ", uid=" + Binder.getCallingUid());
335 void dumpImpl(PrintWriter pw) {
336 synchronized (mLock) {
337 pw.println("Current UI Mode Service state:");
338 pw.print(" mDockState="); pw.print(mDockState);
339 pw.print(" mLastBroadcastState="); pw.println(mLastBroadcastState);
340 pw.print(" mNightMode="); pw.print(mNightMode);
341 pw.print(" mNightModeLocked="); pw.print(mNightModeLocked);
342 pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
343 pw.print(" mComputedNightMode="); pw.print(mComputedNightMode);
344 pw.print(" mCarModeEnableFlags="); pw.print(mCarModeEnableFlags);
345 pw.print(" mEnableCarDockLaunch="); pw.println(mEnableCarDockLaunch);
346 pw.print(" mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
347 pw.print(" mUiModeLocked="); pw.print(mUiModeLocked);
348 pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
349 pw.print(" mHoldingConfiguration="); pw.print(mHoldingConfiguration);
350 pw.print(" mSystemReady="); pw.println(mSystemReady);
351 if (mTwilightManager != null) {
352 // We may not have a TwilightManager.
353 pw.print(" mTwilightService.getLastTwilightState()=");
354 pw.println(mTwilightManager.getLastTwilightState());
360 public void onBootPhase(int phase) {
361 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
362 synchronized (mLock) {
363 mTwilightManager = getLocalService(TwilightManager.class);
365 mCarModeEnabled = mDockState == Intent.EXTRA_DOCK_STATE_CAR;
366 updateComputedNightModeLocked();
372 void setCarModeLocked(boolean enabled, int flags) {
373 if (mCarModeEnabled != enabled) {
374 mCarModeEnabled = enabled;
376 mCarModeEnableFlags = flags;
379 private void updateDockState(int newState) {
380 synchronized (mLock) {
381 if (newState != mDockState) {
382 mDockState = newState;
383 setCarModeLocked(mDockState == Intent.EXTRA_DOCK_STATE_CAR, 0);
385 updateLocked(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME, 0);
391 private static boolean isDeskDockState(int state) {
393 case Intent.EXTRA_DOCK_STATE_DESK:
394 case Intent.EXTRA_DOCK_STATE_LE_DESK:
395 case Intent.EXTRA_DOCK_STATE_HE_DESK:
402 private void updateConfigurationLocked() {
403 int uiMode = mDefaultUiModeType;
405 // no-op, keeps default one
406 } else if (mTelevision) {
407 uiMode = Configuration.UI_MODE_TYPE_TELEVISION;
409 uiMode = Configuration.UI_MODE_TYPE_WATCH;
410 } else if (mCarModeEnabled) {
411 uiMode = Configuration.UI_MODE_TYPE_CAR;
412 } else if (isDeskDockState(mDockState)) {
413 uiMode = Configuration.UI_MODE_TYPE_DESK;
416 if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
417 if (mTwilightManager != null) {
418 mTwilightManager.registerListener(mTwilightListener, mHandler);
420 updateComputedNightModeLocked();
421 uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
422 : Configuration.UI_MODE_NIGHT_NO;
424 if (mTwilightManager != null) {
425 mTwilightManager.unregisterListener(mTwilightListener);
427 uiMode |= mNightMode << 4;
432 "updateConfigurationLocked: mDockState=" + mDockState
433 + "; mCarMode=" + mCarModeEnabled
434 + "; mNightMode=" + mNightMode
435 + "; uiMode=" + uiMode);
439 if (!mHoldingConfiguration) {
440 mConfiguration.uiMode = uiMode;
444 private void sendConfigurationLocked() {
445 if (mSetUiMode != mConfiguration.uiMode) {
446 mSetUiMode = mConfiguration.uiMode;
449 ActivityManagerNative.getDefault().updateConfiguration(mConfiguration);
450 } catch (RemoteException e) {
451 Slog.w(TAG, "Failure communicating with activity manager", e);
456 void updateLocked(int enableFlags, int disableFlags) {
457 String action = null;
458 String oldAction = null;
459 if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
460 adjustStatusBarCarModeLocked();
461 oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
462 } else if (isDeskDockState(mLastBroadcastState)) {
463 oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
466 if (mCarModeEnabled) {
467 if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
468 adjustStatusBarCarModeLocked();
470 if (oldAction != null) {
471 getContext().sendBroadcastAsUser(new Intent(oldAction), UserHandle.ALL);
473 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
474 action = UiModeManager.ACTION_ENTER_CAR_MODE;
476 } else if (isDeskDockState(mDockState)) {
477 if (!isDeskDockState(mLastBroadcastState)) {
478 if (oldAction != null) {
479 getContext().sendBroadcastAsUser(new Intent(oldAction), UserHandle.ALL);
481 mLastBroadcastState = mDockState;
482 action = UiModeManager.ACTION_ENTER_DESK_MODE;
485 mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
489 if (action != null) {
491 Slog.v(TAG, String.format(
492 "updateLocked: preparing broadcast: action=%s enable=0x%08x disable=0x%08x",
493 action, enableFlags, disableFlags));
496 // Send the ordered broadcast; the result receiver will receive after all
497 // broadcasts have been sent. If any broadcast receiver changes the result
498 // code from the initial value of RESULT_OK, then the result receiver will
499 // not launch the corresponding dock application. This gives apps a chance
500 // to override the behavior and stay in their app even when the device is
501 // placed into a dock.
502 Intent intent = new Intent(action);
503 intent.putExtra("enableFlags", enableFlags);
504 intent.putExtra("disableFlags", disableFlags);
505 getContext().sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null,
506 mResultReceiver, null, Activity.RESULT_OK, null, null);
508 // Attempting to make this transition a little more clean, we are going
509 // to hold off on doing a configuration change until we have finished
510 // the broadcast and started the home activity.
511 mHoldingConfiguration = true;
512 updateConfigurationLocked();
514 String category = null;
515 if (mCarModeEnabled) {
516 if (mEnableCarDockLaunch
517 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
518 category = Intent.CATEGORY_CAR_DOCK;
520 } else if (isDeskDockState(mDockState)) {
521 if (ENABLE_LAUNCH_DESK_DOCK_APP
522 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
523 category = Intent.CATEGORY_DESK_DOCK;
526 if ((disableFlags & UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
527 category = Intent.CATEGORY_HOME;
532 Slog.v(TAG, "updateLocked: null action, mDockState="
533 + mDockState +", category=" + category);
536 sendConfigurationAndStartDreamOrDockAppLocked(category);
539 // keep screen on when charging and in car mode
540 boolean keepScreenOn = mCharging &&
541 ((mCarModeEnabled && mCarModeKeepsScreenOn &&
542 (mCarModeEnableFlags & UiModeManager.ENABLE_CAR_MODE_ALLOW_SLEEP) == 0) ||
543 (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
544 if (keepScreenOn != mWakeLock.isHeld()) {
553 private void updateAfterBroadcastLocked(String action, int enableFlags, int disableFlags) {
554 // Launch a dock activity
555 String category = null;
556 if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(action)) {
557 // Only launch car home when car mode is enabled and the caller
558 // has asked us to switch to it.
559 if (mEnableCarDockLaunch
560 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
561 category = Intent.CATEGORY_CAR_DOCK;
563 } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(action)) {
564 // Only launch car home when desk mode is enabled and the caller
565 // has asked us to switch to it. Currently re-using the car
566 // mode flag since we don't have a formal API for "desk mode".
567 if (ENABLE_LAUNCH_DESK_DOCK_APP
568 && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
569 category = Intent.CATEGORY_DESK_DOCK;
572 // Launch the standard home app if requested.
573 if ((disableFlags & UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
574 category = Intent.CATEGORY_HOME;
579 Slog.v(TAG, String.format(
580 "Handling broadcast result for action %s: enable=0x%08x, disable=0x%08x, "
582 action, enableFlags, disableFlags, category));
585 sendConfigurationAndStartDreamOrDockAppLocked(category);
588 private void sendConfigurationAndStartDreamOrDockAppLocked(String category) {
589 // Update the configuration but don't send it yet.
590 mHoldingConfiguration = false;
591 updateConfigurationLocked();
593 // Start the dock app, if there is one.
594 boolean dockAppStarted = false;
595 if (category != null) {
596 // Now we are going to be careful about switching the
597 // configuration and starting the activity -- we need to
598 // do this in a specific order under control of the
599 // activity manager, to do it cleanly. So compute the
600 // new config, but don't set it yet, and let the
601 // activity manager take care of both the start and config
603 Intent homeIntent = buildHomeIntent(category);
604 if (Sandman.shouldStartDockApp(getContext(), homeIntent)) {
606 int result = ActivityManagerNative.getDefault().startActivityWithConfig(
607 null, null, homeIntent, null, null, null, 0, 0,
608 mConfiguration, null, UserHandle.USER_CURRENT);
609 if (result >= ActivityManager.START_SUCCESS) {
610 dockAppStarted = true;
611 } else if (result != ActivityManager.START_INTENT_NOT_RESOLVED) {
612 Slog.e(TAG, "Could not start dock app: " + homeIntent
613 + ", startActivityWithConfig result " + result);
615 } catch (RemoteException ex) {
616 Slog.e(TAG, "Could not start dock app: " + homeIntent, ex);
621 // Send the new configuration.
622 sendConfigurationLocked();
624 // If we did not start a dock app, then start dreaming if supported.
625 if (category != null && !dockAppStarted) {
626 Sandman.startDreamWhenDockedIfAppropriate(getContext());
630 private void adjustStatusBarCarModeLocked() {
631 final Context context = getContext();
632 if (mStatusBarManager == null) {
633 mStatusBarManager = (StatusBarManager)
634 context.getSystemService(Context.STATUS_BAR_SERVICE);
637 // Fear not: StatusBarManagerService manages a list of requests to disable
638 // features of the status bar; these are ORed together to form the
639 // active disabled list. So if (for example) the device is locked and
640 // the status bar should be totally disabled, the calls below will
641 // have no effect until the device is unlocked.
642 if (mStatusBarManager != null) {
643 mStatusBarManager.disable(mCarModeEnabled
644 ? StatusBarManager.DISABLE_NOTIFICATION_TICKER
645 : StatusBarManager.DISABLE_NONE);
648 if (mNotificationManager == null) {
649 mNotificationManager = (NotificationManager)
650 context.getSystemService(Context.NOTIFICATION_SERVICE);
653 if (mNotificationManager != null) {
654 if (mCarModeEnabled) {
655 Intent carModeOffIntent = new Intent(context, DisableCarModeActivity.class);
657 Notification.Builder n = new Notification.Builder(context)
658 .setSmallIcon(R.drawable.stat_notify_car_mode)
659 .setDefaults(Notification.DEFAULT_LIGHTS)
662 .setColor(context.getColor(
663 com.android.internal.R.color.system_notification_accent_color))
665 context.getString(R.string.car_mode_disable_notification_title))
667 context.getString(R.string.car_mode_disable_notification_message))
669 PendingIntent.getActivityAsUser(context, 0, carModeOffIntent, 0,
670 null, UserHandle.CURRENT));
671 mNotificationManager.notifyAsUser(null,
672 R.string.car_mode_disable_notification_title, n.build(), UserHandle.ALL);
674 mNotificationManager.cancelAsUser(null,
675 R.string.car_mode_disable_notification_title, UserHandle.ALL);
680 private void updateComputedNightModeLocked() {
681 if (mTwilightManager != null) {
682 TwilightState state = mTwilightManager.getLastTwilightState();
684 mComputedNightMode = state.isNight();