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.settings.network;
18 
19 import android.content.Context;
20 import android.database.ContentObserver;
21 import android.net.Uri;
22 import android.os.Handler;
23 import android.provider.Settings;
24 import android.telephony.TelephonyManager;
25 
26 /**
27  * {@link ContentObserver} to listen to update of mobile data change
28  */
29 public class MobileDataContentObserver extends ContentObserver {
30     private OnMobileDataChangedListener mListener;
31 
MobileDataContentObserver(Handler handler)32     public MobileDataContentObserver(Handler handler) {
33         super(handler);
34     }
35 
36     /**
37      * Return a URI of mobile data(ON vs OFF)
38      */
getObservableUri(Context context, int subId)39     public static Uri getObservableUri(Context context, int subId) {
40         Uri uri = Settings.Global.getUriFor(Settings.Global.MOBILE_DATA);
41         TelephonyManager telephonyManager = context.getSystemService(TelephonyManager.class);
42         if (telephonyManager.getActiveModemCount() != 1) {
43             uri = Settings.Global.getUriFor(Settings.Global.MOBILE_DATA + subId);
44         }
45         return uri;
46     }
47 
setOnMobileDataChangedListener(OnMobileDataChangedListener lsn)48     public void setOnMobileDataChangedListener(OnMobileDataChangedListener lsn) {
49         mListener = lsn;
50     }
51 
52     @Override
onChange(boolean selfChange)53     public void onChange(boolean selfChange) {
54         super.onChange(selfChange);
55         if (mListener != null) {
56             mListener.onMobileDataChanged();
57         }
58     }
59 
register(Context context, int subId)60     public void register(Context context, int subId) {
61         final Uri uri = getObservableUri(context, subId);
62         context.getContentResolver().registerContentObserver(uri, false, this);
63 
64     }
65 
unRegister(Context context)66     public void unRegister(Context context) {
67         context.getContentResolver().unregisterContentObserver(this);
68     }
69 
70     /**
71      * Listener for update of mobile data(ON vs OFF)
72      */
73     public interface OnMobileDataChangedListener {
onMobileDataChanged()74         void onMobileDataChanged();
75     }
76 }
77