blob: 692c75382ef37c185854f91b1c2dd54075503404 [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 Sharkey29d56b32011-06-20 17:06:52 -070019import static android.net.ConnectivityManager.TYPE_MOBILE;
20import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -070021import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -070022import static android.net.NetworkPolicyManager.ACTION_DATA_USAGE_LIMIT;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -070023import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkey8a503642011-06-10 13:31:21 -070024import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
25import static android.net.NetworkPolicyManager.computeNextCycleBoundary;
Jeff Sharkeya662e492011-06-18 21:57:06 -070026import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
27import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
28import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
29import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070030import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070031
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070032import android.app.AlertDialog;
33import android.app.Dialog;
34import android.app.DialogFragment;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070035import android.app.Fragment;
36import android.content.Context;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070037import android.content.DialogInterface;
Jeff Sharkey4dfa6602011-06-13 00:42:03 -070038import android.content.Intent;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070039import android.content.SharedPreferences;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070040import android.content.pm.ApplicationInfo;
41import android.content.pm.PackageInfo;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070042import android.content.pm.PackageManager;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070043import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070044import android.net.ConnectivityManager;
Jeff Sharkey8a503642011-06-10 13:31:21 -070045import android.net.INetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070046import android.net.INetworkStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -070047import android.net.NetworkPolicy;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -070048import android.net.NetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070049import android.net.NetworkStats;
50import android.net.NetworkStatsHistory;
Jeff Sharkeya662e492011-06-18 21:57:06 -070051import android.net.NetworkTemplate;
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -070052import android.os.AsyncTask;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070053import android.os.Bundle;
54import android.os.RemoteException;
55import android.os.ServiceManager;
Jeff Sharkey8a503642011-06-10 13:31:21 -070056import android.preference.Preference;
Jeff Sharkey4dfa6602011-06-13 00:42:03 -070057import android.preference.PreferenceActivity;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -070058import android.telephony.TelephonyManager;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070059import android.text.TextUtils;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070060import android.text.format.DateUtils;
61import android.text.format.Formatter;
Jeff Sharkey8a503642011-06-10 13:31:21 -070062import android.text.format.Time;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070063import android.util.Log;
64import android.view.LayoutInflater;
Jeff Sharkey8a503642011-06-10 13:31:21 -070065import android.view.Menu;
66import android.view.MenuInflater;
67import android.view.MenuItem;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070068import android.view.View;
69import android.view.ViewGroup;
Jeff Sharkey8a503642011-06-10 13:31:21 -070070import android.widget.AdapterView;
71import android.widget.AdapterView.OnItemClickListener;
72import android.widget.AdapterView.OnItemSelectedListener;
73import android.widget.ArrayAdapter;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070074import android.widget.BaseAdapter;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070075import android.widget.CheckBox;
76import android.widget.CompoundButton;
77import android.widget.CompoundButton.OnCheckedChangeListener;
Jeff Sharkey8a503642011-06-10 13:31:21 -070078import android.widget.LinearLayout;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070079import android.widget.ListView;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070080import android.widget.NumberPicker;
Jeff Sharkey8a503642011-06-10 13:31:21 -070081import android.widget.Spinner;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070082import android.widget.Switch;
Jeff Sharkey8a503642011-06-10 13:31:21 -070083import android.widget.TabHost;
84import android.widget.TabHost.OnTabChangeListener;
85import android.widget.TabHost.TabContentFactory;
86import android.widget.TabHost.TabSpec;
87import android.widget.TabWidget;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070088import android.widget.TextView;
89
Jeff Sharkey29d56b32011-06-20 17:06:52 -070090import com.android.internal.telephony.Phone;
Jeff Sharkeya662e492011-06-18 21:57:06 -070091import com.android.settings.net.NetworkPolicyEditor;
Jeff Sharkey8a503642011-06-10 13:31:21 -070092import com.android.settings.widget.DataUsageChartView;
93import com.android.settings.widget.DataUsageChartView.DataUsageChartListener;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070094import com.google.android.collect.Lists;
95
96import java.util.ArrayList;
Jeff Sharkey8a503642011-06-10 13:31:21 -070097import java.util.Arrays;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070098import java.util.Collections;
Jeff Sharkey8a503642011-06-10 13:31:21 -070099import java.util.Locale;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700100
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700101/**
102 * Panel show data usage history across various networks, including options to
103 * inspect based on usage cycle and control through {@link NetworkPolicy}.
104 */
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700105public class DataUsageSummary extends Fragment {
106 private static final String TAG = "DataUsage";
Jeff Sharkey8a503642011-06-10 13:31:21 -0700107 private static final boolean LOGD = true;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700108
Jeff Sharkey8a503642011-06-10 13:31:21 -0700109 private static final int TEMPLATE_INVALID = -1;
110
111 private static final String TAB_3G = "3g";
112 private static final String TAB_4G = "4g";
113 private static final String TAB_MOBILE = "mobile";
114 private static final String TAB_WIFI = "wifi";
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700115
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700116 private static final String TAG_CONFIRM_LIMIT = "confirmLimit";
117 private static final String TAG_CYCLE_EDITOR = "cycleEditor";
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700118 private static final String TAG_POLICY_LIMIT = "policyLimit";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700119
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700120 private static final long KB_IN_BYTES = 1024;
121 private static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
122 private static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
123
124 private INetworkStatsService mStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700125 private INetworkPolicyManager mPolicyService;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700126 private ConnectivityManager mConnService;
127
128 private static final String PREF_FILE = "data_usage";
129 private static final String PREF_SHOW_WIFI = "show_wifi";
130
131 private SharedPreferences mPrefs;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700132
Jeff Sharkey8a503642011-06-10 13:31:21 -0700133 private TabHost mTabHost;
134 private TabWidget mTabWidget;
135 private ListView mListView;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700136 private DataUsageAdapter mAdapter;
137
Jeff Sharkey8a503642011-06-10 13:31:21 -0700138 private View mHeader;
139 private LinearLayout mSwitches;
140
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700141 private Switch mDataEnabled;
142 private CheckBox mDisableAtLimit;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700143 private View mDataEnabledView;
144 private View mDisableAtLimitView;
145
146 private DataUsageChartView mChart;
147
148 private Spinner mCycleSpinner;
149 private CycleAdapter mCycleAdapter;
150
Jeff Sharkey8a503642011-06-10 13:31:21 -0700151 private boolean mShowWifi = false;
152
Jeff Sharkeya662e492011-06-18 21:57:06 -0700153 private NetworkTemplate mTemplate = null;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700154
Jeff Sharkeya662e492011-06-18 21:57:06 -0700155 private NetworkPolicyEditor mPolicyEditor;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700156 private NetworkStatsHistory mHistory;
157
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700158 private String mIntentTab = null;
159
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700160 /** Flag used to ignore listeners during binding. */
161 private boolean mBinding;
162
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700163 @Override
Jeff Sharkey8a503642011-06-10 13:31:21 -0700164 public void onCreate(Bundle savedInstanceState) {
165 super.onCreate(savedInstanceState);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700166
167 mStatsService = INetworkStatsService.Stub.asInterface(
168 ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700169 mPolicyService = INetworkPolicyManager.Stub.asInterface(
170 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700171 mConnService = (ConnectivityManager) getActivity().getSystemService(
172 Context.CONNECTIVITY_SERVICE);
173 mPrefs = getActivity().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700174
Jeff Sharkeya662e492011-06-18 21:57:06 -0700175 mPolicyEditor = new NetworkPolicyEditor(mPolicyService);
176 mPolicyEditor.read();
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700177
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700178 mShowWifi = mPrefs.getBoolean(PREF_SHOW_WIFI, false);
179
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700180 setHasOptionsMenu(true);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700181 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700182
Jeff Sharkey8a503642011-06-10 13:31:21 -0700183 @Override
184 public View onCreateView(LayoutInflater inflater, ViewGroup container,
185 Bundle savedInstanceState) {
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700186
Jeff Sharkey8a503642011-06-10 13:31:21 -0700187 final Context context = inflater.getContext();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700188 final View view = inflater.inflate(R.layout.data_usage_summary, container, false);
189
Jeff Sharkey8a503642011-06-10 13:31:21 -0700190 mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
191 mTabWidget = (TabWidget) view.findViewById(android.R.id.tabs);
192 mListView = (ListView) view.findViewById(android.R.id.list);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700193
Jeff Sharkey8a503642011-06-10 13:31:21 -0700194 mTabHost.setup();
195 mTabHost.setOnTabChangedListener(mTabListener);
196
197 mHeader = inflater.inflate(R.layout.data_usage_header, mListView, false);
198 mListView.addHeaderView(mHeader, null, false);
199
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700200 mDataEnabled = new Switch(inflater.getContext());
201 mDataEnabledView = inflatePreference(inflater, mSwitches, mDataEnabled);
202 mDataEnabled.setOnCheckedChangeListener(mDataEnabledListener);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700203
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700204 mDisableAtLimit = new CheckBox(inflater.getContext());
Jeff Sharkey52c3f442011-06-23 00:39:38 -0700205 mDisableAtLimit.setClickable(false);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700206 mDisableAtLimitView = inflatePreference(inflater, mSwitches, mDisableAtLimit);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700207 mDisableAtLimitView.setOnClickListener(mDisableAtLimitListener);
208
209 mSwitches = (LinearLayout) mHeader.findViewById(R.id.switches);
210 mSwitches.addView(mDataEnabledView);
211 mSwitches.addView(mDisableAtLimitView);
212
213 mCycleSpinner = (Spinner) mHeader.findViewById(R.id.cycles);
214 mCycleAdapter = new CycleAdapter(context);
215 mCycleSpinner.setAdapter(mCycleAdapter);
216 mCycleSpinner.setOnItemSelectedListener(mCycleListener);
217
Jeff Sharkey52c3f442011-06-23 00:39:38 -0700218 mChart = (DataUsageChartView) inflater.inflate(R.layout.data_usage_chart, mListView, false);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700219 mChart.setListener(mChartListener);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700220 mListView.addHeaderView(mChart, null, false);
221
222 mAdapter = new DataUsageAdapter();
223 mListView.setOnItemClickListener(mListListener);
224 mListView.setAdapter(mAdapter);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700225
226 return view;
227 }
228
229 @Override
230 public void onResume() {
231 super.onResume();
232
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700233 // pick default tab based on incoming intent
234 final Intent intent = getActivity().getIntent();
235 mIntentTab = computeTabFromIntent(intent);
236
Jeff Sharkey8a503642011-06-10 13:31:21 -0700237 // this kicks off chain reaction which creates tabs, binds the body to
238 // selected network, and binds chart, cycles and detail list.
239 updateTabs();
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700240
241 // template and tab has been selected; show dialog if limit passed
242 final String action = intent.getAction();
243 if (ACTION_DATA_USAGE_LIMIT.equals(action)) {
244 PolicyLimitFragment.show(this);
245 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700246 }
247
Jeff Sharkey8a503642011-06-10 13:31:21 -0700248 @Override
249 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
250 inflater.inflate(R.menu.data_usage, menu);
251 }
252
253 @Override
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700254 public void onPrepareOptionsMenu(Menu menu) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700255 final Context context = getActivity();
256
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700257 final MenuItem split4g = menu.findItem(R.id.action_split_4g);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700258 split4g.setVisible(hasMobile4gRadio(context));
Jeff Sharkeya662e492011-06-18 21:57:06 -0700259 split4g.setChecked(isMobilePolicySplit());
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700260
261 final MenuItem showWifi = menu.findItem(R.id.action_show_wifi);
262 showWifi.setVisible(hasMobileRadio(context) && hasWifiRadio(context));
263 showWifi.setChecked(mShowWifi);
264
265 final MenuItem settings = menu.findItem(R.id.action_settings);
266 settings.setVisible(split4g.isVisible() || showWifi.isVisible());
267
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700268 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700269
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700270 @Override
271 public boolean onOptionsItemSelected(MenuItem item) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700272 switch (item.getItemId()) {
273 case R.id.action_split_4g: {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700274 final boolean mobileSplit = !item.isChecked();
Jeff Sharkeya662e492011-06-18 21:57:06 -0700275 setMobilePolicySplit(mobileSplit);
276 item.setChecked(isMobilePolicySplit());
Jeff Sharkey8a503642011-06-10 13:31:21 -0700277 updateTabs();
278 return true;
279 }
280 case R.id.action_show_wifi: {
281 mShowWifi = !item.isChecked();
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700282 mPrefs.edit().putBoolean(PREF_SHOW_WIFI, mShowWifi).apply();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700283 item.setChecked(mShowWifi);
284 updateTabs();
285 return true;
286 }
287 }
288 return false;
289 }
290
Jeff Sharkey94a90952011-06-13 22:31:09 -0700291 @Override
292 public void onDestroyView() {
293 super.onDestroyView();
294
295 mDataEnabledView = null;
296 mDisableAtLimitView = null;
297 }
298
Jeff Sharkey8a503642011-06-10 13:31:21 -0700299 /**
Jeff Sharkeya662e492011-06-18 21:57:06 -0700300 * Rebuild all tabs based on {@link NetworkPolicyEditor} and
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700301 * {@link #mShowWifi}, hiding the tabs entirely when applicable. Selects
302 * first tab, and kicks off a full rebind of body contents.
Jeff Sharkey8a503642011-06-10 13:31:21 -0700303 */
304 private void updateTabs() {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700305 final Context context = getActivity();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700306 mTabHost.clearAllTabs();
307
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700308 final boolean mobileSplit = isMobilePolicySplit();
309 if (mobileSplit && hasMobile4gRadio(context)) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700310 mTabHost.addTab(buildTabSpec(TAB_3G, R.string.data_usage_tab_3g));
311 mTabHost.addTab(buildTabSpec(TAB_4G, R.string.data_usage_tab_4g));
312 }
313
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700314 if (mShowWifi && hasWifiRadio(context) && hasMobileRadio(context)) {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700315 if (!mobileSplit) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700316 mTabHost.addTab(buildTabSpec(TAB_MOBILE, R.string.data_usage_tab_mobile));
317 }
318 mTabHost.addTab(buildTabSpec(TAB_WIFI, R.string.data_usage_tab_wifi));
319 }
320
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700321 final boolean hasTabs = mTabWidget.getTabCount() > 0;
322 mTabWidget.setVisibility(hasTabs ? View.VISIBLE : View.GONE);
323 if (hasTabs) {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700324 if (mIntentTab != null) {
325 // select default tab, which will kick off updateBody()
326 mTabHost.setCurrentTabByTag(mIntentTab);
327 } else {
328 // select first tab, which will kick off updateBody()
329 mTabHost.setCurrentTab(0);
330 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700331 } else {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700332 // no tabs visible; update body manually
Jeff Sharkey8a503642011-06-10 13:31:21 -0700333 updateBody();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700334 }
335 }
336
Jeff Sharkey8a503642011-06-10 13:31:21 -0700337 /**
338 * Factory that provide empty {@link View} to make {@link TabHost} happy.
339 */
340 private TabContentFactory mEmptyTabContent = new TabContentFactory() {
341 /** {@inheritDoc} */
342 public View createTabContent(String tag) {
343 return new View(mTabHost.getContext());
344 }
345 };
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700346
Jeff Sharkey8a503642011-06-10 13:31:21 -0700347 /**
348 * Build {@link TabSpec} with thin indicator, and empty content.
349 */
350 private TabSpec buildTabSpec(String tag, int titleRes) {
351 final LayoutInflater inflater = LayoutInflater.from(mTabWidget.getContext());
352 final View indicator = inflater.inflate(
353 R.layout.tab_indicator_thin_holo, mTabWidget, false);
354 final TextView title = (TextView) indicator.findViewById(android.R.id.title);
355 title.setText(titleRes);
356 return mTabHost.newTabSpec(tag).setIndicator(indicator).setContent(mEmptyTabContent);
357 }
358
359 private OnTabChangeListener mTabListener = new OnTabChangeListener() {
360 /** {@inheritDoc} */
361 public void onTabChanged(String tabId) {
362 // user changed tab; update body
363 updateBody();
364 }
365 };
366
367 /**
368 * Update body content based on current tab. Loads
369 * {@link NetworkStatsHistory} and {@link NetworkPolicy} from system, and
370 * binds them to visible controls.
371 */
372 private void updateBody() {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700373 mBinding = true;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700374
Jeff Sharkeya662e492011-06-18 21:57:06 -0700375 final Context context = getActivity();
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700376 final String tabTag = mTabHost.getCurrentTabTag();
377
378 final String currentTab;
379 if (tabTag != null) {
380 currentTab = tabTag;
381 } else if (hasMobileRadio(context)) {
382 currentTab = TAB_MOBILE;
383 } else if (hasWifiRadio(context)) {
384 currentTab = TAB_WIFI;
385 } else {
386 throw new IllegalStateException("no mobile or wifi radios");
387 }
Jeff Sharkeya662e492011-06-18 21:57:06 -0700388
Jeff Sharkey8a503642011-06-10 13:31:21 -0700389 if (LOGD) Log.d(TAG, "updateBody() with currentTab=" + currentTab);
390
391 if (TAB_WIFI.equals(currentTab)) {
392 // wifi doesn't have any controls
393 mDataEnabledView.setVisibility(View.GONE);
394 mDisableAtLimitView.setVisibility(View.GONE);
Jeff Sharkeya662e492011-06-18 21:57:06 -0700395 mTemplate = new NetworkTemplate(MATCH_WIFI, null);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700396
397 } else {
398 // make sure we show for non-wifi
399 mDataEnabledView.setVisibility(View.VISIBLE);
400 mDisableAtLimitView.setVisibility(View.VISIBLE);
401 }
402
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700403 final String subscriberId = getActiveSubscriberId(context);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700404 if (TAB_MOBILE.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700405 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_mobile);
406 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_mobile_limit);
407 mDataEnabled.setChecked(mConnService.getMobileDataEnabled());
Jeff Sharkeya662e492011-06-18 21:57:06 -0700408 mTemplate = new NetworkTemplate(MATCH_MOBILE_ALL, subscriberId);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700409
410 } else if (TAB_3G.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700411 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_3g);
412 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_3g_limit);
413 // TODO: bind mDataEnabled to 3G radio state
Jeff Sharkeya662e492011-06-18 21:57:06 -0700414 mTemplate = new NetworkTemplate(MATCH_MOBILE_3G_LOWER, subscriberId);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700415
416 } else if (TAB_4G.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700417 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_4g);
418 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_4g_limit);
419 // TODO: bind mDataEnabled to 4G radio state
Jeff Sharkeya662e492011-06-18 21:57:06 -0700420 mTemplate = new NetworkTemplate(MATCH_MOBILE_4G, subscriberId);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700421 }
422
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700423 try {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700424 // load stats for current template
Jeff Sharkey8a503642011-06-10 13:31:21 -0700425 mHistory = mStatsService.getHistoryForNetwork(mTemplate);
426 } catch (RemoteException e) {
427 // since we can't do much without policy or history, and we don't
428 // want to leave with half-baked UI, we bail hard.
429 throw new RuntimeException("problem reading network policy or stats", e);
430 }
431
Jeff Sharkey8a503642011-06-10 13:31:21 -0700432 // bind chart to historical stats
Jeff Sharkey8a503642011-06-10 13:31:21 -0700433 mChart.bindNetworkStats(mHistory);
434
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700435 updatePolicy(true);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700436
437 // force scroll to top of body
438 mListView.smoothScrollToPosition(0);
439
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700440 mBinding = false;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700441 }
442
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700443 private void setPolicyCycleDay(int cycleDay) {
444 if (LOGD) Log.d(TAG, "setPolicyCycleDay()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700445 mPolicyEditor.setPolicyCycleDay(mTemplate, cycleDay);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700446 updatePolicy(true);
447 }
448
449 private void setPolicyWarningBytes(long warningBytes) {
450 if (LOGD) Log.d(TAG, "setPolicyWarningBytes()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700451 mPolicyEditor.setPolicyWarningBytes(mTemplate, warningBytes);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700452 updatePolicy(false);
453 }
454
455 private void setPolicyLimitBytes(long limitBytes) {
456 if (LOGD) Log.d(TAG, "setPolicyLimitBytes()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700457 mPolicyEditor.setPolicyLimitBytes(mTemplate, limitBytes);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700458 updatePolicy(false);
459 }
460
Jeff Sharkey8a503642011-06-10 13:31:21 -0700461 /**
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700462 * Update chart sweeps and cycle list to reflect {@link NetworkPolicy} for
463 * current {@link #mTemplate}.
464 */
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700465 private void updatePolicy(boolean refreshCycle) {
Jeff Sharkeya662e492011-06-18 21:57:06 -0700466 final NetworkPolicy policy = mPolicyEditor.getPolicy(mTemplate);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700467
468 // reflect policy limit in checkbox
469 mDisableAtLimit.setChecked(policy != null && policy.limitBytes != LIMIT_DISABLED);
470 mChart.bindNetworkPolicy(policy);
471
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700472 if (refreshCycle) {
473 // generate cycle list based on policy and available history
474 updateCycleList(policy);
475 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700476 }
477
478 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -0700479 * Return full time bounds (earliest and latest time recorded) of the given
480 * {@link NetworkStatsHistory}.
481 */
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700482 public static long[] getHistoryBounds(NetworkStatsHistory history) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700483 final long currentTime = System.currentTimeMillis();
484
485 long start = currentTime;
486 long end = currentTime;
487 if (history.bucketCount > 0) {
488 start = history.bucketStart[0];
489 end = history.bucketStart[history.bucketCount - 1];
490 }
491
492 return new long[] { start, end };
493 }
494
495 /**
496 * Rebuild {@link #mCycleAdapter} based on {@link NetworkPolicy#cycleDay}
497 * and available {@link NetworkStatsHistory} data. Always selects the newest
498 * item, updating the inspection range on {@link #mChart}.
499 */
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700500 private void updateCycleList(NetworkPolicy policy) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700501 mCycleAdapter.clear();
502
503 final Context context = mCycleSpinner.getContext();
504
505 final long[] bounds = getHistoryBounds(mHistory);
506 final long historyStart = bounds[0];
507 final long historyEnd = bounds[1];
508
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700509 if (policy != null) {
510 // find the next cycle boundary
511 long cycleEnd = computeNextCycleBoundary(historyEnd, policy);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700512
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700513 int guardCount = 0;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700514
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700515 // walk backwards, generating all valid cycle ranges
516 while (cycleEnd > historyStart) {
517 final long cycleStart = computeLastCycleBoundary(cycleEnd, policy);
518 Log.d(TAG, "generating cs=" + cycleStart + " to ce=" + cycleEnd + " waiting for hs="
519 + historyStart);
520 mCycleAdapter.add(new CycleItem(context, cycleStart, cycleEnd));
521 cycleEnd = cycleStart;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700522
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700523 // TODO: remove this guard once we have better testing
524 if (guardCount++ > 50) {
525 Log.wtf(TAG, "stuck generating ranges for bounds=" + Arrays.toString(bounds)
526 + " and policy=" + policy);
527 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700528 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700529
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700530 // one last cycle entry to modify policy cycle day
531 mCycleAdapter.add(new CycleChangeItem(context));
532
533 } else {
534 // no valid cycle; show all data
535 // TODO: offer simple ranges like "last week" etc
536 mCycleAdapter.add(new CycleItem(context, historyStart, historyEnd));
537
538 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700539
540 // force pick the current cycle (first item)
541 mCycleSpinner.setSelection(0);
542 mCycleListener.onItemSelected(mCycleSpinner, null, 0, 0);
543 }
544
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700545 private OnCheckedChangeListener mDataEnabledListener = new OnCheckedChangeListener() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700546 /** {@inheritDoc} */
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700547 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
548 if (mBinding) return;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700549
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700550 final boolean dataEnabled = isChecked;
551 mDataEnabled.setChecked(dataEnabled);
552
553 switch (mTemplate.getMatchRule()) {
554 case MATCH_MOBILE_ALL: {
555 mConnService.setMobileDataEnabled(dataEnabled);
556 }
557 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700558 }
559 };
560
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700561 private View.OnClickListener mDisableAtLimitListener = new View.OnClickListener() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700562 /** {@inheritDoc} */
563 public void onClick(View v) {
564 final boolean disableAtLimit = !mDisableAtLimit.isChecked();
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700565 if (disableAtLimit) {
566 // enabling limit; show confirmation dialog which eventually
567 // calls setPolicyLimitBytes() once user confirms.
568 ConfirmLimitFragment.show(DataUsageSummary.this);
569 } else {
570 setPolicyLimitBytes(LIMIT_DISABLED);
571 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700572 }
573 };
574
575 private OnItemClickListener mListListener = new OnItemClickListener() {
576 /** {@inheritDoc} */
577 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700578 final AppUsageItem app = (AppUsageItem) parent.getItemAtPosition(position);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700579
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700580 final Bundle args = new Bundle();
Jeff Sharkeya662e492011-06-18 21:57:06 -0700581 args.putParcelable(DataUsageAppDetail.EXTRA_NETWORK_TEMPLATE, mTemplate);
582 args.putInt(DataUsageAppDetail.EXTRA_UID, app.uid);
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700583
584 final PreferenceActivity activity = (PreferenceActivity) getActivity();
585 activity.startPreferencePanel(DataUsageAppDetail.class.getName(), args,
586 R.string.data_usage_summary_title, null, null, 0);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700587 }
588 };
589
590 private OnItemSelectedListener mCycleListener = new OnItemSelectedListener() {
591 /** {@inheritDoc} */
592 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
593 final CycleItem cycle = (CycleItem) parent.getItemAtPosition(position);
594 if (cycle instanceof CycleChangeItem) {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700595 // show cycle editor; will eventually call setPolicyCycleDay()
596 // when user finishes editing.
597 CycleEditorFragment.show(DataUsageSummary.this);
598
599 // reset spinner to something other than "change cycle..."
600 mCycleSpinner.setSelection(0);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700601
602 } else {
Jeff Sharkey8e911d72011-06-14 22:41:21 -0700603 if (LOGD) {
604 Log.d(TAG, "showing cycle " + cycle + ", start=" + cycle.start + ", end="
605 + cycle.end + "]");
606 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700607
608 // update chart to show selected cycle, and update detail data
609 // to match updated sweep bounds.
610 final long[] bounds = getHistoryBounds(mHistory);
611 mChart.setVisibleRange(cycle.start, cycle.end, bounds[1]);
612
613 updateDetailData();
614 }
615 }
616
617 /** {@inheritDoc} */
618 public void onNothingSelected(AdapterView<?> parent) {
619 // ignored
620 }
621 };
622
623 /**
624 * Update {@link #mAdapter} with sorted list of applications data usage,
625 * based on current inspection from {@link #mChart}.
626 */
627 private void updateDetailData() {
628 if (LOGD) Log.d(TAG, "updateDetailData()");
629
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -0700630 new AsyncTask<Void, Void, NetworkStats>() {
631 @Override
632 protected NetworkStats doInBackground(Void... params) {
633 try {
634 final long[] range = mChart.getInspectRange();
Jeff Sharkey827fde32011-06-19 20:56:31 -0700635 return mStatsService.getSummaryForAllUid(mTemplate, range[0], range[1], false);
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -0700636 } catch (RemoteException e) {
637 Log.w(TAG, "problem reading stats");
638 }
639 return null;
640 }
641
642 @Override
643 protected void onPostExecute(NetworkStats stats) {
644 if (stats != null) {
645 mAdapter.bindStats(stats);
646 }
647 }
648 }.execute();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700649 }
650
Jeff Sharkeya662e492011-06-18 21:57:06 -0700651 private boolean isMobilePolicySplit() {
652 final String subscriberId = getActiveSubscriberId(getActivity());
653 return mPolicyEditor.isMobilePolicySplit(subscriberId);
654 }
655
656 private void setMobilePolicySplit(boolean split) {
657 final String subscriberId = getActiveSubscriberId(getActivity());
658 mPolicyEditor.setMobilePolicySplit(subscriberId, split);
659 }
660
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700661 private static String getActiveSubscriberId(Context context) {
662 final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
663 Context.TELEPHONY_SERVICE);
664 return telephony.getSubscriberId();
665 }
666
Jeff Sharkey8a503642011-06-10 13:31:21 -0700667 private DataUsageChartListener mChartListener = new DataUsageChartListener() {
668 /** {@inheritDoc} */
669 public void onInspectRangeChanged() {
670 if (LOGD) Log.d(TAG, "onInspectRangeChanged()");
671 updateDetailData();
672 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700673
Jeff Sharkey8a503642011-06-10 13:31:21 -0700674 /** {@inheritDoc} */
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700675 public void onWarningChanged() {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700676 setPolicyWarningBytes(mChart.getWarningBytes());
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700677 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700678
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700679 /** {@inheritDoc} */
680 public void onLimitChanged() {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700681 setPolicyLimitBytes(mChart.getLimitBytes());
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700682 }
683 };
684
685
686 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -0700687 * List item that reflects a specific data usage cycle.
688 */
689 public static class CycleItem {
690 public CharSequence label;
691 public long start;
692 public long end;
693
694 private static final StringBuilder sBuilder = new StringBuilder(50);
695 private static final java.util.Formatter sFormatter = new java.util.Formatter(
696 sBuilder, Locale.getDefault());
697
698 CycleItem(CharSequence label) {
699 this.label = label;
700 }
701
702 public CycleItem(Context context, long start, long end) {
703 this.label = formatDateRangeUtc(context, start, end);
704 this.start = start;
705 this.end = end;
706 }
707
708 private static String formatDateRangeUtc(Context context, long start, long end) {
709 synchronized (sBuilder) {
710 sBuilder.setLength(0);
711 return DateUtils.formatDateRange(context, sFormatter, start, end,
712 DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH,
713 Time.TIMEZONE_UTC).toString();
714 }
715 }
716
717 @Override
718 public String toString() {
719 return label.toString();
720 }
721 }
722
723 /**
724 * Special-case data usage cycle that triggers dialog to change
725 * {@link NetworkPolicy#cycleDay}.
726 */
727 public static class CycleChangeItem extends CycleItem {
728 public CycleChangeItem(Context context) {
729 super(context.getString(R.string.data_usage_change_cycle));
730 }
731 }
732
733 public static class CycleAdapter extends ArrayAdapter<CycleItem> {
734 public CycleAdapter(Context context) {
735 super(context, android.R.layout.simple_spinner_item);
736 setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
737 }
738 }
739
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700740 private static class AppUsageItem implements Comparable<AppUsageItem> {
741 public int uid;
742 public long total;
743
744 /** {@inheritDoc} */
745 public int compareTo(AppUsageItem another) {
746 return Long.compare(another.total, total);
747 }
748 }
749
Jeff Sharkey8a503642011-06-10 13:31:21 -0700750 /**
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700751 * Adapter of applications, sorted by total usage descending.
752 */
753 public static class DataUsageAdapter extends BaseAdapter {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700754 private ArrayList<AppUsageItem> mItems = Lists.newArrayList();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700755
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700756 public void bindStats(NetworkStats stats) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700757 mItems.clear();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700758
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700759 for (int i = 0; i < stats.size; i++) {
Jeff Sharkey8e911d72011-06-14 22:41:21 -0700760 final long total = stats.rx[i] + stats.tx[i];
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700761 final AppUsageItem item = new AppUsageItem();
762 item.uid = stats.uid[i];
763 item.total = total;
764 mItems.add(item);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700765 }
766
Jeff Sharkey8a503642011-06-10 13:31:21 -0700767 Collections.sort(mItems);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700768 notifyDataSetChanged();
769 }
770
771 @Override
772 public int getCount() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700773 return mItems.size();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700774 }
775
776 @Override
777 public Object getItem(int position) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700778 return mItems.get(position);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700779 }
780
781 @Override
782 public long getItemId(int position) {
783 return position;
784 }
785
786 @Override
787 public View getView(int position, View convertView, ViewGroup parent) {
788 if (convertView == null) {
789 convertView = LayoutInflater.from(parent.getContext()).inflate(
Jeff Sharkey52c3f442011-06-23 00:39:38 -0700790 R.layout.data_usage_item, parent, false);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700791 }
792
793 final Context context = parent.getContext();
794 final PackageManager pm = context.getPackageManager();
795
796 final TextView text1 = (TextView) convertView.findViewById(android.R.id.text1);
797 final TextView text2 = (TextView) convertView.findViewById(android.R.id.text2);
798
Jeff Sharkey8a503642011-06-10 13:31:21 -0700799 final AppUsageItem item = mItems.get(position);
Jeff Sharkey8e911d72011-06-14 22:41:21 -0700800 text1.setText(resolveLabelForUid(pm, item.uid));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700801 text2.setText(Formatter.formatFileSize(context, item.total));
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700802
803 return convertView;
804 }
805
806 }
807
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700808 /**
809 * Dialog to request user confirmation before setting
810 * {@link NetworkPolicy#limitBytes}.
811 */
812 public static class ConfirmLimitFragment extends DialogFragment {
813 public static final String EXTRA_MESSAGE_ID = "messageId";
814 public static final String EXTRA_LIMIT_BYTES = "limitBytes";
815
816 public static void show(DataUsageSummary parent) {
817 final Bundle args = new Bundle();
818
819 // TODO: customize default limits based on network template
Jeff Sharkeya662e492011-06-18 21:57:06 -0700820 switch (parent.mTemplate.getMatchRule()) {
821 case MATCH_MOBILE_3G_LOWER: {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700822 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_3g);
823 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
824 break;
825 }
Jeff Sharkeya662e492011-06-18 21:57:06 -0700826 case MATCH_MOBILE_4G: {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700827 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_4g);
828 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
829 break;
830 }
Jeff Sharkeya662e492011-06-18 21:57:06 -0700831 case MATCH_MOBILE_ALL: {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700832 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_mobile);
833 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
834 break;
835 }
836 }
837
838 final ConfirmLimitFragment dialog = new ConfirmLimitFragment();
839 dialog.setArguments(args);
840 dialog.setTargetFragment(parent, 0);
841 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_LIMIT);
842 }
843
844 @Override
845 public Dialog onCreateDialog(Bundle savedInstanceState) {
846 final Context context = getActivity();
847
848 final int messageId = getArguments().getInt(EXTRA_MESSAGE_ID);
849 final long limitBytes = getArguments().getLong(EXTRA_LIMIT_BYTES);
850
851 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
852 builder.setTitle(R.string.data_usage_limit_dialog_title);
853 builder.setMessage(messageId);
854
855 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
856 public void onClick(DialogInterface dialog, int which) {
857 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
858 if (target != null) {
859 target.setPolicyLimitBytes(limitBytes);
860 }
861 }
862 });
863
864 return builder.create();
865 }
866 }
867
868 /**
869 * Dialog to edit {@link NetworkPolicy#cycleDay}.
870 */
871 public static class CycleEditorFragment extends DialogFragment {
872 public static final String EXTRA_CYCLE_DAY = "cycleDay";
873
874 public static void show(DataUsageSummary parent) {
Jeff Sharkeya662e492011-06-18 21:57:06 -0700875 final NetworkPolicy policy = parent.mPolicyEditor.getPolicy(parent.mTemplate);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700876 final Bundle args = new Bundle();
877 args.putInt(CycleEditorFragment.EXTRA_CYCLE_DAY, policy.cycleDay);
878
879 final CycleEditorFragment dialog = new CycleEditorFragment();
880 dialog.setArguments(args);
881 dialog.setTargetFragment(parent, 0);
882 dialog.show(parent.getFragmentManager(), TAG_CYCLE_EDITOR);
883 }
884
885 @Override
886 public Dialog onCreateDialog(Bundle savedInstanceState) {
887 final Context context = getActivity();
888
889 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
890 final LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext());
891
892 final View view = dialogInflater.inflate(R.layout.data_usage_cycle_editor, null, false);
893 final NumberPicker cycleDayPicker = (NumberPicker) view.findViewById(R.id.cycle_day);
894
895 final int oldCycleDay = getArguments().getInt(EXTRA_CYCLE_DAY, 1);
896
897 cycleDayPicker.setMinValue(1);
898 cycleDayPicker.setMaxValue(31);
899 cycleDayPicker.setValue(oldCycleDay);
900 cycleDayPicker.setWrapSelectorWheel(true);
901
902 builder.setTitle(R.string.data_usage_cycle_editor_title);
903 builder.setView(view);
904
905 builder.setPositiveButton(R.string.data_usage_cycle_editor_positive,
906 new DialogInterface.OnClickListener() {
907 public void onClick(DialogInterface dialog, int which) {
908 final int cycleDay = cycleDayPicker.getValue();
909 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
910 if (target != null) {
911 target.setPolicyCycleDay(cycleDay);
912 }
913 }
914 });
915
916 return builder.create();
917 }
918 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700919
Jeff Sharkey8e911d72011-06-14 22:41:21 -0700920 /**
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700921 * Dialog explaining that {@link NetworkPolicy#limitBytes} has been passed,
922 * and giving the user an option to bypass.
923 */
924 public static class PolicyLimitFragment extends DialogFragment {
925 public static final String EXTRA_TITLE_ID = "titleId";
926
927 public static void show(DataUsageSummary parent) {
928 final Bundle args = new Bundle();
929
Jeff Sharkeya662e492011-06-18 21:57:06 -0700930 switch (parent.mTemplate.getMatchRule()) {
931 case MATCH_MOBILE_3G_LOWER: {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700932 args.putInt(EXTRA_TITLE_ID, R.string.data_usage_disabled_dialog_3g_title);
933 break;
934 }
Jeff Sharkeya662e492011-06-18 21:57:06 -0700935 case MATCH_MOBILE_4G: {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700936 args.putInt(EXTRA_TITLE_ID, R.string.data_usage_disabled_dialog_4g_title);
937 break;
938 }
Jeff Sharkeya662e492011-06-18 21:57:06 -0700939 case MATCH_MOBILE_ALL: {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700940 args.putInt(EXTRA_TITLE_ID, R.string.data_usage_disabled_dialog_mobile_title);
941 break;
942 }
943 }
944
945 final PolicyLimitFragment dialog = new PolicyLimitFragment();
946 dialog.setArguments(args);
947 dialog.setTargetFragment(parent, 0);
948 dialog.show(parent.getFragmentManager(), TAG_POLICY_LIMIT);
949 }
950
951 @Override
952 public Dialog onCreateDialog(Bundle savedInstanceState) {
953 final Context context = getActivity();
954
955 final int titleId = getArguments().getInt(EXTRA_TITLE_ID);
956
957 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
958 builder.setTitle(titleId);
959 builder.setMessage(R.string.data_usage_disabled_dialog);
960
961 builder.setPositiveButton(android.R.string.ok, null);
962 builder.setNegativeButton(R.string.data_usage_disabled_dialog_enable,
963 new DialogInterface.OnClickListener() {
964 public void onClick(DialogInterface dialog, int which) {
965 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
966 if (target != null) {
967 // TODO: consider "allow 100mb more data", or
968 // only bypass limit for current cycle.
969 target.setPolicyLimitBytes(LIMIT_DISABLED);
970 }
971 }
972 });
973
974 return builder.create();
975 }
976 }
977
978 /**
979 * Compute default tab that should be selected, based on
980 * {@link NetworkPolicyManager#EXTRA_NETWORK_TEMPLATE} extra.
981 */
982 private static String computeTabFromIntent(Intent intent) {
983 final int networkTemplate = intent.getIntExtra(EXTRA_NETWORK_TEMPLATE, TEMPLATE_INVALID);
984 switch (networkTemplate) {
Jeff Sharkeya662e492011-06-18 21:57:06 -0700985 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700986 return TAB_3G;
Jeff Sharkeya662e492011-06-18 21:57:06 -0700987 case MATCH_MOBILE_4G:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700988 return TAB_4G;
Jeff Sharkeya662e492011-06-18 21:57:06 -0700989 case MATCH_MOBILE_ALL:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700990 return TAB_MOBILE;
Jeff Sharkeya662e492011-06-18 21:57:06 -0700991 case MATCH_WIFI:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700992 return TAB_WIFI;
993 default:
994 return null;
995 }
996 }
997
998 /**
Jeff Sharkey8e911d72011-06-14 22:41:21 -0700999 * Resolve best descriptive label for the given UID.
1000 */
1001 public static CharSequence resolveLabelForUid(PackageManager pm, int uid) {
1002 final String[] packageNames = pm.getPackagesForUid(uid);
1003 final int length = packageNames != null ? packageNames.length : 0;
1004
1005 CharSequence label = pm.getNameForUid(uid);
1006 try {
1007 if (length == 1) {
1008 final ApplicationInfo info = pm.getApplicationInfo(packageNames[0], 0);
1009 label = info.loadLabel(pm);
1010 } else if (length > 1) {
1011 for (String packageName : packageNames) {
1012 final PackageInfo info = pm.getPackageInfo(packageName, 0);
1013 if (info.sharedUserLabel != 0) {
1014 label = pm.getText(packageName, info.sharedUserLabel, info.applicationInfo);
1015 if (!TextUtils.isEmpty(label)) {
1016 break;
1017 }
1018 }
1019 }
1020 }
1021 } catch (NameNotFoundException e) {
1022 }
1023
1024 if (TextUtils.isEmpty(label)) {
1025 label = Integer.toString(uid);
1026 }
1027 return label;
1028 }
1029
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001030 /**
1031 * Test if device has a mobile data radio.
1032 */
1033 private static boolean hasMobileRadio(Context context) {
1034 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1035 Context.CONNECTIVITY_SERVICE);
1036
1037 // mobile devices should have MOBILE network tracker regardless of
1038 // connection status.
1039 return conn.getNetworkInfo(TYPE_MOBILE) != null;
1040 }
1041
1042 /**
1043 * Test if device has a mobile 4G data radio.
1044 */
1045 private static boolean hasMobile4gRadio(Context context) {
1046 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1047 Context.CONNECTIVITY_SERVICE);
1048 final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
1049 Context.TELEPHONY_SERVICE);
1050
1051 // WiMAX devices should have WiMAX network tracker regardless of
1052 // connection status.
1053 final boolean hasWimax = conn.getNetworkInfo(TYPE_WIMAX) != null;
1054 final boolean hasLte = telephony.getLteOnCdmaMode() == Phone.LTE_ON_CDMA_TRUE;
1055 return hasWimax || hasLte;
1056 }
1057
1058 /**
1059 * Test if device has a Wi-Fi data radio.
1060 */
1061 private static boolean hasWifiRadio(Context context) {
1062 return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI);
1063 }
1064
1065 /**
1066 * Inflate a {@link Preference} style layout, adding the given {@link View}
1067 * widget into {@link android.R.id#widget_frame}.
1068 */
1069 private static View inflatePreference(LayoutInflater inflater, ViewGroup root, View widget) {
1070 final View view = inflater.inflate(R.layout.preference, root, false);
1071 final LinearLayout widgetFrame = (LinearLayout) view.findViewById(
1072 android.R.id.widget_frame);
1073 widgetFrame.addView(widget, new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
1074 return view;
1075 }
1076
1077 /**
1078 * Set {@link android.R.id#title} for a preference view inflated with
Jeff Sharkey52c3f442011-06-23 00:39:38 -07001079 * {@link #inflatePreference(LayoutInflater, ViewGroup, View)}.
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001080 */
1081 private static void setPreferenceTitle(View parent, int resId) {
1082 final TextView title = (TextView) parent.findViewById(android.R.id.title);
1083 title.setText(resId);
1084 }
1085
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001086}