• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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.documentsui.prefs;
18 
19 import android.app.backup.BackupManager;
20 import android.content.SharedPreferences;
21 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
22 
23 import com.android.documentsui.base.ApplicationScope;
24 
25 import java.util.function.Consumer;
26 
27 /**
28  * A class that monitors changes to the default shared preferences file. If a preference which
29  * should be backed up changed, schedule a backup.
30  *
31  * Also, notifies a callback when such changes are noticed. This is the key mechanism by which
32  * we learn about preference changes in other instances of the app.
33  */
34 public final class PreferencesMonitor {
35 
36     private final String mPackageName;
37     private final SharedPreferences mPrefs;
38     private final OnSharedPreferenceChangeListener mListener = this::onSharedPreferenceChanged;
39     private final Consumer<String> mChangeCallback;
40 
PreferencesMonitor( @pplicationScope String packageName, SharedPreferences prefs, Consumer<String> listener)41     public PreferencesMonitor(
42             @ApplicationScope String packageName,
43             SharedPreferences prefs,
44             Consumer<String> listener) {
45 
46         mPackageName = packageName;
47         mPrefs = prefs;
48         mChangeCallback = listener;
49     }
50 
start()51     public void start() {
52         mPrefs.registerOnSharedPreferenceChangeListener(mListener);
53     }
54 
stop()55     public void stop() {
56         mPrefs.unregisterOnSharedPreferenceChangeListener(mListener);
57     }
58 
59     // visible for use as a lambda, otherwise treat as a private.
onSharedPreferenceChanged(SharedPreferences prefs, String key)60     void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
61         if (Preferences.shouldBackup(key)) {
62             mChangeCallback.accept(key);
63             BackupManager.dataChanged(mPackageName);
64         }
65     }
66 }
67