1 /* 2 * Copyright (C) 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 * except in compliance with the License. You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software distributed under the 10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 11 * KIND, either express or implied. See the License for the specific language governing 12 * permissions and limitations under the License. 13 */ 14 15 package com.android.settings.display.darkmode; 16 17 import android.content.Context; 18 import android.content.res.Configuration; 19 import android.os.PowerManager; 20 import android.util.AttributeSet; 21 22 import com.android.settings.R; 23 import com.android.settingslib.PrimarySwitchPreference; 24 25 /** 26 * component for the display settings dark ui summary 27 */ 28 public class DarkModePreference extends PrimarySwitchPreference { 29 30 private DarkModeObserver mDarkModeObserver; 31 private boolean isCatalystEnabled; 32 DarkModePreference(Context context, AttributeSet attrs)33 public DarkModePreference(Context context, AttributeSet attrs) { 34 super(context, attrs); 35 } 36 37 /** 38 * Sets if catalyst is enabled on the preference. 39 */ setCatalystEnabled(boolean catalystEnabled)40 public void setCatalystEnabled(boolean catalystEnabled) { 41 isCatalystEnabled = catalystEnabled; 42 } 43 44 @Override onAttached()45 public void onAttached() { 46 super.onAttached(); 47 if (!isCatalystEnabled) { 48 Context context = getContext(); 49 mDarkModeObserver = new DarkModeObserver(context); 50 Runnable callback = () -> { 51 PowerManager powerManager = context.getSystemService(PowerManager.class); 52 final boolean batterySaver = powerManager.isPowerSaveMode(); 53 final boolean active = (context.getResources().getConfiguration().uiMode 54 & Configuration.UI_MODE_NIGHT_YES) != 0; 55 setSwitchEnabled(!batterySaver); 56 updateSummary(batterySaver, active); 57 }; 58 mDarkModeObserver.subscribe(callback); 59 } 60 } 61 62 @Override onDetached()63 public void onDetached() { 64 super.onDetached(); 65 if (!isCatalystEnabled) { 66 mDarkModeObserver.unsubscribe(); 67 } 68 } 69 updateSummary(boolean batterySaver, boolean active)70 private void updateSummary(boolean batterySaver, boolean active) { 71 if (batterySaver) { 72 final int stringId = active 73 ? R.string.dark_ui_mode_disabled_summary_dark_theme_on 74 : R.string.dark_ui_mode_disabled_summary_dark_theme_off; 75 setSummary(getContext().getString(stringId)); 76 } else { 77 setSummary(AutoDarkTheme.getStatus(getContext(), active)); 78 } 79 } 80 } 81