MobileDataControllerImpl.java revision 36ffb0494dd1045c164b7479b68165e206f8c759
1/*
2 * Copyright (C) 2014 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
17package com.android.systemui.statusbar.policy;
18
19import static android.net.ConnectivityManager.TYPE_MOBILE;
20import static android.net.NetworkStatsHistory.FIELD_RX_BYTES;
21import static android.net.NetworkStatsHistory.FIELD_TX_BYTES;
22import static android.telephony.TelephonyManager.SIM_STATE_READY;
23import static android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
24import static android.text.format.DateUtils.FORMAT_SHOW_DATE;
25
26import android.content.Context;
27import android.net.ConnectivityManager;
28import android.net.INetworkStatsService;
29import android.net.INetworkStatsSession;
30import android.net.NetworkPolicy;
31import android.net.NetworkPolicyManager;
32import android.net.NetworkStatsHistory;
33import android.net.NetworkTemplate;
34import android.os.RemoteException;
35import android.os.ServiceManager;
36import android.telephony.SubscriptionManager;
37import android.telephony.TelephonyManager;
38import android.text.format.DateUtils;
39import android.text.format.Time;
40import android.util.Log;
41
42import java.util.Date;
43import java.util.Locale;
44
45public class MobileDataControllerImpl implements NetworkController.MobileDataController {
46    private static final String TAG = "MobileDataController";
47    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
48
49    private static final long DEFAULT_WARNING_LEVEL = 2L * 1024 * 1024 * 1024;
50    private static final int FIELDS = FIELD_RX_BYTES | FIELD_TX_BYTES;
51    private static final StringBuilder PERIOD_BUILDER = new StringBuilder(50);
52    private static final java.util.Formatter PERIOD_FORMATTER = new java.util.Formatter(
53            PERIOD_BUILDER, Locale.getDefault());
54
55    private final Context mContext;
56    private final TelephonyManager mTelephonyManager;
57    private final ConnectivityManager mConnectivityManager;
58    private final INetworkStatsService mStatsService;
59    private final NetworkPolicyManager mPolicyManager;
60
61    private INetworkStatsSession mSession;
62    private Callback mCallback;
63    private NetworkControllerImpl mNetworkController;
64
65    public MobileDataControllerImpl(Context context) {
66        mContext = context;
67        mTelephonyManager = TelephonyManager.from(context);
68        mConnectivityManager = ConnectivityManager.from(context);
69        mStatsService = INetworkStatsService.Stub.asInterface(
70                ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
71        mPolicyManager = NetworkPolicyManager.from(mContext);
72    }
73
74    public void setNetworkController(NetworkControllerImpl networkController) {
75        mNetworkController = networkController;
76    }
77
78    private INetworkStatsSession getSession() {
79        if (mSession == null) {
80            try {
81                mSession = mStatsService.openSession();
82            } catch (RemoteException e) {
83                Log.w(TAG, "Failed to open stats session", e);
84            } catch (RuntimeException e) {
85                Log.w(TAG, "Failed to open stats session", e);
86            }
87        }
88        return mSession;
89    }
90
91    public void setCallback(Callback callback) {
92        mCallback = callback;
93    }
94
95    private DataUsageInfo warn(String msg) {
96        Log.w(TAG, "Failed to get data usage, " + msg);
97        return null;
98    }
99
100    private static Time addMonth(Time t, int months) {
101        final Time rt = new Time(t);
102        rt.set(t.monthDay, t.month + months, t.year);
103        rt.normalize(false);
104        return rt;
105    }
106
107    public DataUsageInfo getDataUsageInfo() {
108        final String subscriberId = getActiveSubscriberId(mContext);
109        if (subscriberId == null) {
110            return warn("no subscriber id");
111        }
112        final INetworkStatsSession session = getSession();
113        if (session == null) {
114            return warn("no stats session");
115        }
116        final NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriberId);
117        final NetworkPolicy policy = findNetworkPolicy(template);
118        try {
119            final NetworkStatsHistory history = mSession.getHistoryForNetwork(template, FIELDS);
120            final long now = System.currentTimeMillis();
121            final long start, end;
122            if (policy != null && policy.cycleDay > 0) {
123                // period = determined from cycleDay
124                if (DEBUG) Log.d(TAG, "Cycle day=" + policy.cycleDay + " tz="
125                        + policy.cycleTimezone);
126                final Time nowTime = new Time(policy.cycleTimezone);
127                nowTime.setToNow();
128                final Time policyTime = new Time(nowTime);
129                policyTime.set(policy.cycleDay, policyTime.month, policyTime.year);
130                policyTime.normalize(false);
131                if (nowTime.after(policyTime)) {
132                    start = policyTime.toMillis(false);
133                    end = addMonth(policyTime, 1).toMillis(false);
134                } else {
135                    start = addMonth(policyTime, -1).toMillis(false);
136                    end = policyTime.toMillis(false);
137                }
138            } else {
139                // period = last 4 wks
140                end = now;
141                start = now - DateUtils.WEEK_IN_MILLIS * 4;
142            }
143            final long callStart = System.currentTimeMillis();
144            final NetworkStatsHistory.Entry entry = history.getValues(start, end, now, null);
145            final long callEnd = System.currentTimeMillis();
146            if (DEBUG) Log.d(TAG, String.format("history call from %s to %s now=%s took %sms: %s",
147                    new Date(start), new Date(end), new Date(now), callEnd - callStart,
148                    historyEntryToString(entry)));
149            if (entry == null) {
150                return warn("no entry data");
151            }
152            final long totalBytes = entry.rxBytes + entry.txBytes;
153            final DataUsageInfo usage = new DataUsageInfo();
154            usage.usageLevel = totalBytes;
155            usage.period = formatDateRange(start, end);
156            if (policy != null) {
157                usage.limitLevel = policy.limitBytes > 0 ? policy.limitBytes : 0;
158                usage.warningLevel = policy.warningBytes > 0 ? policy.warningBytes : 0;
159            } else {
160                usage.warningLevel = DEFAULT_WARNING_LEVEL;
161            }
162            if (usage != null) {
163                usage.carrier = mNetworkController.getMobileNetworkName();
164            }
165            return usage;
166        } catch (RemoteException e) {
167            return warn("remote call failed");
168        }
169    }
170
171    private NetworkPolicy findNetworkPolicy(NetworkTemplate template) {
172        if (mPolicyManager == null || template == null) return null;
173        final NetworkPolicy[] policies = mPolicyManager.getNetworkPolicies();
174        if (policies == null) return null;
175        final int N = policies.length;
176        for (int i = 0; i < N; i++) {
177            final NetworkPolicy policy = policies[i];
178            if (policy != null && template.equals(policy.template)) {
179                return policy;
180            }
181        }
182        return null;
183    }
184
185    private static String historyEntryToString(NetworkStatsHistory.Entry entry) {
186        return entry == null ? null : new StringBuilder("Entry[")
187                .append("bucketDuration=").append(entry.bucketDuration)
188                .append(",bucketStart=").append(entry.bucketStart)
189                .append(",activeTime=").append(entry.activeTime)
190                .append(",rxBytes=").append(entry.rxBytes)
191                .append(",rxPackets=").append(entry.rxPackets)
192                .append(",txBytes=").append(entry.txBytes)
193                .append(",txPackets=").append(entry.txPackets)
194                .append(",operations=").append(entry.operations)
195                .append(']').toString();
196    }
197
198    public void setMobileDataEnabled(boolean enabled) {
199        Log.d(TAG, "setMobileDataEnabled: enabled=" + enabled);
200        mTelephonyManager.setDataEnabled(enabled);
201        if (mCallback != null) {
202            mCallback.onMobileDataEnabled(enabled);
203        }
204    }
205
206    public boolean isMobileDataSupported() {
207        // require both supported network and ready SIM
208        return mConnectivityManager.isNetworkSupported(TYPE_MOBILE)
209                && mTelephonyManager.getSimState() == SIM_STATE_READY;
210    }
211
212    public boolean isMobileDataEnabled() {
213        return mTelephonyManager.getDataEnabled();
214    }
215
216    private static String getActiveSubscriberId(Context context) {
217        final TelephonyManager tele = TelephonyManager.from(context);
218        final String actualSubscriberId = tele.getSubscriberId(
219                SubscriptionManager.getDefaultDataSubId());
220        return actualSubscriberId;
221    }
222
223    private String formatDateRange(long start, long end) {
224        final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
225        synchronized (PERIOD_BUILDER) {
226            PERIOD_BUILDER.setLength(0);
227            return DateUtils.formatDateRange(mContext, PERIOD_FORMATTER, start, end, flags, null)
228                    .toString();
229        }
230    }
231
232    public interface Callback {
233        void onMobileDataEnabled(boolean enabled);
234    }
235}
236