1 /* 2 * Copyright (C) 2016 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 package com.android.settings.display; 15 16 import android.app.UiModeManager; 17 import android.content.Context; 18 import android.support.v7.preference.ListPreference; 19 import android.support.v7.preference.Preference; 20 import android.support.v7.preference.PreferenceScreen; 21 import android.util.Log; 22 23 import com.android.settings.core.PreferenceController; 24 25 import static android.content.Context.UI_MODE_SERVICE; 26 27 public class NightModePreferenceController extends PreferenceController 28 implements Preference.OnPreferenceChangeListener { 29 30 private static final String TAG = "NightModePrefContr"; 31 private static final String KEY_NIGHT_MODE = "night_mode"; 32 33 public NightModePreferenceController(Context context) { 34 super(context); 35 } 36 37 @Override 38 public boolean isAvailable() { 39 return false; 40 } 41 42 @Override 43 public String getPreferenceKey() { 44 return KEY_NIGHT_MODE; 45 } 46 47 @Override 48 public void displayPreference(PreferenceScreen screen) { 49 if (!isAvailable()) { 50 removePreference(screen, KEY_NIGHT_MODE); 51 return; 52 } 53 ListPreference mNightModePreference = (ListPreference) screen.findPreference( 54 KEY_NIGHT_MODE); 55 if (mNightModePreference != null) { 56 final UiModeManager uiManager = 57 (UiModeManager) mContext.getSystemService(UI_MODE_SERVICE); 58 final int currentNightMode = uiManager.getNightMode(); 59 mNightModePreference.setValue(String.valueOf(currentNightMode)); 60 mNightModePreference.setOnPreferenceChangeListener(this); 61 } 62 } 63 64 @Override 65 public boolean onPreferenceChange(Preference preference, Object newValue) { 66 try { 67 final int value = Integer.parseInt((String) newValue); 68 final UiModeManager uiManager = 69 (UiModeManager) mContext.getSystemService(UI_MODE_SERVICE); 70 uiManager.setNightMode(value); 71 } catch (NumberFormatException e) { 72 Log.e(TAG, "could not persist night mode setting", e); 73 return false; 74 } 75 return true; 76 } 77 } 78