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.settings.widget;
18 
19 import android.content.Context;
20 import android.text.TextUtils;
21 
22 /**
23  * Helper class that listens to settings changes and notifies client when there is update in
24  * corresponding summary info.
25  */
26 public abstract class SummaryUpdater {
27 
28     protected final Context mContext;
29 
30     private final OnSummaryChangeListener mListener;
31     private String mSummary;
32 
33     /**
34      * Interface definition for a callback to be invoked when the summary has been changed.
35      */
36     public interface OnSummaryChangeListener {
37         /**
38          * Called when summary has changed.
39          *
40          * @param summary The new summary .
41          */
onSummaryChanged(String summary)42         void onSummaryChanged(String summary);
43     }
44 
45     /**
46      * Constructor
47      *
48      * @param context The Context the updater is running in, through which it can register broadcast
49      * receiver etc.
50      * @param listener The listener that would like to receive summary change notification.
51      *
52      */
SummaryUpdater(Context context, OnSummaryChangeListener listener)53     public SummaryUpdater(Context context, OnSummaryChangeListener listener) {
54         mContext = context;
55         mListener = listener;
56     }
57 
58     /**
59      * Notifies the listener when there is update in summary
60      */
notifyChangeIfNeeded()61     protected void notifyChangeIfNeeded() {
62         String summary = getSummary();
63         if (!TextUtils.equals(mSummary, summary)) {
64             mSummary = summary;
65             if (mListener != null) {
66                 mListener.onSummaryChanged(summary);
67             }
68         }
69     }
70 
71     /**
72      * Starts/stops receiving updates on the summary.
73      *
74      * @param register true if we want to receive updates, false otherwise
75      */
register(boolean register)76     public abstract void register(boolean register);
77 
78     /**
79      * Gets the summary. Subclass should checks latest conditions and update the summary
80      * accordingly.
81      *
82      * @return  the latest summary text
83      */
getSummary()84     protected abstract String getSummary();
85 
86 }
87