1 /* 2 * Copyright (C) 2019 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.car.dialer.livedata; 18 19 import android.content.Context; 20 import android.content.SharedPreferences; 21 import android.text.TextUtils; 22 23 import androidx.annotation.StringRes; 24 import androidx.lifecycle.LiveData; 25 import androidx.preference.PreferenceManager; 26 27 import com.android.car.dialer.log.L; 28 29 /** 30 * Provides SharedPreferences. 31 */ 32 public class SharedPreferencesLiveData extends LiveData<SharedPreferences> { 33 private static final String TAG = "CD.PreferenceLiveData"; 34 35 private final SharedPreferences mSharedPreferences; 36 private final String mKey; 37 38 private final SharedPreferences.OnSharedPreferenceChangeListener 39 mOnSharedPreferenceChangeListener; 40 SharedPreferencesLiveData(Context context, String key)41 public SharedPreferencesLiveData(Context context, String key) { 42 mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); 43 mKey = key; 44 45 mOnSharedPreferenceChangeListener = (sharedPreferences, k) -> { 46 if (TextUtils.equals(k, mKey)) { 47 updateSharedPreferences(); 48 } 49 }; 50 } 51 SharedPreferencesLiveData(Context context, @StringRes int key)52 public SharedPreferencesLiveData(Context context, @StringRes int key) { 53 this(context, context.getString(key)); 54 } 55 56 @Override onActive()57 protected void onActive() { 58 updateSharedPreferences(); 59 mSharedPreferences.registerOnSharedPreferenceChangeListener( 60 mOnSharedPreferenceChangeListener); 61 } 62 63 @Override onInactive()64 protected void onInactive() { 65 mSharedPreferences.unregisterOnSharedPreferenceChangeListener( 66 mOnSharedPreferenceChangeListener); 67 } 68 updateSharedPreferences()69 private void updateSharedPreferences() { 70 L.i(TAG, "Update SharedPreferences"); 71 setValue(mSharedPreferences); 72 } 73 74 /** 75 * Returns the monitored shared preference key. 76 */ getKey()77 public String getKey() { 78 return mKey; 79 } 80 } 81