1 /* 2 * Copyright (C) 2015 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 17 package com.android.tv.common.feature; 18 19 import android.content.Context; 20 import android.content.SharedPreferences; 21 import android.util.Log; 22 import com.android.tv.common.util.SharedPreferencesUtils; 23 24 /** Feature controlled by shared preferences. */ 25 public final class SharedPreferencesFeature implements Feature { 26 private static final String TAG = "SharedPrefFeature"; 27 private static final boolean DEBUG = false; 28 29 private final String mKey; 30 private boolean mEnabled; 31 private final boolean mDefaultValue; 32 private SharedPreferences mSharedPreferences; 33 private final Feature mBaseFeature; 34 35 /** 36 * Create SharedPreferences controlled feature. 37 * 38 * @param key the SharedPreferences key. 39 * @param defaultValue the value to return if the property is undefined or empty. 40 * @param baseFeature if {@code baseFeature} is turned off, this feature is always disabled. 41 */ SharedPreferencesFeature(String key, boolean defaultValue, Feature baseFeature)42 public SharedPreferencesFeature(String key, boolean defaultValue, Feature baseFeature) { 43 mKey = key; 44 mDefaultValue = defaultValue; 45 mBaseFeature = baseFeature; 46 } 47 48 @Override isEnabled(Context context)49 public boolean isEnabled(Context context) { 50 if (!mBaseFeature.isEnabled(context)) { 51 return false; 52 } 53 if (mSharedPreferences == null) { 54 mSharedPreferences = 55 context.getSharedPreferences( 56 SharedPreferencesUtils.SHARED_PREF_FEATURES, Context.MODE_PRIVATE); 57 mEnabled = mSharedPreferences.getBoolean(mKey, mDefaultValue); 58 } 59 if (DEBUG) Log.d(TAG, mKey + " is " + mEnabled); 60 return mEnabled; 61 } 62 63 @Override toString()64 public String toString() { 65 return "SharedPreferencesFeature:key=" + mKey + ",value=" + mEnabled; 66 } 67 setEnabled(Context context, boolean enable)68 public void setEnabled(Context context, boolean enable) { 69 if (DEBUG) Log.d(TAG, mKey + " is set to " + enable); 70 if (mSharedPreferences == null) { 71 mSharedPreferences = 72 context.getSharedPreferences( 73 SharedPreferencesUtils.SHARED_PREF_FEATURES, Context.MODE_PRIVATE); 74 mEnabled = enable; 75 mSharedPreferences.edit().putBoolean(mKey, enable).apply(); 76 } else if (mEnabled != enable) { 77 mEnabled = enable; 78 mSharedPreferences.edit().putBoolean(mKey, enable).apply(); 79 } 80 } 81 } 82