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.internal.telephony; 18 19 import android.content.ContentResolver; 20 import android.content.Context; 21 import android.database.ContentObserver; 22 import android.net.Uri; 23 import android.os.Handler; 24 25 import com.android.telephony.Rlog; 26 27 import java.util.HashMap; 28 import java.util.Map; 29 30 /** 31 * The class to describe settings observer 32 */ 33 public class SettingsObserver extends ContentObserver { 34 private final Map<Uri, Integer> mUriEventMap; 35 private final Context mContext; 36 private final Handler mHandler; 37 private static final String TAG = "SettingsObserver"; 38 SettingsObserver(Context context, Handler handler)39 public SettingsObserver(Context context, Handler handler) { 40 super(null); 41 mUriEventMap = new HashMap<>(); 42 mContext = context; 43 mHandler = handler; 44 } 45 46 /** 47 * Start observing a content. 48 * @param uri Content URI 49 * @param what The event to fire if the content changes 50 */ observe(Uri uri, int what)51 public void observe(Uri uri, int what) { 52 mUriEventMap.put(uri, what); 53 final ContentResolver resolver = mContext.getContentResolver(); 54 resolver.registerContentObserver(uri, false, this); 55 } 56 57 /** 58 * Stop observing a content. 59 */ unobserve()60 public void unobserve() { 61 final ContentResolver resolver = mContext.getContentResolver(); 62 resolver.unregisterContentObserver(this); 63 } 64 65 @Override onChange(boolean selfChange)66 public void onChange(boolean selfChange) { 67 Rlog.e(TAG, "Should never be reached."); 68 } 69 70 @Override onChange(boolean selfChange, Uri uri)71 public void onChange(boolean selfChange, Uri uri) { 72 final Integer what = mUriEventMap.get(uri); 73 if (what != null) { 74 mHandler.obtainMessage(what.intValue()).sendToTarget(); 75 } else { 76 Rlog.e(TAG, "No matching event to send for URI=" + uri); 77 } 78 } 79 } 80