blob: 0b5d2959be8bbcc401532677220d84e45d3bc833 [file] [log] [blame]
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001/*
2 * Copyright (C) 2011 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.settings;
18
Jeff Sharkey9549e9f2011-07-14 20:01:13 -070019import static android.net.ConnectivityManager.TYPE_ETHERNET;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070020import static android.net.ConnectivityManager.TYPE_MOBILE;
21import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -070022import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -070023import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070024import static android.net.NetworkPolicyManager.POLICY_NONE;
25import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkey8a503642011-06-10 13:31:21 -070026import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
27import static android.net.NetworkPolicyManager.computeNextCycleBoundary;
Jeff Sharkeya662e492011-06-18 21:57:06 -070028import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
29import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
30import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
31import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -070032import static android.net.NetworkTemplate.buildTemplateEthernet;
33import static android.net.NetworkTemplate.buildTemplateMobile3gLower;
34import static android.net.NetworkTemplate.buildTemplateMobile4g;
35import static android.net.NetworkTemplate.buildTemplateMobileAll;
36import static android.net.NetworkTemplate.buildTemplateWifi;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070037import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070038
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070039import android.animation.LayoutTransition;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070040import android.app.AlertDialog;
41import android.app.Dialog;
42import android.app.DialogFragment;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070043import android.app.Fragment;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070044import android.app.FragmentTransaction;
Jeff Sharkey398b18f2011-07-10 18:56:30 -070045import android.app.LoaderManager.LoaderCallbacks;
Jeff Sharkey9fab0da2011-07-09 17:52:31 -070046import android.content.ContentResolver;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070047import android.content.Context;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070048import android.content.DialogInterface;
Jeff Sharkey4dfa6602011-06-13 00:42:03 -070049import android.content.Intent;
Jeff Sharkey398b18f2011-07-10 18:56:30 -070050import android.content.Loader;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070051import android.content.SharedPreferences;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070052import android.content.pm.ApplicationInfo;
53import android.content.pm.PackageInfo;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070054import android.content.pm.PackageManager;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070055import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -070056import android.content.res.Resources;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070057import android.net.ConnectivityManager;
Jeff Sharkey8a503642011-06-10 13:31:21 -070058import android.net.INetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070059import android.net.INetworkStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -070060import android.net.NetworkPolicy;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -070061import android.net.NetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070062import android.net.NetworkStats;
63import android.net.NetworkStatsHistory;
Jeff Sharkeya662e492011-06-18 21:57:06 -070064import android.net.NetworkTemplate;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -070065import android.net.TrafficStats;
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -070066import android.os.AsyncTask;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070067import android.os.Bundle;
68import android.os.RemoteException;
69import android.os.ServiceManager;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -070070import android.os.SystemProperties;
Jeff Sharkey8a503642011-06-10 13:31:21 -070071import android.preference.Preference;
Jeff Sharkey9fab0da2011-07-09 17:52:31 -070072import android.provider.Settings;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -070073import android.telephony.TelephonyManager;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070074import android.text.TextUtils;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070075import android.text.format.DateUtils;
76import android.text.format.Formatter;
Jeff Sharkey8a503642011-06-10 13:31:21 -070077import android.text.format.Time;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070078import android.util.Log;
79import android.view.LayoutInflater;
Jeff Sharkey8a503642011-06-10 13:31:21 -070080import android.view.Menu;
81import android.view.MenuInflater;
82import android.view.MenuItem;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070083import android.view.View;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070084import android.view.View.OnClickListener;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070085import android.view.ViewGroup;
Jeff Sharkey2af35fb2011-06-24 17:30:27 -070086import android.view.ViewTreeObserver.OnGlobalLayoutListener;
Jeff Sharkey8a503642011-06-10 13:31:21 -070087import android.widget.AdapterView;
88import android.widget.AdapterView.OnItemClickListener;
89import android.widget.AdapterView.OnItemSelectedListener;
90import android.widget.ArrayAdapter;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070091import android.widget.BaseAdapter;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070092import android.widget.Button;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070093import android.widget.CheckBox;
94import android.widget.CompoundButton;
95import android.widget.CompoundButton.OnCheckedChangeListener;
Jeff Sharkey8a503642011-06-10 13:31:21 -070096import android.widget.LinearLayout;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070097import android.widget.ListView;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070098import android.widget.NumberPicker;
Jeff Sharkey2412b0f2011-07-17 20:31:40 -070099import android.widget.ProgressBar;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700100import android.widget.Spinner;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700101import android.widget.Switch;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700102import android.widget.TabHost;
103import android.widget.TabHost.OnTabChangeListener;
104import android.widget.TabHost.TabContentFactory;
105import android.widget.TabHost.TabSpec;
106import android.widget.TabWidget;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700107import android.widget.TextView;
108
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700109import com.android.internal.telephony.Phone;
Jeff Sharkeya662e492011-06-18 21:57:06 -0700110import com.android.settings.net.NetworkPolicyEditor;
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700111import com.android.settings.net.SummaryForAllUidLoader;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700112import com.android.settings.widget.DataUsageChartView;
113import com.android.settings.widget.DataUsageChartView.DataUsageChartListener;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700114import com.google.android.collect.Lists;
115
116import java.util.ArrayList;
117import java.util.Collections;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700118import java.util.Locale;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700119
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700120import libcore.util.Objects;
121
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700122/**
123 * Panel show data usage history across various networks, including options to
124 * inspect based on usage cycle and control through {@link NetworkPolicy}.
125 */
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700126public class DataUsageSummary extends Fragment {
127 private static final String TAG = "DataUsage";
Jeff Sharkey8a503642011-06-10 13:31:21 -0700128 private static final boolean LOGD = true;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700129
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700130 // TODO: remove this testing code
131 private static final boolean TEST_RADIOS = false;
132 private static final String TEST_RADIOS_PROP = "test.radios";
133
Jeff Sharkey8a503642011-06-10 13:31:21 -0700134 private static final String TAB_3G = "3g";
135 private static final String TAB_4G = "4g";
136 private static final String TAB_MOBILE = "mobile";
137 private static final String TAB_WIFI = "wifi";
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700138 private static final String TAB_ETHERNET = "ethernet";
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700139
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700140 private static final String TAG_CONFIRM_ROAMING = "confirmRoaming";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700141 private static final String TAG_CONFIRM_LIMIT = "confirmLimit";
142 private static final String TAG_CYCLE_EDITOR = "cycleEditor";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700143 private static final String TAG_CONFIRM_RESTRICT = "confirmRestrict";
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700144 private static final String TAG_CONFIRM_APP_RESTRICT = "confirmAppRestrict";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700145 private static final String TAG_APP_DETAILS = "appDetails";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700146
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700147 private static final int LOADER_SUMMARY = 2;
148
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700149 private static final long KB_IN_BYTES = 1024;
150 private static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
151 private static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
152
153 private INetworkStatsService mStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700154 private INetworkPolicyManager mPolicyService;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700155 private ConnectivityManager mConnService;
156
157 private static final String PREF_FILE = "data_usage";
158 private static final String PREF_SHOW_WIFI = "show_wifi";
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700159 private static final String PREF_SHOW_ETHERNET = "show_ethernet";
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700160
161 private SharedPreferences mPrefs;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700162
Jeff Sharkey8a503642011-06-10 13:31:21 -0700163 private TabHost mTabHost;
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700164 private ViewGroup mTabsContainer;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700165 private TabWidget mTabWidget;
166 private ListView mListView;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700167 private DataUsageAdapter mAdapter;
168
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700169 private ViewGroup mHeader;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700170
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700171 private ViewGroup mNetworkSwitchesContainer;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700172 private LinearLayout mNetworkSwitches;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700173 private Switch mDataEnabled;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700174 private View mDataEnabledView;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700175 private CheckBox mDisableAtLimit;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700176 private View mDisableAtLimitView;
177
Jeff Sharkey8a503642011-06-10 13:31:21 -0700178 private Spinner mCycleSpinner;
179 private CycleAdapter mCycleAdapter;
180
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700181 private DataUsageChartView mChart;
182
183 private View mAppDetail;
184 private TextView mAppTitle;
185 private TextView mAppSubtitle;
186 private Button mAppSettings;
187
188 private LinearLayout mAppSwitches;
189 private CheckBox mAppRestrict;
190 private View mAppRestrictView;
191
Jeff Sharkey8a503642011-06-10 13:31:21 -0700192 private boolean mShowWifi = false;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700193 private boolean mShowEthernet = false;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700194
Jeff Sharkeya662e492011-06-18 21:57:06 -0700195 private NetworkTemplate mTemplate = null;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700196
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700197 private static final int UID_NONE = -1;
198 private int mUid = UID_NONE;
199
200 private Intent mAppSettingsIntent;
201
Jeff Sharkeya662e492011-06-18 21:57:06 -0700202 private NetworkPolicyEditor mPolicyEditor;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700203
Jeff Sharkey8a503642011-06-10 13:31:21 -0700204 private NetworkStatsHistory mHistory;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700205 private NetworkStatsHistory mDetailHistory;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700206
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700207 private String mCurrentTab = null;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700208 private String mIntentTab = null;
209
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700210 private MenuItem mMenuDataRoaming;
211 private MenuItem mMenuRestrictBackground;
212
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700213 /** Flag used to ignore listeners during binding. */
214 private boolean mBinding;
215
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700216 @Override
Jeff Sharkey8a503642011-06-10 13:31:21 -0700217 public void onCreate(Bundle savedInstanceState) {
218 super.onCreate(savedInstanceState);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700219
220 mStatsService = INetworkStatsService.Stub.asInterface(
221 ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700222 mPolicyService = INetworkPolicyManager.Stub.asInterface(
223 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700224 mConnService = (ConnectivityManager) getActivity().getSystemService(
225 Context.CONNECTIVITY_SERVICE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700226
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700227 mPrefs = getActivity().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700228
Jeff Sharkeya662e492011-06-18 21:57:06 -0700229 mPolicyEditor = new NetworkPolicyEditor(mPolicyService);
230 mPolicyEditor.read();
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700231
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700232 mShowWifi = mPrefs.getBoolean(PREF_SHOW_WIFI, false);
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700233 mShowEthernet = mPrefs.getBoolean(PREF_SHOW_ETHERNET, false);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700234
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700235 setHasOptionsMenu(true);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700236 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700237
Jeff Sharkey8a503642011-06-10 13:31:21 -0700238 @Override
239 public View onCreateView(LayoutInflater inflater, ViewGroup container,
240 Bundle savedInstanceState) {
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700241
Jeff Sharkey8a503642011-06-10 13:31:21 -0700242 final Context context = inflater.getContext();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700243 final View view = inflater.inflate(R.layout.data_usage_summary, container, false);
244
Jeff Sharkey8a503642011-06-10 13:31:21 -0700245 mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700246 mTabsContainer = (ViewGroup) view.findViewById(R.id.tabs_container);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700247 mTabWidget = (TabWidget) view.findViewById(android.R.id.tabs);
248 mListView = (ListView) view.findViewById(android.R.id.list);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700249
Jeff Sharkey8a503642011-06-10 13:31:21 -0700250 mTabHost.setup();
251 mTabHost.setOnTabChangedListener(mTabListener);
252
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700253 mHeader = (ViewGroup) inflater.inflate(R.layout.data_usage_header, mListView, false);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700254 mListView.addHeaderView(mHeader, null, false);
255
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700256 {
257 // bind network switches
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700258 mNetworkSwitchesContainer = (ViewGroup) mHeader.findViewById(
259 R.id.network_switches_container);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700260 mNetworkSwitches = (LinearLayout) mHeader.findViewById(R.id.network_switches);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700261
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700262 mDataEnabled = new Switch(inflater.getContext());
263 mDataEnabledView = inflatePreference(inflater, mNetworkSwitches, mDataEnabled);
264 mDataEnabled.setOnCheckedChangeListener(mDataEnabledListener);
265 mNetworkSwitches.addView(mDataEnabledView);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700266
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700267 mDisableAtLimit = new CheckBox(inflater.getContext());
268 mDisableAtLimit.setClickable(false);
269 mDisableAtLimitView = inflatePreference(inflater, mNetworkSwitches, mDisableAtLimit);
270 mDisableAtLimitView.setOnClickListener(mDisableAtLimitListener);
271 mNetworkSwitches.addView(mDisableAtLimitView);
272 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700273
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700274 // bind cycle dropdown
Jeff Sharkey8a503642011-06-10 13:31:21 -0700275 mCycleSpinner = (Spinner) mHeader.findViewById(R.id.cycles);
276 mCycleAdapter = new CycleAdapter(context);
277 mCycleSpinner.setAdapter(mCycleAdapter);
278 mCycleSpinner.setOnItemSelectedListener(mCycleListener);
279
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700280 mChart = (DataUsageChartView) mHeader.findViewById(R.id.chart);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700281 mChart.setListener(mChartListener);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700282
283 {
284 // bind app detail controls
285 mAppDetail = view.findViewById(R.id.app_detail);
286 mAppTitle = (TextView) view.findViewById(R.id.app_title);
287 mAppSubtitle = (TextView) view.findViewById(R.id.app_subtitle);
288 mAppSwitches = (LinearLayout) view.findViewById(R.id.app_switches);
289
290 mAppSettings = (Button) view.findViewById(R.id.app_settings);
291 mAppSettings.setOnClickListener(mAppSettingsListener);
292
293 mAppRestrict = new CheckBox(inflater.getContext());
294 mAppRestrict.setClickable(false);
295 mAppRestrictView = inflatePreference(inflater, mAppSwitches, mAppRestrict);
296 setPreferenceTitle(mAppRestrictView, R.string.data_usage_app_restrict_background);
297 setPreferenceSummary(
298 mAppRestrictView, R.string.data_usage_app_restrict_background_summary);
299 mAppRestrictView.setOnClickListener(mAppRestrictListener);
300 mAppSwitches.addView(mAppRestrictView);
301 }
302
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700303 // only assign layout transitions once first layout is finished
304 mHeader.getViewTreeObserver().addOnGlobalLayoutListener(mFirstLayoutListener);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700305
306 mAdapter = new DataUsageAdapter();
307 mListView.setOnItemClickListener(mListListener);
308 mListView.setAdapter(mAdapter);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700309
310 return view;
311 }
312
313 @Override
314 public void onResume() {
315 super.onResume();
316
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700317 // pick default tab based on incoming intent
318 final Intent intent = getActivity().getIntent();
319 mIntentTab = computeTabFromIntent(intent);
320
Jeff Sharkey8a503642011-06-10 13:31:21 -0700321 // this kicks off chain reaction which creates tabs, binds the body to
322 // selected network, and binds chart, cycles and detail list.
323 updateTabs();
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700324
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700325 // kick off background task to update stats
326 new AsyncTask<Void, Void, Void>() {
327 @Override
328 protected Void doInBackground(Void... params) {
329 try {
330 mStatsService.forceUpdate();
331 } catch (RemoteException e) {
332 }
333 return null;
334 }
335
336 @Override
337 protected void onPostExecute(Void result) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700338 if (isAdded()) {
339 updateBody();
340 }
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700341 }
342 }.execute();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700343 }
344
Jeff Sharkey8a503642011-06-10 13:31:21 -0700345 @Override
346 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
347 inflater.inflate(R.menu.data_usage, menu);
348 }
349
350 @Override
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700351 public void onPrepareOptionsMenu(Menu menu) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700352 final Context context = getActivity();
353
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700354 mMenuDataRoaming = menu.findItem(R.id.data_usage_menu_roaming);
355 mMenuDataRoaming.setVisible(hasMobileRadio(context));
356 mMenuDataRoaming.setChecked(getDataRoaming());
357
358 mMenuRestrictBackground = menu.findItem(R.id.data_usage_menu_restrict_background);
359 mMenuRestrictBackground.setChecked(getRestrictBackground());
360
361 final MenuItem split4g = menu.findItem(R.id.data_usage_menu_split_4g);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700362 split4g.setVisible(hasMobile4gRadio(context));
Jeff Sharkeya662e492011-06-18 21:57:06 -0700363 split4g.setChecked(isMobilePolicySplit());
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700364
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700365 final MenuItem showWifi = menu.findItem(R.id.data_usage_menu_show_wifi);
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700366 if (hasWifiRadio(context) && hasMobileRadio(context)) {
367 showWifi.setVisible(true);
368 showWifi.setChecked(mShowWifi);
369 } else {
370 showWifi.setVisible(false);
371 mShowWifi = true;
372 }
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700373
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700374 final MenuItem showEthernet = menu.findItem(R.id.data_usage_menu_show_ethernet);
375 if (hasEthernet(context) && hasMobileRadio(context)) {
376 showEthernet.setVisible(true);
377 showEthernet.setChecked(mShowEthernet);
378 } else {
379 showEthernet.setVisible(false);
380 mShowEthernet = true;
381 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700382 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700383
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700384 @Override
385 public boolean onOptionsItemSelected(MenuItem item) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700386 switch (item.getItemId()) {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700387 case R.id.data_usage_menu_roaming: {
388 final boolean dataRoaming = !item.isChecked();
389 if (dataRoaming) {
390 ConfirmDataRoamingFragment.show(this);
391 } else {
392 // no confirmation to disable roaming
393 setDataRoaming(false);
394 }
395 return true;
396 }
397 case R.id.data_usage_menu_restrict_background: {
398 final boolean restrictBackground = !item.isChecked();
399 if (restrictBackground) {
400 ConfirmRestrictFragment.show(this);
401 } else {
402 // no confirmation to drop restriction
403 setRestrictBackground(false);
404 }
405 return true;
406 }
407 case R.id.data_usage_menu_split_4g: {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700408 final boolean mobileSplit = !item.isChecked();
Jeff Sharkeya662e492011-06-18 21:57:06 -0700409 setMobilePolicySplit(mobileSplit);
410 item.setChecked(isMobilePolicySplit());
Jeff Sharkey8a503642011-06-10 13:31:21 -0700411 updateTabs();
412 return true;
413 }
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700414 case R.id.data_usage_menu_show_wifi: {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700415 mShowWifi = !item.isChecked();
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700416 mPrefs.edit().putBoolean(PREF_SHOW_WIFI, mShowWifi).apply();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700417 item.setChecked(mShowWifi);
418 updateTabs();
419 return true;
420 }
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700421 case R.id.data_usage_menu_show_ethernet: {
422 mShowEthernet = !item.isChecked();
423 mPrefs.edit().putBoolean(PREF_SHOW_ETHERNET, mShowEthernet).apply();
424 item.setChecked(mShowEthernet);
425 updateTabs();
426 return true;
427 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700428 }
429 return false;
430 }
431
Jeff Sharkey94a90952011-06-13 22:31:09 -0700432 @Override
433 public void onDestroyView() {
434 super.onDestroyView();
435
436 mDataEnabledView = null;
437 mDisableAtLimitView = null;
438 }
439
Jeff Sharkey8a503642011-06-10 13:31:21 -0700440 /**
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700441 * Listener to setup {@link LayoutTransition} after first layout pass.
442 */
443 private OnGlobalLayoutListener mFirstLayoutListener = new OnGlobalLayoutListener() {
444 /** {@inheritDoc} */
445 public void onGlobalLayout() {
446 mHeader.getViewTreeObserver().removeGlobalOnLayoutListener(mFirstLayoutListener);
447
448 mTabsContainer.setLayoutTransition(new LayoutTransition());
449 mHeader.setLayoutTransition(new LayoutTransition());
450 mNetworkSwitchesContainer.setLayoutTransition(new LayoutTransition());
451
452 final LayoutTransition chartTransition = new LayoutTransition();
453 chartTransition.setStartDelay(LayoutTransition.APPEARING, 0);
454 chartTransition.setStartDelay(LayoutTransition.DISAPPEARING, 0);
455 mChart.setLayoutTransition(chartTransition);
456 }
457 };
458
459 /**
Jeff Sharkeya662e492011-06-18 21:57:06 -0700460 * Rebuild all tabs based on {@link NetworkPolicyEditor} and
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700461 * {@link #mShowWifi}, hiding the tabs entirely when applicable. Selects
462 * first tab, and kicks off a full rebind of body contents.
Jeff Sharkey8a503642011-06-10 13:31:21 -0700463 */
464 private void updateTabs() {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700465 final Context context = getActivity();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700466 mTabHost.clearAllTabs();
467
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700468 final boolean mobileSplit = isMobilePolicySplit();
469 if (mobileSplit && hasMobile4gRadio(context)) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700470 mTabHost.addTab(buildTabSpec(TAB_3G, R.string.data_usage_tab_3g));
471 mTabHost.addTab(buildTabSpec(TAB_4G, R.string.data_usage_tab_4g));
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700472 } else if (hasMobileRadio(context)) {
473 mTabHost.addTab(buildTabSpec(TAB_MOBILE, R.string.data_usage_tab_mobile));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700474 }
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700475 if (mShowWifi && hasWifiRadio(context)) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700476 mTabHost.addTab(buildTabSpec(TAB_WIFI, R.string.data_usage_tab_wifi));
477 }
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700478 if (mShowEthernet && hasEthernet(context)) {
479 mTabHost.addTab(buildTabSpec(TAB_ETHERNET, R.string.data_usage_tab_ethernet));
480 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700481
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700482 final boolean multipleTabs = mTabWidget.getTabCount() > 1;
483 mTabWidget.setVisibility(multipleTabs ? View.VISIBLE : View.GONE);
484 if (mIntentTab != null) {
485 if (Objects.equal(mIntentTab, mTabHost.getCurrentTabTag())) {
486 updateBody();
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700487 } else {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700488 mTabHost.setCurrentTabByTag(mIntentTab);
489 }
490 mIntentTab = null;
491 } else {
492 if (mTabHost.getCurrentTab() == 0) {
493 updateBody();
494 } else {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700495 mTabHost.setCurrentTab(0);
496 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700497 }
498 }
499
Jeff Sharkey8a503642011-06-10 13:31:21 -0700500 /**
501 * Factory that provide empty {@link View} to make {@link TabHost} happy.
502 */
503 private TabContentFactory mEmptyTabContent = new TabContentFactory() {
504 /** {@inheritDoc} */
505 public View createTabContent(String tag) {
506 return new View(mTabHost.getContext());
507 }
508 };
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700509
Jeff Sharkey8a503642011-06-10 13:31:21 -0700510 /**
511 * Build {@link TabSpec} with thin indicator, and empty content.
512 */
513 private TabSpec buildTabSpec(String tag, int titleRes) {
514 final LayoutInflater inflater = LayoutInflater.from(mTabWidget.getContext());
515 final View indicator = inflater.inflate(
516 R.layout.tab_indicator_thin_holo, mTabWidget, false);
517 final TextView title = (TextView) indicator.findViewById(android.R.id.title);
518 title.setText(titleRes);
519 return mTabHost.newTabSpec(tag).setIndicator(indicator).setContent(mEmptyTabContent);
520 }
521
522 private OnTabChangeListener mTabListener = new OnTabChangeListener() {
523 /** {@inheritDoc} */
524 public void onTabChanged(String tabId) {
525 // user changed tab; update body
526 updateBody();
527 }
528 };
529
530 /**
531 * Update body content based on current tab. Loads
532 * {@link NetworkStatsHistory} and {@link NetworkPolicy} from system, and
533 * binds them to visible controls.
534 */
535 private void updateBody() {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700536 mBinding = true;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700537
Jeff Sharkeya662e492011-06-18 21:57:06 -0700538 final Context context = getActivity();
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700539 final String currentTab = mTabHost.getCurrentTabTag();
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700540
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700541 if (currentTab == null) {
542 Log.w(TAG, "no tab selected; hiding body");
543 mListView.setVisibility(View.GONE);
544 return;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700545 } else {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700546 mListView.setVisibility(View.VISIBLE);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700547 }
Jeff Sharkeya662e492011-06-18 21:57:06 -0700548
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700549 final boolean tabChanged = !currentTab.equals(mCurrentTab);
550 mCurrentTab = currentTab;
551
Jeff Sharkey8a503642011-06-10 13:31:21 -0700552 if (LOGD) Log.d(TAG, "updateBody() with currentTab=" + currentTab);
553
554 if (TAB_WIFI.equals(currentTab)) {
555 // wifi doesn't have any controls
556 mDataEnabledView.setVisibility(View.GONE);
557 mDisableAtLimitView.setVisibility(View.GONE);
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700558 mTemplate = buildTemplateWifi();
559
560 } else if (TAB_ETHERNET.equals(currentTab)) {
561 // ethernet doesn't have any controls
562 mDataEnabledView.setVisibility(View.GONE);
563 mDisableAtLimitView.setVisibility(View.GONE);
564 mTemplate = buildTemplateEthernet();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700565
566 } else {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700567 mDataEnabledView.setVisibility(View.VISIBLE);
568 mDisableAtLimitView.setVisibility(View.VISIBLE);
569 }
570
571 if (TAB_MOBILE.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700572 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_mobile);
573 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_mobile_limit);
574 mDataEnabled.setChecked(mConnService.getMobileDataEnabled());
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700575 mTemplate = buildTemplateMobileAll(getActiveSubscriberId(context));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700576
577 } else if (TAB_3G.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700578 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_3g);
579 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_3g_limit);
580 // TODO: bind mDataEnabled to 3G radio state
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700581 mTemplate = buildTemplateMobile3gLower(getActiveSubscriberId(context));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700582
583 } else if (TAB_4G.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700584 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_4g);
585 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_4g_limit);
586 // TODO: bind mDataEnabled to 4G radio state
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700587 mTemplate = buildTemplateMobile4g(getActiveSubscriberId(context));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700588 }
589
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700590 try {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700591 // load stats for current template
Jeff Sharkey8a503642011-06-10 13:31:21 -0700592 mHistory = mStatsService.getHistoryForNetwork(mTemplate);
593 } catch (RemoteException e) {
594 // since we can't do much without policy or history, and we don't
595 // want to leave with half-baked UI, we bail hard.
596 throw new RuntimeException("problem reading network policy or stats", e);
597 }
598
Jeff Sharkey8a503642011-06-10 13:31:21 -0700599 // bind chart to historical stats
Jeff Sharkey8a503642011-06-10 13:31:21 -0700600 mChart.bindNetworkStats(mHistory);
601
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700602 // only update policy when switching tabs
603 updatePolicy(tabChanged);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700604 updateAppDetail();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700605
606 // force scroll to top of body
607 mListView.smoothScrollToPosition(0);
608
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700609 mBinding = false;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700610 }
611
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700612 private boolean isAppDetailMode() {
613 return mUid != UID_NONE;
614 }
615
616 /**
617 * Update UID details panels to match {@link #mUid}, showing or hiding them
618 * depending on {@link #isAppDetailMode()}.
619 */
620 private void updateAppDetail() {
621 if (isAppDetailMode()) {
622 mAppDetail.setVisibility(View.VISIBLE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700623 mCycleAdapter.setChangeVisible(false);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700624 } else {
625 mAppDetail.setVisibility(View.GONE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700626 mCycleAdapter.setChangeVisible(true);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700627
628 // hide detail stats when not in detail mode
629 mChart.bindDetailNetworkStats(null);
630 return;
631 }
632
633 // remove warning/limit sweeps while in detail mode
634 mChart.bindNetworkPolicy(null);
635
636 final PackageManager pm = getActivity().getPackageManager();
637 mAppTitle.setText(pm.getNameForUid(mUid));
638
639 // enable settings button when package provides it
640 // TODO: target torwards entire UID instead of just first package
641 final String[] packageNames = pm.getPackagesForUid(mUid);
642 if (packageNames != null && packageNames.length > 0) {
643 mAppSettingsIntent = new Intent(Intent.ACTION_MANAGE_NETWORK_USAGE);
644 mAppSettingsIntent.setPackage(packageNames[0]);
645 mAppSettingsIntent.addCategory(Intent.CATEGORY_DEFAULT);
646
647 final boolean matchFound = pm.resolveActivity(mAppSettingsIntent, 0) != null;
648 mAppSettings.setEnabled(matchFound);
649
650 } else {
651 mAppSettingsIntent = null;
652 mAppSettings.setEnabled(false);
653 }
654
655 try {
656 // load stats for current uid and template
657 // TODO: read template from extras
658 mDetailHistory = mStatsService.getHistoryForUid(mTemplate, mUid, NetworkStats.TAG_NONE);
659 } catch (RemoteException e) {
660 // since we can't do much without history, and we don't want to
661 // leave with half-baked UI, we bail hard.
662 throw new RuntimeException("problem reading network stats", e);
663 }
664
665 // bind chart to historical stats
666 mChart.bindDetailNetworkStats(mDetailHistory);
667
668 updateDetailData();
669
670 final Context context = getActivity();
671 if (NetworkPolicyManager.isUidValidForPolicy(context, mUid)) {
672 mAppRestrictView.setVisibility(View.VISIBLE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700673 mAppRestrict.setChecked(getAppRestrictBackground());
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700674
675 } else {
676 mAppRestrictView.setVisibility(View.GONE);
677 }
678
679 }
680
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700681 private void setPolicyCycleDay(int cycleDay) {
682 if (LOGD) Log.d(TAG, "setPolicyCycleDay()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700683 mPolicyEditor.setPolicyCycleDay(mTemplate, cycleDay);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700684 updatePolicy(true);
685 }
686
687 private void setPolicyWarningBytes(long warningBytes) {
688 if (LOGD) Log.d(TAG, "setPolicyWarningBytes()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700689 mPolicyEditor.setPolicyWarningBytes(mTemplate, warningBytes);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700690 updatePolicy(false);
691 }
692
693 private void setPolicyLimitBytes(long limitBytes) {
694 if (LOGD) Log.d(TAG, "setPolicyLimitBytes()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700695 mPolicyEditor.setPolicyLimitBytes(mTemplate, limitBytes);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700696 updatePolicy(false);
697 }
698
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700699 private boolean getDataRoaming() {
700 final ContentResolver resolver = getActivity().getContentResolver();
701 return Settings.Secure.getInt(resolver, Settings.Secure.DATA_ROAMING, 0) != 0;
702 }
703
704 private void setDataRoaming(boolean enabled) {
705 // TODO: teach telephony DataConnectionTracker to watch and apply
706 // updates when changed.
707 final ContentResolver resolver = getActivity().getContentResolver();
708 Settings.Secure.putInt(resolver, Settings.Secure.DATA_ROAMING, enabled ? 1 : 0);
709 mMenuDataRoaming.setChecked(enabled);
710 }
711
712 private boolean getRestrictBackground() {
713 return !mConnService.getBackgroundDataSetting();
714 }
715
716 private void setRestrictBackground(boolean restrictBackground) {
717 if (LOGD) Log.d(TAG, "setRestrictBackground()");
718 mConnService.setBackgroundDataSetting(!restrictBackground);
719 mMenuRestrictBackground.setChecked(restrictBackground);
720 }
721
722 private boolean getAppRestrictBackground() {
723 final int uidPolicy;
724 try {
725 uidPolicy = mPolicyService.getUidPolicy(mUid);
726 } catch (RemoteException e) {
727 // since we can't do much without policy, we bail hard.
728 throw new RuntimeException("problem reading network policy", e);
729 }
730
731 return (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
732 }
733
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700734 private void setAppRestrictBackground(boolean restrictBackground) {
735 if (LOGD) Log.d(TAG, "setRestrictBackground()");
736 try {
737 mPolicyService.setUidPolicy(
738 mUid, restrictBackground ? POLICY_REJECT_METERED_BACKGROUND : POLICY_NONE);
739 } catch (RemoteException e) {
740 throw new RuntimeException("unable to save policy", e);
741 }
742
743 mAppRestrict.setChecked(restrictBackground);
744 }
745
Jeff Sharkey8a503642011-06-10 13:31:21 -0700746 /**
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700747 * Update chart sweeps and cycle list to reflect {@link NetworkPolicy} for
748 * current {@link #mTemplate}.
749 */
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700750 private void updatePolicy(boolean refreshCycle) {
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700751 if (isAppDetailMode()) {
752 mNetworkSwitches.setVisibility(View.GONE);
753 // we fall through to update cycle list for detail mode
754 } else {
755 mNetworkSwitches.setVisibility(View.VISIBLE);
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700756
757 // when heading back to summary without cycle refresh, kick details
758 // update to repopulate list.
759 if (!refreshCycle) {
760 updateDetailData();
761 }
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700762 }
763
Jeff Sharkeya662e492011-06-18 21:57:06 -0700764 final NetworkPolicy policy = mPolicyEditor.getPolicy(mTemplate);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700765
766 // reflect policy limit in checkbox
767 mDisableAtLimit.setChecked(policy != null && policy.limitBytes != LIMIT_DISABLED);
768 mChart.bindNetworkPolicy(policy);
769
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700770 if (refreshCycle) {
771 // generate cycle list based on policy and available history
772 updateCycleList(policy);
773 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700774 }
775
776 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -0700777 * Rebuild {@link #mCycleAdapter} based on {@link NetworkPolicy#cycleDay}
778 * and available {@link NetworkStatsHistory} data. Always selects the newest
779 * item, updating the inspection range on {@link #mChart}.
780 */
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700781 private void updateCycleList(NetworkPolicy policy) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700782 mCycleAdapter.clear();
783
784 final Context context = mCycleSpinner.getContext();
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700785 long historyStart = mHistory.getStart();
786 long historyEnd = mHistory.getEnd();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700787
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700788 if (historyStart == Long.MAX_VALUE || historyEnd == Long.MIN_VALUE) {
789 historyStart = System.currentTimeMillis();
790 historyEnd = System.currentTimeMillis();
791 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700792
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700793 boolean hasCycles = false;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700794 if (policy != null) {
795 // find the next cycle boundary
796 long cycleEnd = computeNextCycleBoundary(historyEnd, policy);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700797
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700798 int guardCount = 0;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700799
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700800 // walk backwards, generating all valid cycle ranges
801 while (cycleEnd > historyStart) {
802 final long cycleStart = computeLastCycleBoundary(cycleEnd, policy);
803 Log.d(TAG, "generating cs=" + cycleStart + " to ce=" + cycleEnd + " waiting for hs="
804 + historyStart);
805 mCycleAdapter.add(new CycleItem(context, cycleStart, cycleEnd));
806 cycleEnd = cycleStart;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700807 hasCycles = true;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700808
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700809 // TODO: remove this guard once we have better testing
810 if (guardCount++ > 50) {
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700811 Log.wtf(TAG, "stuck generating ranges for historyStart=" + historyStart
812 + ", historyEnd=" + historyEnd + " and policy=" + policy);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700813 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700814 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700815
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700816 // one last cycle entry to modify policy cycle day
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700817 mCycleAdapter.setChangePossible(true);
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700818 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700819
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700820 if (!hasCycles) {
821 // no valid cycles; show all data
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700822 // TODO: offer simple ranges like "last week" etc
823 mCycleAdapter.add(new CycleItem(context, historyStart, historyEnd));
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700824 mCycleAdapter.setChangePossible(false);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700825 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700826
827 // force pick the current cycle (first item)
828 mCycleSpinner.setSelection(0);
829 mCycleListener.onItemSelected(mCycleSpinner, null, 0, 0);
830 }
831
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700832 private OnCheckedChangeListener mDataEnabledListener = new OnCheckedChangeListener() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700833 /** {@inheritDoc} */
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700834 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
835 if (mBinding) return;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700836
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700837 final boolean dataEnabled = isChecked;
838 mDataEnabled.setChecked(dataEnabled);
839
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700840 final String currentTab = mCurrentTab;
841 if (TAB_MOBILE.equals(currentTab)) {
842 mConnService.setMobileDataEnabled(dataEnabled);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700843 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700844 }
845 };
846
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700847 private View.OnClickListener mDisableAtLimitListener = new View.OnClickListener() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700848 /** {@inheritDoc} */
849 public void onClick(View v) {
850 final boolean disableAtLimit = !mDisableAtLimit.isChecked();
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700851 if (disableAtLimit) {
852 // enabling limit; show confirmation dialog which eventually
853 // calls setPolicyLimitBytes() once user confirms.
854 ConfirmLimitFragment.show(DataUsageSummary.this);
855 } else {
856 setPolicyLimitBytes(LIMIT_DISABLED);
857 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700858 }
859 };
860
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700861 private View.OnClickListener mAppRestrictListener = new View.OnClickListener() {
862 /** {@inheritDoc} */
863 public void onClick(View v) {
864 final boolean restrictBackground = !mAppRestrict.isChecked();
865
866 if (restrictBackground) {
867 // enabling restriction; show confirmation dialog which
868 // eventually calls setRestrictBackground() once user confirms.
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700869 ConfirmAppRestrictFragment.show(DataUsageSummary.this);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700870 } else {
871 setAppRestrictBackground(false);
872 }
873 }
874 };
875
876 private OnClickListener mAppSettingsListener = new OnClickListener() {
877 /** {@inheritDoc} */
878 public void onClick(View v) {
879 // TODO: target torwards entire UID instead of just first package
880 startActivity(mAppSettingsIntent);
881 }
882 };
883
Jeff Sharkey8a503642011-06-10 13:31:21 -0700884 private OnItemClickListener mListListener = new OnItemClickListener() {
885 /** {@inheritDoc} */
886 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700887 final AppUsageItem app = (AppUsageItem) parent.getItemAtPosition(position);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700888 AppDetailsFragment.show(DataUsageSummary.this, app.uid);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700889 }
890 };
891
892 private OnItemSelectedListener mCycleListener = new OnItemSelectedListener() {
893 /** {@inheritDoc} */
894 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
895 final CycleItem cycle = (CycleItem) parent.getItemAtPosition(position);
896 if (cycle instanceof CycleChangeItem) {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700897 // show cycle editor; will eventually call setPolicyCycleDay()
898 // when user finishes editing.
899 CycleEditorFragment.show(DataUsageSummary.this);
900
901 // reset spinner to something other than "change cycle..."
902 mCycleSpinner.setSelection(0);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700903
904 } else {
Jeff Sharkey8e911d72011-06-14 22:41:21 -0700905 if (LOGD) {
906 Log.d(TAG, "showing cycle " + cycle + ", start=" + cycle.start + ", end="
907 + cycle.end + "]");
908 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700909
910 // update chart to show selected cycle, and update detail data
911 // to match updated sweep bounds.
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700912 mChart.setVisibleRange(cycle.start, cycle.end, mHistory.getEnd());
Jeff Sharkey8a503642011-06-10 13:31:21 -0700913
914 updateDetailData();
915 }
916 }
917
918 /** {@inheritDoc} */
919 public void onNothingSelected(AdapterView<?> parent) {
920 // ignored
921 }
922 };
923
924 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700925 * Update details based on {@link #mChart} inspection range depending on
926 * current mode. In network mode, updates {@link #mAdapter} with sorted list
927 * of applications data usage, and when {@link #isAppDetailMode()} update
928 * app details.
Jeff Sharkey8a503642011-06-10 13:31:21 -0700929 */
930 private void updateDetailData() {
931 if (LOGD) Log.d(TAG, "updateDetailData()");
932
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700933 final long start = mChart.getInspectStart();
934 final long end = mChart.getInspectEnd();
935
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700936 if (isAppDetailMode()) {
937 if (mDetailHistory != null) {
938 final Context context = mChart.getContext();
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700939 final long now = System.currentTimeMillis();
940 final NetworkStatsHistory.Entry entry = mDetailHistory.getValues(
941 start, end, now, null);
Jeff Sharkey2412b0f2011-07-17 20:31:40 -0700942
943 mAppSubtitle.setText(
944 getString(R.string.data_usage_received_sent,
945 Formatter.formatFileSize(context, entry.rxBytes),
946 Formatter.formatFileSize(context, entry.txBytes)));
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700947 }
948
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700949 getLoaderManager().destroyLoader(LOADER_SUMMARY);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700950
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700951 } else {
952 // kick off loader for detailed stats
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700953 getLoaderManager().restartLoader(LOADER_SUMMARY,
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700954 SummaryForAllUidLoader.buildArgs(mTemplate, start, end), mSummaryForAllUid);
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700955
956 }
957 }
958
959 private final LoaderCallbacks<NetworkStats> mSummaryForAllUid = new LoaderCallbacks<
960 NetworkStats>() {
961 /** {@inheritDoc} */
962 public Loader<NetworkStats> onCreateLoader(int id, Bundle args) {
963 return new SummaryForAllUidLoader(getActivity(), mStatsService, args);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700964 }
965
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700966 /** {@inheritDoc} */
967 public void onLoadFinished(Loader<NetworkStats> loader, NetworkStats data) {
968 mAdapter.bindStats(data);
969 }
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -0700970
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700971 /** {@inheritDoc} */
972 public void onLoaderReset(Loader<NetworkStats> loader) {
973 mAdapter.bindStats(null);
974 }
975 };
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700976
Jeff Sharkeya662e492011-06-18 21:57:06 -0700977 private boolean isMobilePolicySplit() {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700978 final Context context = getActivity();
979 if (hasMobileRadio(context)) {
980 final String subscriberId = getActiveSubscriberId(context);
981 return mPolicyEditor.isMobilePolicySplit(subscriberId);
982 } else {
983 return false;
984 }
Jeff Sharkeya662e492011-06-18 21:57:06 -0700985 }
986
987 private void setMobilePolicySplit(boolean split) {
988 final String subscriberId = getActiveSubscriberId(getActivity());
989 mPolicyEditor.setMobilePolicySplit(subscriberId, split);
990 }
991
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700992 private static String getActiveSubscriberId(Context context) {
993 final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
994 Context.TELEPHONY_SERVICE);
995 return telephony.getSubscriberId();
996 }
997
Jeff Sharkey8a503642011-06-10 13:31:21 -0700998 private DataUsageChartListener mChartListener = new DataUsageChartListener() {
999 /** {@inheritDoc} */
1000 public void onInspectRangeChanged() {
1001 if (LOGD) Log.d(TAG, "onInspectRangeChanged()");
1002 updateDetailData();
1003 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001004
Jeff Sharkey8a503642011-06-10 13:31:21 -07001005 /** {@inheritDoc} */
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001006 public void onWarningChanged() {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001007 setPolicyWarningBytes(mChart.getWarningBytes());
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001008 }
Jeff Sharkey8a503642011-06-10 13:31:21 -07001009
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001010 /** {@inheritDoc} */
1011 public void onLimitChanged() {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001012 setPolicyLimitBytes(mChart.getLimitBytes());
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001013 }
1014 };
1015
1016
1017 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -07001018 * List item that reflects a specific data usage cycle.
1019 */
1020 public static class CycleItem {
1021 public CharSequence label;
1022 public long start;
1023 public long end;
1024
1025 private static final StringBuilder sBuilder = new StringBuilder(50);
1026 private static final java.util.Formatter sFormatter = new java.util.Formatter(
1027 sBuilder, Locale.getDefault());
1028
1029 CycleItem(CharSequence label) {
1030 this.label = label;
1031 }
1032
1033 public CycleItem(Context context, long start, long end) {
1034 this.label = formatDateRangeUtc(context, start, end);
1035 this.start = start;
1036 this.end = end;
1037 }
1038
1039 private static String formatDateRangeUtc(Context context, long start, long end) {
1040 synchronized (sBuilder) {
1041 sBuilder.setLength(0);
1042 return DateUtils.formatDateRange(context, sFormatter, start, end,
1043 DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH,
1044 Time.TIMEZONE_UTC).toString();
1045 }
1046 }
1047
1048 @Override
1049 public String toString() {
1050 return label.toString();
1051 }
1052 }
1053
1054 /**
1055 * Special-case data usage cycle that triggers dialog to change
1056 * {@link NetworkPolicy#cycleDay}.
1057 */
1058 public static class CycleChangeItem extends CycleItem {
1059 public CycleChangeItem(Context context) {
1060 super(context.getString(R.string.data_usage_change_cycle));
1061 }
1062 }
1063
1064 public static class CycleAdapter extends ArrayAdapter<CycleItem> {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001065 private boolean mChangePossible = false;
1066 private boolean mChangeVisible = false;
1067
1068 private final CycleChangeItem mChangeItem;
1069
Jeff Sharkey8a503642011-06-10 13:31:21 -07001070 public CycleAdapter(Context context) {
1071 super(context, android.R.layout.simple_spinner_item);
1072 setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001073 mChangeItem = new CycleChangeItem(context);
1074 }
1075
1076 public void setChangePossible(boolean possible) {
1077 mChangePossible = possible;
1078 updateChange();
1079 }
1080
1081 public void setChangeVisible(boolean visible) {
1082 mChangeVisible = visible;
1083 updateChange();
1084 }
1085
1086 private void updateChange() {
1087 remove(mChangeItem);
1088 if (mChangePossible && mChangeVisible) {
1089 add(mChangeItem);
1090 }
Jeff Sharkey8a503642011-06-10 13:31:21 -07001091 }
1092 }
1093
Jeff Sharkey4dfa6602011-06-13 00:42:03 -07001094 private static class AppUsageItem implements Comparable<AppUsageItem> {
1095 public int uid;
1096 public long total;
1097
1098 /** {@inheritDoc} */
1099 public int compareTo(AppUsageItem another) {
1100 return Long.compare(another.total, total);
1101 }
1102 }
1103
Jeff Sharkey8a503642011-06-10 13:31:21 -07001104 /**
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001105 * Adapter of applications, sorted by total usage descending.
1106 */
1107 public static class DataUsageAdapter extends BaseAdapter {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001108 private ArrayList<AppUsageItem> mItems = Lists.newArrayList();
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001109 private long mLargest;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001110
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001111 /**
1112 * Bind the given {@link NetworkStats}, or {@code null} to clear list.
1113 */
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001114 public void bindStats(NetworkStats stats) {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001115 mItems.clear();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001116
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001117 if (stats != null) {
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001118 final AppUsageItem systemItem = new AppUsageItem();
1119 systemItem.uid = android.os.Process.SYSTEM_UID;
1120
Jeff Sharkeyebae6592011-07-12 13:53:11 -07001121 NetworkStats.Entry entry = null;
1122 for (int i = 0; i < stats.size(); i++) {
1123 entry = stats.getValues(i, entry);
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001124
1125 final boolean isApp = entry.uid >= android.os.Process.FIRST_APPLICATION_UID
1126 && entry.uid <= android.os.Process.LAST_APPLICATION_UID;
1127 if (isApp || entry.uid == TrafficStats.UID_REMOVED) {
1128 final AppUsageItem item = new AppUsageItem();
1129 item.uid = entry.uid;
1130 item.total = entry.rxBytes + entry.txBytes;
1131 mItems.add(item);
1132 } else {
1133 systemItem.total += entry.rxBytes + entry.txBytes;
1134 }
1135 }
1136
1137 if (systemItem.total > 0) {
1138 mItems.add(systemItem);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001139 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001140 }
1141
Jeff Sharkey8a503642011-06-10 13:31:21 -07001142 Collections.sort(mItems);
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001143 mLargest = (mItems.size() > 0) ? mItems.get(0).total : 0;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001144 notifyDataSetChanged();
1145 }
1146
1147 @Override
1148 public int getCount() {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001149 return mItems.size();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001150 }
1151
1152 @Override
1153 public Object getItem(int position) {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001154 return mItems.get(position);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001155 }
1156
1157 @Override
1158 public long getItemId(int position) {
1159 return position;
1160 }
1161
1162 @Override
1163 public View getView(int position, View convertView, ViewGroup parent) {
1164 if (convertView == null) {
1165 convertView = LayoutInflater.from(parent.getContext()).inflate(
Jeff Sharkey52c3f442011-06-23 00:39:38 -07001166 R.layout.data_usage_item, parent, false);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001167 }
1168
1169 final Context context = parent.getContext();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001170
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001171 final TextView title = (TextView) convertView.findViewById(android.R.id.title);
1172 final TextView summary = (TextView) convertView.findViewById(android.R.id.summary);
1173 final ProgressBar progress = (ProgressBar) convertView.findViewById(
1174 android.R.id.progress);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001175
Jeff Sharkey8a503642011-06-10 13:31:21 -07001176 final AppUsageItem item = mItems.get(position);
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001177 title.setText(resolveLabelForUid(context, item.uid));
1178 summary.setText(Formatter.formatFileSize(context, item.total));
1179
1180 final int percentTotal = mLargest != 0 ? (int) (item.total * 100 / mLargest) : 0;
1181 progress.setProgress(percentTotal);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001182
1183 return convertView;
1184 }
1185
1186 }
1187
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001188 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001189 * Empty {@link Fragment} that controls display of UID details in
1190 * {@link DataUsageSummary}.
1191 */
1192 public static class AppDetailsFragment extends Fragment {
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001193 private static final String EXTRA_UID = "uid";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001194
1195 public static void show(DataUsageSummary parent, int uid) {
1196 final Bundle args = new Bundle();
1197 args.putInt(EXTRA_UID, uid);
1198
1199 final AppDetailsFragment fragment = new AppDetailsFragment();
1200 fragment.setArguments(args);
1201 fragment.setTargetFragment(parent, 0);
1202
1203 final FragmentTransaction ft = parent.getFragmentManager().beginTransaction();
1204 ft.add(fragment, TAG_APP_DETAILS);
1205 ft.addToBackStack(TAG_APP_DETAILS);
1206 ft.commit();
1207 }
1208
1209 @Override
1210 public void onStart() {
1211 super.onStart();
1212 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1213 target.mUid = getArguments().getInt(EXTRA_UID);
1214 target.updateBody();
1215 }
1216
1217 @Override
1218 public void onStop() {
1219 super.onStop();
1220 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1221 target.mUid = UID_NONE;
1222 target.updateBody();
1223 }
1224 }
1225
1226 /**
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001227 * Dialog to request user confirmation before setting
1228 * {@link NetworkPolicy#limitBytes}.
1229 */
1230 public static class ConfirmLimitFragment extends DialogFragment {
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001231 private static final String EXTRA_MESSAGE_ID = "messageId";
1232 private static final String EXTRA_LIMIT_BYTES = "limitBytes";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001233
1234 public static void show(DataUsageSummary parent) {
1235 final Bundle args = new Bundle();
1236
1237 // TODO: customize default limits based on network template
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001238 final String currentTab = parent.mCurrentTab;
1239 if (TAB_3G.equals(currentTab)) {
1240 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_3g);
1241 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
1242 } else if (TAB_4G.equals(currentTab)) {
1243 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_4g);
1244 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
1245 } else if (TAB_MOBILE.equals(currentTab)) {
1246 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_mobile);
1247 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001248 }
1249
1250 final ConfirmLimitFragment dialog = new ConfirmLimitFragment();
1251 dialog.setArguments(args);
1252 dialog.setTargetFragment(parent, 0);
1253 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_LIMIT);
1254 }
1255
1256 @Override
1257 public Dialog onCreateDialog(Bundle savedInstanceState) {
1258 final Context context = getActivity();
1259
1260 final int messageId = getArguments().getInt(EXTRA_MESSAGE_ID);
1261 final long limitBytes = getArguments().getLong(EXTRA_LIMIT_BYTES);
1262
1263 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1264 builder.setTitle(R.string.data_usage_limit_dialog_title);
1265 builder.setMessage(messageId);
1266
1267 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1268 public void onClick(DialogInterface dialog, int which) {
1269 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1270 if (target != null) {
1271 target.setPolicyLimitBytes(limitBytes);
1272 }
1273 }
1274 });
1275
1276 return builder.create();
1277 }
1278 }
1279
1280 /**
1281 * Dialog to edit {@link NetworkPolicy#cycleDay}.
1282 */
1283 public static class CycleEditorFragment extends DialogFragment {
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001284 private static final String EXTRA_CYCLE_DAY = "cycleDay";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001285
1286 public static void show(DataUsageSummary parent) {
Jeff Sharkeya662e492011-06-18 21:57:06 -07001287 final NetworkPolicy policy = parent.mPolicyEditor.getPolicy(parent.mTemplate);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001288 final Bundle args = new Bundle();
1289 args.putInt(CycleEditorFragment.EXTRA_CYCLE_DAY, policy.cycleDay);
1290
1291 final CycleEditorFragment dialog = new CycleEditorFragment();
1292 dialog.setArguments(args);
1293 dialog.setTargetFragment(parent, 0);
1294 dialog.show(parent.getFragmentManager(), TAG_CYCLE_EDITOR);
1295 }
1296
1297 @Override
1298 public Dialog onCreateDialog(Bundle savedInstanceState) {
1299 final Context context = getActivity();
1300
1301 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1302 final LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext());
1303
1304 final View view = dialogInflater.inflate(R.layout.data_usage_cycle_editor, null, false);
1305 final NumberPicker cycleDayPicker = (NumberPicker) view.findViewById(R.id.cycle_day);
1306
1307 final int oldCycleDay = getArguments().getInt(EXTRA_CYCLE_DAY, 1);
1308
1309 cycleDayPicker.setMinValue(1);
1310 cycleDayPicker.setMaxValue(31);
1311 cycleDayPicker.setValue(oldCycleDay);
1312 cycleDayPicker.setWrapSelectorWheel(true);
1313
1314 builder.setTitle(R.string.data_usage_cycle_editor_title);
1315 builder.setView(view);
1316
1317 builder.setPositiveButton(R.string.data_usage_cycle_editor_positive,
1318 new DialogInterface.OnClickListener() {
1319 public void onClick(DialogInterface dialog, int which) {
1320 final int cycleDay = cycleDayPicker.getValue();
1321 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1322 if (target != null) {
1323 target.setPolicyCycleDay(cycleDay);
1324 }
1325 }
1326 });
1327
1328 return builder.create();
1329 }
1330 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001331
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001332 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001333 * Dialog to request user confirmation before setting
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001334 * {@link Settings.Secure#DATA_ROAMING}.
1335 */
1336 public static class ConfirmDataRoamingFragment extends DialogFragment {
1337 public static void show(DataUsageSummary parent) {
1338 final Bundle args = new Bundle();
1339
1340 final ConfirmDataRoamingFragment dialog = new ConfirmDataRoamingFragment();
1341 dialog.setTargetFragment(parent, 0);
1342 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_ROAMING);
1343 }
1344
1345 @Override
1346 public Dialog onCreateDialog(Bundle savedInstanceState) {
1347 final Context context = getActivity();
1348
1349 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1350 builder.setTitle(R.string.roaming_reenable_title);
1351 builder.setMessage(R.string.roaming_warning);
1352
1353 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1354 public void onClick(DialogInterface dialog, int which) {
1355 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1356 if (target != null) {
1357 target.setDataRoaming(true);
1358 }
1359 }
1360 });
1361 builder.setNegativeButton(android.R.string.cancel, null);
1362
1363 return builder.create();
1364 }
1365 }
1366
1367 /**
1368 * Dialog to request user confirmation before setting
1369 * {@link ConnectivityManager#setBackgroundDataSetting(boolean)}.
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001370 */
1371 public static class ConfirmRestrictFragment extends DialogFragment {
1372 public static void show(DataUsageSummary parent) {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001373 final Bundle args = new Bundle();
1374
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001375 final ConfirmRestrictFragment dialog = new ConfirmRestrictFragment();
1376 dialog.setTargetFragment(parent, 0);
1377 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_RESTRICT);
1378 }
1379
1380 @Override
1381 public Dialog onCreateDialog(Bundle savedInstanceState) {
1382 final Context context = getActivity();
1383
1384 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001385 builder.setTitle(R.string.data_usage_restrict_background_title);
1386 builder.setMessage(R.string.data_usage_restrict_background);
1387
1388 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1389 public void onClick(DialogInterface dialog, int which) {
1390 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1391 if (target != null) {
1392 target.setRestrictBackground(true);
1393 }
1394 }
1395 });
1396 builder.setNegativeButton(android.R.string.cancel, null);
1397
1398 return builder.create();
1399 }
1400 }
1401
1402 /**
1403 * Dialog to request user confirmation before setting
1404 * {@link #POLICY_REJECT_METERED_BACKGROUND}.
1405 */
1406 public static class ConfirmAppRestrictFragment extends DialogFragment {
1407 public static void show(DataUsageSummary parent) {
1408 final ConfirmAppRestrictFragment dialog = new ConfirmAppRestrictFragment();
1409 dialog.setTargetFragment(parent, 0);
1410 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_APP_RESTRICT);
1411 }
1412
1413 @Override
1414 public Dialog onCreateDialog(Bundle savedInstanceState) {
1415 final Context context = getActivity();
1416
1417 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001418 builder.setTitle(R.string.data_usage_app_restrict_dialog_title);
1419 builder.setMessage(R.string.data_usage_app_restrict_dialog);
1420
1421 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1422 public void onClick(DialogInterface dialog, int which) {
1423 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1424 if (target != null) {
1425 target.setAppRestrictBackground(true);
1426 }
1427 }
1428 });
1429 builder.setNegativeButton(android.R.string.cancel, null);
1430
1431 return builder.create();
1432 }
1433 }
1434
1435 /**
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001436 * Compute default tab that should be selected, based on
1437 * {@link NetworkPolicyManager#EXTRA_NETWORK_TEMPLATE} extra.
1438 */
1439 private static String computeTabFromIntent(Intent intent) {
Jeff Sharkey271ec8a2011-07-20 16:59:16 -07001440 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
1441 if (template == null) return null;
1442
1443 switch (template.getMatchRule()) {
Jeff Sharkeya662e492011-06-18 21:57:06 -07001444 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001445 return TAB_3G;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001446 case MATCH_MOBILE_4G:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001447 return TAB_4G;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001448 case MATCH_MOBILE_ALL:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001449 return TAB_MOBILE;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001450 case MATCH_WIFI:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001451 return TAB_WIFI;
1452 default:
1453 return null;
1454 }
1455 }
1456
1457 /**
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001458 * Resolve best descriptive label for the given UID.
1459 */
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001460 public static CharSequence resolveLabelForUid(Context context, int uid) {
1461 final Resources res = context.getResources();
1462 final PackageManager pm = context.getPackageManager();
1463
1464 // handle special case labels
1465 switch (uid) {
1466 case android.os.Process.SYSTEM_UID:
1467 return res.getText(R.string.process_kernel_label);
1468 case TrafficStats.UID_REMOVED:
1469 return res.getText(R.string.data_usage_uninstalled_apps);
1470 }
1471
1472 // otherwise fall back to using packagemanager labels
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001473 final String[] packageNames = pm.getPackagesForUid(uid);
1474 final int length = packageNames != null ? packageNames.length : 0;
1475
1476 CharSequence label = pm.getNameForUid(uid);
1477 try {
1478 if (length == 1) {
1479 final ApplicationInfo info = pm.getApplicationInfo(packageNames[0], 0);
1480 label = info.loadLabel(pm);
1481 } else if (length > 1) {
1482 for (String packageName : packageNames) {
1483 final PackageInfo info = pm.getPackageInfo(packageName, 0);
1484 if (info.sharedUserLabel != 0) {
1485 label = pm.getText(packageName, info.sharedUserLabel, info.applicationInfo);
1486 if (!TextUtils.isEmpty(label)) {
1487 break;
1488 }
1489 }
1490 }
1491 }
1492 } catch (NameNotFoundException e) {
1493 }
1494
1495 if (TextUtils.isEmpty(label)) {
1496 label = Integer.toString(uid);
1497 }
1498 return label;
1499 }
1500
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001501 /**
1502 * Test if device has a mobile data radio.
1503 */
1504 private static boolean hasMobileRadio(Context context) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001505 if (TEST_RADIOS) {
1506 return SystemProperties.get(TEST_RADIOS_PROP).contains("mobile");
1507 }
1508
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001509 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1510 Context.CONNECTIVITY_SERVICE);
1511
1512 // mobile devices should have MOBILE network tracker regardless of
1513 // connection status.
1514 return conn.getNetworkInfo(TYPE_MOBILE) != null;
1515 }
1516
1517 /**
1518 * Test if device has a mobile 4G data radio.
1519 */
1520 private static boolean hasMobile4gRadio(Context context) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001521 if (TEST_RADIOS) {
1522 return SystemProperties.get(TEST_RADIOS_PROP).contains("4g");
1523 }
1524
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001525 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1526 Context.CONNECTIVITY_SERVICE);
1527 final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
1528 Context.TELEPHONY_SERVICE);
1529
1530 // WiMAX devices should have WiMAX network tracker regardless of
1531 // connection status.
1532 final boolean hasWimax = conn.getNetworkInfo(TYPE_WIMAX) != null;
1533 final boolean hasLte = telephony.getLteOnCdmaMode() == Phone.LTE_ON_CDMA_TRUE;
1534 return hasWimax || hasLte;
1535 }
1536
1537 /**
1538 * Test if device has a Wi-Fi data radio.
1539 */
1540 private static boolean hasWifiRadio(Context context) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001541 if (TEST_RADIOS) {
1542 return SystemProperties.get(TEST_RADIOS_PROP).contains("wifi");
1543 }
1544
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001545 return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI);
1546 }
1547
1548 /**
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001549 * Test if device has an ethernet network connection.
1550 */
1551 private static boolean hasEthernet(Context context) {
1552 if (TEST_RADIOS) {
1553 return SystemProperties.get(TEST_RADIOS_PROP).contains("ethernet");
1554 }
1555
1556 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1557 Context.CONNECTIVITY_SERVICE);
1558 return conn.getNetworkInfo(TYPE_ETHERNET) != null;
1559 }
1560
1561 /**
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001562 * Inflate a {@link Preference} style layout, adding the given {@link View}
1563 * widget into {@link android.R.id#widget_frame}.
1564 */
1565 private static View inflatePreference(LayoutInflater inflater, ViewGroup root, View widget) {
1566 final View view = inflater.inflate(R.layout.preference, root, false);
1567 final LinearLayout widgetFrame = (LinearLayout) view.findViewById(
1568 android.R.id.widget_frame);
1569 widgetFrame.addView(widget, new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
1570 return view;
1571 }
1572
1573 /**
1574 * Set {@link android.R.id#title} for a preference view inflated with
Jeff Sharkey52c3f442011-06-23 00:39:38 -07001575 * {@link #inflatePreference(LayoutInflater, ViewGroup, View)}.
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001576 */
1577 private static void setPreferenceTitle(View parent, int resId) {
1578 final TextView title = (TextView) parent.findViewById(android.R.id.title);
1579 title.setText(resId);
1580 }
1581
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001582 /**
1583 * Set {@link android.R.id#summary} for a preference view inflated with
1584 * {@link #inflatePreference(LayoutInflater, ViewGroup, View)}.
1585 */
1586 private static void setPreferenceSummary(View parent, int resId) {
1587 final TextView summary = (TextView) parent.findViewById(android.R.id.summary);
1588 summary.setVisibility(View.VISIBLE);
1589 summary.setText(resId);
1590 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001591}