blob: 739ed589849ae1f7efc50daae537d77348e41255 [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 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 Sharkey29d56b32011-06-20 17:06:52 -070032import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070033
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070034import android.animation.LayoutTransition;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070035import android.app.AlertDialog;
36import android.app.Dialog;
37import android.app.DialogFragment;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070038import android.app.Fragment;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070039import android.app.FragmentTransaction;
Jeff Sharkey398b18f2011-07-10 18:56:30 -070040import android.app.LoaderManager.LoaderCallbacks;
Jeff Sharkey9fab0da2011-07-09 17:52:31 -070041import android.content.ContentResolver;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070042import android.content.Context;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070043import android.content.DialogInterface;
Jeff Sharkey4dfa6602011-06-13 00:42:03 -070044import android.content.Intent;
Jeff Sharkey398b18f2011-07-10 18:56:30 -070045import android.content.Loader;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070046import android.content.SharedPreferences;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070047import android.content.pm.ApplicationInfo;
48import android.content.pm.PackageInfo;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070049import android.content.pm.PackageManager;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070050import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -070051import android.content.res.Resources;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070052import android.net.ConnectivityManager;
Jeff Sharkey8a503642011-06-10 13:31:21 -070053import android.net.INetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070054import android.net.INetworkStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -070055import android.net.NetworkPolicy;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -070056import android.net.NetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070057import android.net.NetworkStats;
58import android.net.NetworkStatsHistory;
Jeff Sharkeya662e492011-06-18 21:57:06 -070059import android.net.NetworkTemplate;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -070060import android.net.TrafficStats;
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -070061import android.os.AsyncTask;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070062import android.os.Bundle;
63import android.os.RemoteException;
64import android.os.ServiceManager;
Jeff Sharkey8a503642011-06-10 13:31:21 -070065import android.preference.Preference;
Jeff Sharkey9fab0da2011-07-09 17:52:31 -070066import android.provider.Settings;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -070067import android.telephony.TelephonyManager;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070068import android.text.TextUtils;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070069import android.text.format.DateUtils;
70import android.text.format.Formatter;
Jeff Sharkey8a503642011-06-10 13:31:21 -070071import android.text.format.Time;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070072import android.util.Log;
73import android.view.LayoutInflater;
Jeff Sharkey8a503642011-06-10 13:31:21 -070074import android.view.Menu;
75import android.view.MenuInflater;
76import android.view.MenuItem;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070077import android.view.View;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070078import android.view.View.OnClickListener;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070079import android.view.ViewGroup;
Jeff Sharkey2af35fb2011-06-24 17:30:27 -070080import android.view.ViewTreeObserver.OnGlobalLayoutListener;
Jeff Sharkey8a503642011-06-10 13:31:21 -070081import android.widget.AdapterView;
82import android.widget.AdapterView.OnItemClickListener;
83import android.widget.AdapterView.OnItemSelectedListener;
84import android.widget.ArrayAdapter;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070085import android.widget.BaseAdapter;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070086import android.widget.Button;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070087import android.widget.CheckBox;
88import android.widget.CompoundButton;
89import android.widget.CompoundButton.OnCheckedChangeListener;
Jeff Sharkey8a503642011-06-10 13:31:21 -070090import android.widget.LinearLayout;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070091import android.widget.ListView;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070092import android.widget.NumberPicker;
Jeff Sharkey8a503642011-06-10 13:31:21 -070093import android.widget.Spinner;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070094import android.widget.Switch;
Jeff Sharkey8a503642011-06-10 13:31:21 -070095import android.widget.TabHost;
96import android.widget.TabHost.OnTabChangeListener;
97import android.widget.TabHost.TabContentFactory;
98import android.widget.TabHost.TabSpec;
99import android.widget.TabWidget;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700100import android.widget.TextView;
101
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700102import com.android.internal.telephony.Phone;
Jeff Sharkeya662e492011-06-18 21:57:06 -0700103import com.android.settings.net.NetworkPolicyEditor;
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700104import com.android.settings.net.SummaryForAllUidLoader;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700105import com.android.settings.widget.DataUsageChartView;
106import com.android.settings.widget.DataUsageChartView.DataUsageChartListener;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700107import com.google.android.collect.Lists;
108
109import java.util.ArrayList;
110import java.util.Collections;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700111import java.util.Locale;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700112
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700113/**
114 * Panel show data usage history across various networks, including options to
115 * inspect based on usage cycle and control through {@link NetworkPolicy}.
116 */
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700117public class DataUsageSummary extends Fragment {
118 private static final String TAG = "DataUsage";
Jeff Sharkey8a503642011-06-10 13:31:21 -0700119 private static final boolean LOGD = true;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700120
Jeff Sharkey8a503642011-06-10 13:31:21 -0700121 private static final String TAB_3G = "3g";
122 private static final String TAB_4G = "4g";
123 private static final String TAB_MOBILE = "mobile";
124 private static final String TAB_WIFI = "wifi";
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700125
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700126 private static final String TAG_CONFIRM_ROAMING = "confirmRoaming";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700127 private static final String TAG_CONFIRM_LIMIT = "confirmLimit";
128 private static final String TAG_CYCLE_EDITOR = "cycleEditor";
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700129 private static final String TAG_POLICY_LIMIT = "policyLimit";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700130 private static final String TAG_CONFIRM_RESTRICT = "confirmRestrict";
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700131 private static final String TAG_CONFIRM_APP_RESTRICT = "confirmAppRestrict";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700132 private static final String TAG_APP_DETAILS = "appDetails";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700133
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700134 private static final int LOADER_SUMMARY = 2;
135
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700136 private static final long KB_IN_BYTES = 1024;
137 private static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
138 private static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
139
140 private INetworkStatsService mStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700141 private INetworkPolicyManager mPolicyService;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700142 private ConnectivityManager mConnService;
143
144 private static final String PREF_FILE = "data_usage";
145 private static final String PREF_SHOW_WIFI = "show_wifi";
146
147 private SharedPreferences mPrefs;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700148
Jeff Sharkey8a503642011-06-10 13:31:21 -0700149 private TabHost mTabHost;
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700150 private ViewGroup mTabsContainer;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700151 private TabWidget mTabWidget;
152 private ListView mListView;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700153 private DataUsageAdapter mAdapter;
154
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700155 private ViewGroup mHeader;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700156
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700157 private ViewGroup mNetworkSwitchesContainer;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700158 private LinearLayout mNetworkSwitches;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700159 private Switch mDataEnabled;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700160 private View mDataEnabledView;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700161 private CheckBox mDisableAtLimit;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700162 private View mDisableAtLimitView;
163
Jeff Sharkey8a503642011-06-10 13:31:21 -0700164 private Spinner mCycleSpinner;
165 private CycleAdapter mCycleAdapter;
166
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700167 private DataUsageChartView mChart;
168
169 private View mAppDetail;
170 private TextView mAppTitle;
171 private TextView mAppSubtitle;
172 private Button mAppSettings;
173
174 private LinearLayout mAppSwitches;
175 private CheckBox mAppRestrict;
176 private View mAppRestrictView;
177
Jeff Sharkey8a503642011-06-10 13:31:21 -0700178 private boolean mShowWifi = false;
179
Jeff Sharkeya662e492011-06-18 21:57:06 -0700180 private NetworkTemplate mTemplate = null;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700181
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700182 private static final int UID_NONE = -1;
183 private int mUid = UID_NONE;
184
185 private Intent mAppSettingsIntent;
186
Jeff Sharkeya662e492011-06-18 21:57:06 -0700187 private NetworkPolicyEditor mPolicyEditor;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700188
Jeff Sharkey8a503642011-06-10 13:31:21 -0700189 private NetworkStatsHistory mHistory;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700190 private NetworkStatsHistory mDetailHistory;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700191
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700192 private String mCurrentTab = null;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700193 private String mIntentTab = null;
194
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700195 private MenuItem mMenuDataRoaming;
196 private MenuItem mMenuRestrictBackground;
197
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700198 /** Flag used to ignore listeners during binding. */
199 private boolean mBinding;
200
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700201 @Override
Jeff Sharkey8a503642011-06-10 13:31:21 -0700202 public void onCreate(Bundle savedInstanceState) {
203 super.onCreate(savedInstanceState);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700204
205 mStatsService = INetworkStatsService.Stub.asInterface(
206 ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700207 mPolicyService = INetworkPolicyManager.Stub.asInterface(
208 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700209 mConnService = (ConnectivityManager) getActivity().getSystemService(
210 Context.CONNECTIVITY_SERVICE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700211
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700212 mPrefs = getActivity().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700213
Jeff Sharkeya662e492011-06-18 21:57:06 -0700214 mPolicyEditor = new NetworkPolicyEditor(mPolicyService);
215 mPolicyEditor.read();
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700216
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700217 mShowWifi = mPrefs.getBoolean(PREF_SHOW_WIFI, false);
218
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700219 setHasOptionsMenu(true);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700220 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700221
Jeff Sharkey8a503642011-06-10 13:31:21 -0700222 @Override
223 public View onCreateView(LayoutInflater inflater, ViewGroup container,
224 Bundle savedInstanceState) {
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700225
Jeff Sharkey8a503642011-06-10 13:31:21 -0700226 final Context context = inflater.getContext();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700227 final View view = inflater.inflate(R.layout.data_usage_summary, container, false);
228
Jeff Sharkey8a503642011-06-10 13:31:21 -0700229 mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700230 mTabsContainer = (ViewGroup) view.findViewById(R.id.tabs_container);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700231 mTabWidget = (TabWidget) view.findViewById(android.R.id.tabs);
232 mListView = (ListView) view.findViewById(android.R.id.list);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700233
Jeff Sharkey8a503642011-06-10 13:31:21 -0700234 mTabHost.setup();
235 mTabHost.setOnTabChangedListener(mTabListener);
236
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700237 mHeader = (ViewGroup) inflater.inflate(R.layout.data_usage_header, mListView, false);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700238 mListView.addHeaderView(mHeader, null, false);
239
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700240 {
241 // bind network switches
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700242 mNetworkSwitchesContainer = (ViewGroup) mHeader.findViewById(
243 R.id.network_switches_container);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700244 mNetworkSwitches = (LinearLayout) mHeader.findViewById(R.id.network_switches);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700245
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700246 mDataEnabled = new Switch(inflater.getContext());
247 mDataEnabledView = inflatePreference(inflater, mNetworkSwitches, mDataEnabled);
248 mDataEnabled.setOnCheckedChangeListener(mDataEnabledListener);
249 mNetworkSwitches.addView(mDataEnabledView);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700250
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700251 mDisableAtLimit = new CheckBox(inflater.getContext());
252 mDisableAtLimit.setClickable(false);
253 mDisableAtLimitView = inflatePreference(inflater, mNetworkSwitches, mDisableAtLimit);
254 mDisableAtLimitView.setOnClickListener(mDisableAtLimitListener);
255 mNetworkSwitches.addView(mDisableAtLimitView);
256 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700257
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700258 // bind cycle dropdown
Jeff Sharkey8a503642011-06-10 13:31:21 -0700259 mCycleSpinner = (Spinner) mHeader.findViewById(R.id.cycles);
260 mCycleAdapter = new CycleAdapter(context);
261 mCycleSpinner.setAdapter(mCycleAdapter);
262 mCycleSpinner.setOnItemSelectedListener(mCycleListener);
263
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700264 mChart = (DataUsageChartView) mHeader.findViewById(R.id.chart);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700265 mChart.setListener(mChartListener);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700266
267 {
268 // bind app detail controls
269 mAppDetail = view.findViewById(R.id.app_detail);
270 mAppTitle = (TextView) view.findViewById(R.id.app_title);
271 mAppSubtitle = (TextView) view.findViewById(R.id.app_subtitle);
272 mAppSwitches = (LinearLayout) view.findViewById(R.id.app_switches);
273
274 mAppSettings = (Button) view.findViewById(R.id.app_settings);
275 mAppSettings.setOnClickListener(mAppSettingsListener);
276
277 mAppRestrict = new CheckBox(inflater.getContext());
278 mAppRestrict.setClickable(false);
279 mAppRestrictView = inflatePreference(inflater, mAppSwitches, mAppRestrict);
280 setPreferenceTitle(mAppRestrictView, R.string.data_usage_app_restrict_background);
281 setPreferenceSummary(
282 mAppRestrictView, R.string.data_usage_app_restrict_background_summary);
283 mAppRestrictView.setOnClickListener(mAppRestrictListener);
284 mAppSwitches.addView(mAppRestrictView);
285 }
286
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700287 // only assign layout transitions once first layout is finished
288 mHeader.getViewTreeObserver().addOnGlobalLayoutListener(mFirstLayoutListener);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700289
290 mAdapter = new DataUsageAdapter();
291 mListView.setOnItemClickListener(mListListener);
292 mListView.setAdapter(mAdapter);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700293
294 return view;
295 }
296
297 @Override
298 public void onResume() {
299 super.onResume();
300
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700301 // pick default tab based on incoming intent
302 final Intent intent = getActivity().getIntent();
303 mIntentTab = computeTabFromIntent(intent);
304
Jeff Sharkey8a503642011-06-10 13:31:21 -0700305 // this kicks off chain reaction which creates tabs, binds the body to
306 // selected network, and binds chart, cycles and detail list.
307 updateTabs();
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700308
309 // template and tab has been selected; show dialog if limit passed
310 final String action = intent.getAction();
311 if (ACTION_DATA_USAGE_LIMIT.equals(action)) {
312 PolicyLimitFragment.show(this);
313 }
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700314
315 // kick off background task to update stats
316 new AsyncTask<Void, Void, Void>() {
317 @Override
318 protected Void doInBackground(Void... params) {
319 try {
320 mStatsService.forceUpdate();
321 } catch (RemoteException e) {
322 }
323 return null;
324 }
325
326 @Override
327 protected void onPostExecute(Void result) {
328 updateBody();
329 }
330 }.execute();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700331 }
332
Jeff Sharkey8a503642011-06-10 13:31:21 -0700333 @Override
334 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
335 inflater.inflate(R.menu.data_usage, menu);
336 }
337
338 @Override
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700339 public void onPrepareOptionsMenu(Menu menu) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700340 final Context context = getActivity();
341
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700342 mMenuDataRoaming = menu.findItem(R.id.data_usage_menu_roaming);
343 mMenuDataRoaming.setVisible(hasMobileRadio(context));
344 mMenuDataRoaming.setChecked(getDataRoaming());
345
346 mMenuRestrictBackground = menu.findItem(R.id.data_usage_menu_restrict_background);
347 mMenuRestrictBackground.setChecked(getRestrictBackground());
348
349 final MenuItem split4g = menu.findItem(R.id.data_usage_menu_split_4g);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700350 split4g.setVisible(hasMobile4gRadio(context));
Jeff Sharkeya662e492011-06-18 21:57:06 -0700351 split4g.setChecked(isMobilePolicySplit());
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700352
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700353 final MenuItem showWifi = menu.findItem(R.id.data_usage_menu_show_wifi);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700354 showWifi.setVisible(hasMobileRadio(context) && hasWifiRadio(context));
355 showWifi.setChecked(mShowWifi);
356
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700357 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700358
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700359 @Override
360 public boolean onOptionsItemSelected(MenuItem item) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700361 switch (item.getItemId()) {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700362 case R.id.data_usage_menu_roaming: {
363 final boolean dataRoaming = !item.isChecked();
364 if (dataRoaming) {
365 ConfirmDataRoamingFragment.show(this);
366 } else {
367 // no confirmation to disable roaming
368 setDataRoaming(false);
369 }
370 return true;
371 }
372 case R.id.data_usage_menu_restrict_background: {
373 final boolean restrictBackground = !item.isChecked();
374 if (restrictBackground) {
375 ConfirmRestrictFragment.show(this);
376 } else {
377 // no confirmation to drop restriction
378 setRestrictBackground(false);
379 }
380 return true;
381 }
382 case R.id.data_usage_menu_split_4g: {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700383 final boolean mobileSplit = !item.isChecked();
Jeff Sharkeya662e492011-06-18 21:57:06 -0700384 setMobilePolicySplit(mobileSplit);
385 item.setChecked(isMobilePolicySplit());
Jeff Sharkey8a503642011-06-10 13:31:21 -0700386 updateTabs();
387 return true;
388 }
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700389 case R.id.data_usage_menu_show_wifi: {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700390 mShowWifi = !item.isChecked();
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700391 mPrefs.edit().putBoolean(PREF_SHOW_WIFI, mShowWifi).apply();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700392 item.setChecked(mShowWifi);
393 updateTabs();
394 return true;
395 }
396 }
397 return false;
398 }
399
Jeff Sharkey94a90952011-06-13 22:31:09 -0700400 @Override
401 public void onDestroyView() {
402 super.onDestroyView();
403
404 mDataEnabledView = null;
405 mDisableAtLimitView = null;
406 }
407
Jeff Sharkey8a503642011-06-10 13:31:21 -0700408 /**
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700409 * Listener to setup {@link LayoutTransition} after first layout pass.
410 */
411 private OnGlobalLayoutListener mFirstLayoutListener = new OnGlobalLayoutListener() {
412 /** {@inheritDoc} */
413 public void onGlobalLayout() {
414 mHeader.getViewTreeObserver().removeGlobalOnLayoutListener(mFirstLayoutListener);
415
416 mTabsContainer.setLayoutTransition(new LayoutTransition());
417 mHeader.setLayoutTransition(new LayoutTransition());
418 mNetworkSwitchesContainer.setLayoutTransition(new LayoutTransition());
419
420 final LayoutTransition chartTransition = new LayoutTransition();
421 chartTransition.setStartDelay(LayoutTransition.APPEARING, 0);
422 chartTransition.setStartDelay(LayoutTransition.DISAPPEARING, 0);
423 mChart.setLayoutTransition(chartTransition);
424 }
425 };
426
427 /**
Jeff Sharkeya662e492011-06-18 21:57:06 -0700428 * Rebuild all tabs based on {@link NetworkPolicyEditor} and
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700429 * {@link #mShowWifi}, hiding the tabs entirely when applicable. Selects
430 * first tab, and kicks off a full rebind of body contents.
Jeff Sharkey8a503642011-06-10 13:31:21 -0700431 */
432 private void updateTabs() {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700433 final Context context = getActivity();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700434 mTabHost.clearAllTabs();
435
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700436 final boolean mobileSplit = isMobilePolicySplit();
437 if (mobileSplit && hasMobile4gRadio(context)) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700438 mTabHost.addTab(buildTabSpec(TAB_3G, R.string.data_usage_tab_3g));
439 mTabHost.addTab(buildTabSpec(TAB_4G, R.string.data_usage_tab_4g));
440 }
441
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700442 if (mShowWifi && hasWifiRadio(context) && hasMobileRadio(context)) {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700443 if (!mobileSplit) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700444 mTabHost.addTab(buildTabSpec(TAB_MOBILE, R.string.data_usage_tab_mobile));
445 }
446 mTabHost.addTab(buildTabSpec(TAB_WIFI, R.string.data_usage_tab_wifi));
447 }
448
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700449 final boolean hasTabs = mTabWidget.getTabCount() > 0;
450 mTabWidget.setVisibility(hasTabs ? View.VISIBLE : View.GONE);
451 if (hasTabs) {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700452 if (mIntentTab != null) {
453 // select default tab, which will kick off updateBody()
454 mTabHost.setCurrentTabByTag(mIntentTab);
455 } else {
456 // select first tab, which will kick off updateBody()
457 mTabHost.setCurrentTab(0);
458 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700459 } else {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700460 // no tabs visible; update body manually
Jeff Sharkey8a503642011-06-10 13:31:21 -0700461 updateBody();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700462 }
463 }
464
Jeff Sharkey8a503642011-06-10 13:31:21 -0700465 /**
466 * Factory that provide empty {@link View} to make {@link TabHost} happy.
467 */
468 private TabContentFactory mEmptyTabContent = new TabContentFactory() {
469 /** {@inheritDoc} */
470 public View createTabContent(String tag) {
471 return new View(mTabHost.getContext());
472 }
473 };
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700474
Jeff Sharkey8a503642011-06-10 13:31:21 -0700475 /**
476 * Build {@link TabSpec} with thin indicator, and empty content.
477 */
478 private TabSpec buildTabSpec(String tag, int titleRes) {
479 final LayoutInflater inflater = LayoutInflater.from(mTabWidget.getContext());
480 final View indicator = inflater.inflate(
481 R.layout.tab_indicator_thin_holo, mTabWidget, false);
482 final TextView title = (TextView) indicator.findViewById(android.R.id.title);
483 title.setText(titleRes);
484 return mTabHost.newTabSpec(tag).setIndicator(indicator).setContent(mEmptyTabContent);
485 }
486
487 private OnTabChangeListener mTabListener = new OnTabChangeListener() {
488 /** {@inheritDoc} */
489 public void onTabChanged(String tabId) {
490 // user changed tab; update body
491 updateBody();
492 }
493 };
494
495 /**
496 * Update body content based on current tab. Loads
497 * {@link NetworkStatsHistory} and {@link NetworkPolicy} from system, and
498 * binds them to visible controls.
499 */
500 private void updateBody() {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700501 mBinding = true;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700502
Jeff Sharkeya662e492011-06-18 21:57:06 -0700503 final Context context = getActivity();
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700504 final String tabTag = mTabHost.getCurrentTabTag();
505
506 final String currentTab;
507 if (tabTag != null) {
508 currentTab = tabTag;
509 } else if (hasMobileRadio(context)) {
510 currentTab = TAB_MOBILE;
511 } else if (hasWifiRadio(context)) {
512 currentTab = TAB_WIFI;
513 } else {
514 throw new IllegalStateException("no mobile or wifi radios");
515 }
Jeff Sharkeya662e492011-06-18 21:57:06 -0700516
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700517 final boolean tabChanged = !currentTab.equals(mCurrentTab);
518 mCurrentTab = currentTab;
519
Jeff Sharkey8a503642011-06-10 13:31:21 -0700520 if (LOGD) Log.d(TAG, "updateBody() with currentTab=" + currentTab);
521
522 if (TAB_WIFI.equals(currentTab)) {
523 // wifi doesn't have any controls
524 mDataEnabledView.setVisibility(View.GONE);
525 mDisableAtLimitView.setVisibility(View.GONE);
Jeff Sharkeya662e492011-06-18 21:57:06 -0700526 mTemplate = new NetworkTemplate(MATCH_WIFI, null);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700527
528 } else {
529 // make sure we show for non-wifi
530 mDataEnabledView.setVisibility(View.VISIBLE);
531 mDisableAtLimitView.setVisibility(View.VISIBLE);
532 }
533
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700534 final String subscriberId = getActiveSubscriberId(context);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700535 if (TAB_MOBILE.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700536 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_mobile);
537 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_mobile_limit);
538 mDataEnabled.setChecked(mConnService.getMobileDataEnabled());
Jeff Sharkeya662e492011-06-18 21:57:06 -0700539 mTemplate = new NetworkTemplate(MATCH_MOBILE_ALL, subscriberId);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700540
541 } else if (TAB_3G.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700542 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_3g);
543 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_3g_limit);
544 // TODO: bind mDataEnabled to 3G radio state
Jeff Sharkeya662e492011-06-18 21:57:06 -0700545 mTemplate = new NetworkTemplate(MATCH_MOBILE_3G_LOWER, subscriberId);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700546
547 } else if (TAB_4G.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700548 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_4g);
549 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_4g_limit);
550 // TODO: bind mDataEnabled to 4G radio state
Jeff Sharkeya662e492011-06-18 21:57:06 -0700551 mTemplate = new NetworkTemplate(MATCH_MOBILE_4G, subscriberId);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700552 }
553
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700554 try {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700555 // load stats for current template
Jeff Sharkey8a503642011-06-10 13:31:21 -0700556 mHistory = mStatsService.getHistoryForNetwork(mTemplate);
557 } catch (RemoteException e) {
558 // since we can't do much without policy or history, and we don't
559 // want to leave with half-baked UI, we bail hard.
560 throw new RuntimeException("problem reading network policy or stats", e);
561 }
562
Jeff Sharkey8a503642011-06-10 13:31:21 -0700563 // bind chart to historical stats
Jeff Sharkey8a503642011-06-10 13:31:21 -0700564 mChart.bindNetworkStats(mHistory);
565
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700566 // only update policy when switching tabs
567 updatePolicy(tabChanged);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700568 updateAppDetail();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700569
570 // force scroll to top of body
571 mListView.smoothScrollToPosition(0);
572
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700573 mBinding = false;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700574 }
575
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700576 private boolean isAppDetailMode() {
577 return mUid != UID_NONE;
578 }
579
580 /**
581 * Update UID details panels to match {@link #mUid}, showing or hiding them
582 * depending on {@link #isAppDetailMode()}.
583 */
584 private void updateAppDetail() {
585 if (isAppDetailMode()) {
586 mAppDetail.setVisibility(View.VISIBLE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700587 mCycleAdapter.setChangeVisible(false);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700588 } else {
589 mAppDetail.setVisibility(View.GONE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700590 mCycleAdapter.setChangeVisible(true);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700591
592 // hide detail stats when not in detail mode
593 mChart.bindDetailNetworkStats(null);
594 return;
595 }
596
597 // remove warning/limit sweeps while in detail mode
598 mChart.bindNetworkPolicy(null);
599
600 final PackageManager pm = getActivity().getPackageManager();
601 mAppTitle.setText(pm.getNameForUid(mUid));
602
603 // enable settings button when package provides it
604 // TODO: target torwards entire UID instead of just first package
605 final String[] packageNames = pm.getPackagesForUid(mUid);
606 if (packageNames != null && packageNames.length > 0) {
607 mAppSettingsIntent = new Intent(Intent.ACTION_MANAGE_NETWORK_USAGE);
608 mAppSettingsIntent.setPackage(packageNames[0]);
609 mAppSettingsIntent.addCategory(Intent.CATEGORY_DEFAULT);
610
611 final boolean matchFound = pm.resolveActivity(mAppSettingsIntent, 0) != null;
612 mAppSettings.setEnabled(matchFound);
613
614 } else {
615 mAppSettingsIntent = null;
616 mAppSettings.setEnabled(false);
617 }
618
619 try {
620 // load stats for current uid and template
621 // TODO: read template from extras
622 mDetailHistory = mStatsService.getHistoryForUid(mTemplate, mUid, NetworkStats.TAG_NONE);
623 } catch (RemoteException e) {
624 // since we can't do much without history, and we don't want to
625 // leave with half-baked UI, we bail hard.
626 throw new RuntimeException("problem reading network stats", e);
627 }
628
629 // bind chart to historical stats
630 mChart.bindDetailNetworkStats(mDetailHistory);
631
632 updateDetailData();
633
634 final Context context = getActivity();
635 if (NetworkPolicyManager.isUidValidForPolicy(context, mUid)) {
636 mAppRestrictView.setVisibility(View.VISIBLE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700637 mAppRestrict.setChecked(getAppRestrictBackground());
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700638
639 } else {
640 mAppRestrictView.setVisibility(View.GONE);
641 }
642
643 }
644
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700645 private void setPolicyCycleDay(int cycleDay) {
646 if (LOGD) Log.d(TAG, "setPolicyCycleDay()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700647 mPolicyEditor.setPolicyCycleDay(mTemplate, cycleDay);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700648 updatePolicy(true);
649 }
650
651 private void setPolicyWarningBytes(long warningBytes) {
652 if (LOGD) Log.d(TAG, "setPolicyWarningBytes()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700653 mPolicyEditor.setPolicyWarningBytes(mTemplate, warningBytes);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700654 updatePolicy(false);
655 }
656
657 private void setPolicyLimitBytes(long limitBytes) {
658 if (LOGD) Log.d(TAG, "setPolicyLimitBytes()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700659 mPolicyEditor.setPolicyLimitBytes(mTemplate, limitBytes);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700660 updatePolicy(false);
661 }
662
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700663 private boolean getDataRoaming() {
664 final ContentResolver resolver = getActivity().getContentResolver();
665 return Settings.Secure.getInt(resolver, Settings.Secure.DATA_ROAMING, 0) != 0;
666 }
667
668 private void setDataRoaming(boolean enabled) {
669 // TODO: teach telephony DataConnectionTracker to watch and apply
670 // updates when changed.
671 final ContentResolver resolver = getActivity().getContentResolver();
672 Settings.Secure.putInt(resolver, Settings.Secure.DATA_ROAMING, enabled ? 1 : 0);
673 mMenuDataRoaming.setChecked(enabled);
674 }
675
676 private boolean getRestrictBackground() {
677 return !mConnService.getBackgroundDataSetting();
678 }
679
680 private void setRestrictBackground(boolean restrictBackground) {
681 if (LOGD) Log.d(TAG, "setRestrictBackground()");
682 mConnService.setBackgroundDataSetting(!restrictBackground);
683 mMenuRestrictBackground.setChecked(restrictBackground);
684 }
685
686 private boolean getAppRestrictBackground() {
687 final int uidPolicy;
688 try {
689 uidPolicy = mPolicyService.getUidPolicy(mUid);
690 } catch (RemoteException e) {
691 // since we can't do much without policy, we bail hard.
692 throw new RuntimeException("problem reading network policy", e);
693 }
694
695 return (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
696 }
697
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700698 private void setAppRestrictBackground(boolean restrictBackground) {
699 if (LOGD) Log.d(TAG, "setRestrictBackground()");
700 try {
701 mPolicyService.setUidPolicy(
702 mUid, restrictBackground ? POLICY_REJECT_METERED_BACKGROUND : POLICY_NONE);
703 } catch (RemoteException e) {
704 throw new RuntimeException("unable to save policy", e);
705 }
706
707 mAppRestrict.setChecked(restrictBackground);
708 }
709
Jeff Sharkey8a503642011-06-10 13:31:21 -0700710 /**
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700711 * Update chart sweeps and cycle list to reflect {@link NetworkPolicy} for
712 * current {@link #mTemplate}.
713 */
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700714 private void updatePolicy(boolean refreshCycle) {
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700715 if (isAppDetailMode()) {
716 mNetworkSwitches.setVisibility(View.GONE);
717 // we fall through to update cycle list for detail mode
718 } else {
719 mNetworkSwitches.setVisibility(View.VISIBLE);
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700720
721 // when heading back to summary without cycle refresh, kick details
722 // update to repopulate list.
723 if (!refreshCycle) {
724 updateDetailData();
725 }
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700726 }
727
Jeff Sharkeya662e492011-06-18 21:57:06 -0700728 final NetworkPolicy policy = mPolicyEditor.getPolicy(mTemplate);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700729
730 // reflect policy limit in checkbox
731 mDisableAtLimit.setChecked(policy != null && policy.limitBytes != LIMIT_DISABLED);
732 mChart.bindNetworkPolicy(policy);
733
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700734 if (refreshCycle) {
735 // generate cycle list based on policy and available history
736 updateCycleList(policy);
737 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700738 }
739
740 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -0700741 * Rebuild {@link #mCycleAdapter} based on {@link NetworkPolicy#cycleDay}
742 * and available {@link NetworkStatsHistory} data. Always selects the newest
743 * item, updating the inspection range on {@link #mChart}.
744 */
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700745 private void updateCycleList(NetworkPolicy policy) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700746 mCycleAdapter.clear();
747
748 final Context context = mCycleSpinner.getContext();
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700749 long historyStart = mHistory.getStart();
750 long historyEnd = mHistory.getEnd();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700751
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700752 if (historyStart == Long.MAX_VALUE || historyEnd == Long.MIN_VALUE) {
753 historyStart = System.currentTimeMillis();
754 historyEnd = System.currentTimeMillis();
755 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700756
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700757 boolean hasCycles = false;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700758 if (policy != null) {
759 // find the next cycle boundary
760 long cycleEnd = computeNextCycleBoundary(historyEnd, policy);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700761
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700762 int guardCount = 0;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700763
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700764 // walk backwards, generating all valid cycle ranges
765 while (cycleEnd > historyStart) {
766 final long cycleStart = computeLastCycleBoundary(cycleEnd, policy);
767 Log.d(TAG, "generating cs=" + cycleStart + " to ce=" + cycleEnd + " waiting for hs="
768 + historyStart);
769 mCycleAdapter.add(new CycleItem(context, cycleStart, cycleEnd));
770 cycleEnd = cycleStart;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700771 hasCycles = true;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700772
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700773 // TODO: remove this guard once we have better testing
774 if (guardCount++ > 50) {
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700775 Log.wtf(TAG, "stuck generating ranges for historyStart=" + historyStart
776 + ", historyEnd=" + historyEnd + " and policy=" + policy);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700777 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700778 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700779
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700780 // one last cycle entry to modify policy cycle day
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700781 mCycleAdapter.setChangePossible(true);
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700782 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700783
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700784 if (!hasCycles) {
785 // no valid cycles; show all data
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700786 // TODO: offer simple ranges like "last week" etc
787 mCycleAdapter.add(new CycleItem(context, historyStart, historyEnd));
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700788 mCycleAdapter.setChangePossible(false);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700789 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700790
791 // force pick the current cycle (first item)
792 mCycleSpinner.setSelection(0);
793 mCycleListener.onItemSelected(mCycleSpinner, null, 0, 0);
794 }
795
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700796 private OnCheckedChangeListener mDataEnabledListener = new OnCheckedChangeListener() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700797 /** {@inheritDoc} */
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700798 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
799 if (mBinding) return;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700800
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700801 final boolean dataEnabled = isChecked;
802 mDataEnabled.setChecked(dataEnabled);
803
804 switch (mTemplate.getMatchRule()) {
805 case MATCH_MOBILE_ALL: {
806 mConnService.setMobileDataEnabled(dataEnabled);
807 }
808 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700809 }
810 };
811
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700812 private View.OnClickListener mDisableAtLimitListener = new View.OnClickListener() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700813 /** {@inheritDoc} */
814 public void onClick(View v) {
815 final boolean disableAtLimit = !mDisableAtLimit.isChecked();
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700816 if (disableAtLimit) {
817 // enabling limit; show confirmation dialog which eventually
818 // calls setPolicyLimitBytes() once user confirms.
819 ConfirmLimitFragment.show(DataUsageSummary.this);
820 } else {
821 setPolicyLimitBytes(LIMIT_DISABLED);
822 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700823 }
824 };
825
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700826 private View.OnClickListener mAppRestrictListener = new View.OnClickListener() {
827 /** {@inheritDoc} */
828 public void onClick(View v) {
829 final boolean restrictBackground = !mAppRestrict.isChecked();
830
831 if (restrictBackground) {
832 // enabling restriction; show confirmation dialog which
833 // eventually calls setRestrictBackground() once user confirms.
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700834 ConfirmAppRestrictFragment.show(DataUsageSummary.this);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700835 } else {
836 setAppRestrictBackground(false);
837 }
838 }
839 };
840
841 private OnClickListener mAppSettingsListener = new OnClickListener() {
842 /** {@inheritDoc} */
843 public void onClick(View v) {
844 // TODO: target torwards entire UID instead of just first package
845 startActivity(mAppSettingsIntent);
846 }
847 };
848
Jeff Sharkey8a503642011-06-10 13:31:21 -0700849 private OnItemClickListener mListListener = new OnItemClickListener() {
850 /** {@inheritDoc} */
851 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700852 final AppUsageItem app = (AppUsageItem) parent.getItemAtPosition(position);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700853 AppDetailsFragment.show(DataUsageSummary.this, app.uid);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700854 }
855 };
856
857 private OnItemSelectedListener mCycleListener = new OnItemSelectedListener() {
858 /** {@inheritDoc} */
859 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
860 final CycleItem cycle = (CycleItem) parent.getItemAtPosition(position);
861 if (cycle instanceof CycleChangeItem) {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700862 // show cycle editor; will eventually call setPolicyCycleDay()
863 // when user finishes editing.
864 CycleEditorFragment.show(DataUsageSummary.this);
865
866 // reset spinner to something other than "change cycle..."
867 mCycleSpinner.setSelection(0);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700868
869 } else {
Jeff Sharkey8e911d72011-06-14 22:41:21 -0700870 if (LOGD) {
871 Log.d(TAG, "showing cycle " + cycle + ", start=" + cycle.start + ", end="
872 + cycle.end + "]");
873 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700874
875 // update chart to show selected cycle, and update detail data
876 // to match updated sweep bounds.
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700877 mChart.setVisibleRange(cycle.start, cycle.end, mHistory.getEnd());
Jeff Sharkey8a503642011-06-10 13:31:21 -0700878
879 updateDetailData();
880 }
881 }
882
883 /** {@inheritDoc} */
884 public void onNothingSelected(AdapterView<?> parent) {
885 // ignored
886 }
887 };
888
889 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700890 * Update details based on {@link #mChart} inspection range depending on
891 * current mode. In network mode, updates {@link #mAdapter} with sorted list
892 * of applications data usage, and when {@link #isAppDetailMode()} update
893 * app details.
Jeff Sharkey8a503642011-06-10 13:31:21 -0700894 */
895 private void updateDetailData() {
896 if (LOGD) Log.d(TAG, "updateDetailData()");
897
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700898 final long start = mChart.getInspectStart();
899 final long end = mChart.getInspectEnd();
900
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700901 if (isAppDetailMode()) {
902 if (mDetailHistory != null) {
903 final Context context = mChart.getContext();
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700904 final long now = System.currentTimeMillis();
905 final NetworkStatsHistory.Entry entry = mDetailHistory.getValues(
906 start, end, now, null);
907 final long total = entry.rxBytes + entry.txBytes;
908 mAppSubtitle.setText(Formatter.formatFileSize(context, total));
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700909 }
910
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700911 getLoaderManager().destroyLoader(LOADER_SUMMARY);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700912
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700913 } else {
914 // kick off loader for detailed stats
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700915 getLoaderManager().restartLoader(LOADER_SUMMARY,
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700916 SummaryForAllUidLoader.buildArgs(mTemplate, start, end), mSummaryForAllUid);
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700917
918 }
919 }
920
921 private final LoaderCallbacks<NetworkStats> mSummaryForAllUid = new LoaderCallbacks<
922 NetworkStats>() {
923 /** {@inheritDoc} */
924 public Loader<NetworkStats> onCreateLoader(int id, Bundle args) {
925 return new SummaryForAllUidLoader(getActivity(), mStatsService, args);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700926 }
927
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700928 /** {@inheritDoc} */
929 public void onLoadFinished(Loader<NetworkStats> loader, NetworkStats data) {
930 mAdapter.bindStats(data);
931 }
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -0700932
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700933 /** {@inheritDoc} */
934 public void onLoaderReset(Loader<NetworkStats> loader) {
935 mAdapter.bindStats(null);
936 }
937 };
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700938
Jeff Sharkeya662e492011-06-18 21:57:06 -0700939 private boolean isMobilePolicySplit() {
940 final String subscriberId = getActiveSubscriberId(getActivity());
941 return mPolicyEditor.isMobilePolicySplit(subscriberId);
942 }
943
944 private void setMobilePolicySplit(boolean split) {
945 final String subscriberId = getActiveSubscriberId(getActivity());
946 mPolicyEditor.setMobilePolicySplit(subscriberId, split);
947 }
948
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700949 private static String getActiveSubscriberId(Context context) {
950 final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
951 Context.TELEPHONY_SERVICE);
952 return telephony.getSubscriberId();
953 }
954
Jeff Sharkey8a503642011-06-10 13:31:21 -0700955 private DataUsageChartListener mChartListener = new DataUsageChartListener() {
956 /** {@inheritDoc} */
957 public void onInspectRangeChanged() {
958 if (LOGD) Log.d(TAG, "onInspectRangeChanged()");
959 updateDetailData();
960 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700961
Jeff Sharkey8a503642011-06-10 13:31:21 -0700962 /** {@inheritDoc} */
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700963 public void onWarningChanged() {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700964 setPolicyWarningBytes(mChart.getWarningBytes());
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700965 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700966
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700967 /** {@inheritDoc} */
968 public void onLimitChanged() {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700969 setPolicyLimitBytes(mChart.getLimitBytes());
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700970 }
971 };
972
973
974 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -0700975 * List item that reflects a specific data usage cycle.
976 */
977 public static class CycleItem {
978 public CharSequence label;
979 public long start;
980 public long end;
981
982 private static final StringBuilder sBuilder = new StringBuilder(50);
983 private static final java.util.Formatter sFormatter = new java.util.Formatter(
984 sBuilder, Locale.getDefault());
985
986 CycleItem(CharSequence label) {
987 this.label = label;
988 }
989
990 public CycleItem(Context context, long start, long end) {
991 this.label = formatDateRangeUtc(context, start, end);
992 this.start = start;
993 this.end = end;
994 }
995
996 private static String formatDateRangeUtc(Context context, long start, long end) {
997 synchronized (sBuilder) {
998 sBuilder.setLength(0);
999 return DateUtils.formatDateRange(context, sFormatter, start, end,
1000 DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH,
1001 Time.TIMEZONE_UTC).toString();
1002 }
1003 }
1004
1005 @Override
1006 public String toString() {
1007 return label.toString();
1008 }
1009 }
1010
1011 /**
1012 * Special-case data usage cycle that triggers dialog to change
1013 * {@link NetworkPolicy#cycleDay}.
1014 */
1015 public static class CycleChangeItem extends CycleItem {
1016 public CycleChangeItem(Context context) {
1017 super(context.getString(R.string.data_usage_change_cycle));
1018 }
1019 }
1020
1021 public static class CycleAdapter extends ArrayAdapter<CycleItem> {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001022 private boolean mChangePossible = false;
1023 private boolean mChangeVisible = false;
1024
1025 private final CycleChangeItem mChangeItem;
1026
Jeff Sharkey8a503642011-06-10 13:31:21 -07001027 public CycleAdapter(Context context) {
1028 super(context, android.R.layout.simple_spinner_item);
1029 setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001030 mChangeItem = new CycleChangeItem(context);
1031 }
1032
1033 public void setChangePossible(boolean possible) {
1034 mChangePossible = possible;
1035 updateChange();
1036 }
1037
1038 public void setChangeVisible(boolean visible) {
1039 mChangeVisible = visible;
1040 updateChange();
1041 }
1042
1043 private void updateChange() {
1044 remove(mChangeItem);
1045 if (mChangePossible && mChangeVisible) {
1046 add(mChangeItem);
1047 }
Jeff Sharkey8a503642011-06-10 13:31:21 -07001048 }
1049 }
1050
Jeff Sharkey4dfa6602011-06-13 00:42:03 -07001051 private static class AppUsageItem implements Comparable<AppUsageItem> {
1052 public int uid;
1053 public long total;
1054
1055 /** {@inheritDoc} */
1056 public int compareTo(AppUsageItem another) {
1057 return Long.compare(another.total, total);
1058 }
1059 }
1060
Jeff Sharkey8a503642011-06-10 13:31:21 -07001061 /**
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001062 * Adapter of applications, sorted by total usage descending.
1063 */
1064 public static class DataUsageAdapter extends BaseAdapter {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001065 private ArrayList<AppUsageItem> mItems = Lists.newArrayList();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001066
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001067 /**
1068 * Bind the given {@link NetworkStats}, or {@code null} to clear list.
1069 */
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001070 public void bindStats(NetworkStats stats) {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001071 mItems.clear();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001072
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001073 if (stats != null) {
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001074 final AppUsageItem systemItem = new AppUsageItem();
1075 systemItem.uid = android.os.Process.SYSTEM_UID;
1076
Jeff Sharkeyebae6592011-07-12 13:53:11 -07001077 NetworkStats.Entry entry = null;
1078 for (int i = 0; i < stats.size(); i++) {
1079 entry = stats.getValues(i, entry);
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001080
1081 final boolean isApp = entry.uid >= android.os.Process.FIRST_APPLICATION_UID
1082 && entry.uid <= android.os.Process.LAST_APPLICATION_UID;
1083 if (isApp || entry.uid == TrafficStats.UID_REMOVED) {
1084 final AppUsageItem item = new AppUsageItem();
1085 item.uid = entry.uid;
1086 item.total = entry.rxBytes + entry.txBytes;
1087 mItems.add(item);
1088 } else {
1089 systemItem.total += entry.rxBytes + entry.txBytes;
1090 }
1091 }
1092
1093 if (systemItem.total > 0) {
1094 mItems.add(systemItem);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001095 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001096 }
1097
Jeff Sharkey8a503642011-06-10 13:31:21 -07001098 Collections.sort(mItems);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001099 notifyDataSetChanged();
1100 }
1101
1102 @Override
1103 public int getCount() {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001104 return mItems.size();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001105 }
1106
1107 @Override
1108 public Object getItem(int position) {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001109 return mItems.get(position);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001110 }
1111
1112 @Override
1113 public long getItemId(int position) {
1114 return position;
1115 }
1116
1117 @Override
1118 public View getView(int position, View convertView, ViewGroup parent) {
1119 if (convertView == null) {
1120 convertView = LayoutInflater.from(parent.getContext()).inflate(
Jeff Sharkey52c3f442011-06-23 00:39:38 -07001121 R.layout.data_usage_item, parent, false);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001122 }
1123
1124 final Context context = parent.getContext();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001125
1126 final TextView text1 = (TextView) convertView.findViewById(android.R.id.text1);
1127 final TextView text2 = (TextView) convertView.findViewById(android.R.id.text2);
1128
Jeff Sharkey8a503642011-06-10 13:31:21 -07001129 final AppUsageItem item = mItems.get(position);
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001130 text1.setText(resolveLabelForUid(context, item.uid));
Jeff Sharkey8a503642011-06-10 13:31:21 -07001131 text2.setText(Formatter.formatFileSize(context, item.total));
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001132
1133 return convertView;
1134 }
1135
1136 }
1137
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001138 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001139 * Empty {@link Fragment} that controls display of UID details in
1140 * {@link DataUsageSummary}.
1141 */
1142 public static class AppDetailsFragment extends Fragment {
1143 public static final String EXTRA_UID = "uid";
1144
1145 public static void show(DataUsageSummary parent, int uid) {
1146 final Bundle args = new Bundle();
1147 args.putInt(EXTRA_UID, uid);
1148
1149 final AppDetailsFragment fragment = new AppDetailsFragment();
1150 fragment.setArguments(args);
1151 fragment.setTargetFragment(parent, 0);
1152
1153 final FragmentTransaction ft = parent.getFragmentManager().beginTransaction();
1154 ft.add(fragment, TAG_APP_DETAILS);
1155 ft.addToBackStack(TAG_APP_DETAILS);
1156 ft.commit();
1157 }
1158
1159 @Override
1160 public void onStart() {
1161 super.onStart();
1162 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1163 target.mUid = getArguments().getInt(EXTRA_UID);
1164 target.updateBody();
1165 }
1166
1167 @Override
1168 public void onStop() {
1169 super.onStop();
1170 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1171 target.mUid = UID_NONE;
1172 target.updateBody();
1173 }
1174 }
1175
1176 /**
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001177 * Dialog to request user confirmation before setting
1178 * {@link NetworkPolicy#limitBytes}.
1179 */
1180 public static class ConfirmLimitFragment extends DialogFragment {
1181 public static final String EXTRA_MESSAGE_ID = "messageId";
1182 public static final String EXTRA_LIMIT_BYTES = "limitBytes";
1183
1184 public static void show(DataUsageSummary parent) {
1185 final Bundle args = new Bundle();
1186
1187 // TODO: customize default limits based on network template
Jeff Sharkeya662e492011-06-18 21:57:06 -07001188 switch (parent.mTemplate.getMatchRule()) {
1189 case MATCH_MOBILE_3G_LOWER: {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001190 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_3g);
1191 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
1192 break;
1193 }
Jeff Sharkeya662e492011-06-18 21:57:06 -07001194 case MATCH_MOBILE_4G: {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001195 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_4g);
1196 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
1197 break;
1198 }
Jeff Sharkeya662e492011-06-18 21:57:06 -07001199 case MATCH_MOBILE_ALL: {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001200 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_mobile);
1201 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
1202 break;
1203 }
1204 }
1205
1206 final ConfirmLimitFragment dialog = new ConfirmLimitFragment();
1207 dialog.setArguments(args);
1208 dialog.setTargetFragment(parent, 0);
1209 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_LIMIT);
1210 }
1211
1212 @Override
1213 public Dialog onCreateDialog(Bundle savedInstanceState) {
1214 final Context context = getActivity();
1215
1216 final int messageId = getArguments().getInt(EXTRA_MESSAGE_ID);
1217 final long limitBytes = getArguments().getLong(EXTRA_LIMIT_BYTES);
1218
1219 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1220 builder.setTitle(R.string.data_usage_limit_dialog_title);
1221 builder.setMessage(messageId);
1222
1223 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1224 public void onClick(DialogInterface dialog, int which) {
1225 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1226 if (target != null) {
1227 target.setPolicyLimitBytes(limitBytes);
1228 }
1229 }
1230 });
1231
1232 return builder.create();
1233 }
1234 }
1235
1236 /**
1237 * Dialog to edit {@link NetworkPolicy#cycleDay}.
1238 */
1239 public static class CycleEditorFragment extends DialogFragment {
1240 public static final String EXTRA_CYCLE_DAY = "cycleDay";
1241
1242 public static void show(DataUsageSummary parent) {
Jeff Sharkeya662e492011-06-18 21:57:06 -07001243 final NetworkPolicy policy = parent.mPolicyEditor.getPolicy(parent.mTemplate);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001244 final Bundle args = new Bundle();
1245 args.putInt(CycleEditorFragment.EXTRA_CYCLE_DAY, policy.cycleDay);
1246
1247 final CycleEditorFragment dialog = new CycleEditorFragment();
1248 dialog.setArguments(args);
1249 dialog.setTargetFragment(parent, 0);
1250 dialog.show(parent.getFragmentManager(), TAG_CYCLE_EDITOR);
1251 }
1252
1253 @Override
1254 public Dialog onCreateDialog(Bundle savedInstanceState) {
1255 final Context context = getActivity();
1256
1257 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1258 final LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext());
1259
1260 final View view = dialogInflater.inflate(R.layout.data_usage_cycle_editor, null, false);
1261 final NumberPicker cycleDayPicker = (NumberPicker) view.findViewById(R.id.cycle_day);
1262
1263 final int oldCycleDay = getArguments().getInt(EXTRA_CYCLE_DAY, 1);
1264
1265 cycleDayPicker.setMinValue(1);
1266 cycleDayPicker.setMaxValue(31);
1267 cycleDayPicker.setValue(oldCycleDay);
1268 cycleDayPicker.setWrapSelectorWheel(true);
1269
1270 builder.setTitle(R.string.data_usage_cycle_editor_title);
1271 builder.setView(view);
1272
1273 builder.setPositiveButton(R.string.data_usage_cycle_editor_positive,
1274 new DialogInterface.OnClickListener() {
1275 public void onClick(DialogInterface dialog, int which) {
1276 final int cycleDay = cycleDayPicker.getValue();
1277 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1278 if (target != null) {
1279 target.setPolicyCycleDay(cycleDay);
1280 }
1281 }
1282 });
1283
1284 return builder.create();
1285 }
1286 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001287
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001288 /**
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001289 * Dialog explaining that {@link NetworkPolicy#limitBytes} has been passed,
1290 * and giving the user an option to bypass.
1291 */
1292 public static class PolicyLimitFragment extends DialogFragment {
1293 public static final String EXTRA_TITLE_ID = "titleId";
1294
1295 public static void show(DataUsageSummary parent) {
1296 final Bundle args = new Bundle();
1297
Jeff Sharkeya662e492011-06-18 21:57:06 -07001298 switch (parent.mTemplate.getMatchRule()) {
1299 case MATCH_MOBILE_3G_LOWER: {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001300 args.putInt(EXTRA_TITLE_ID, R.string.data_usage_disabled_dialog_3g_title);
1301 break;
1302 }
Jeff Sharkeya662e492011-06-18 21:57:06 -07001303 case MATCH_MOBILE_4G: {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001304 args.putInt(EXTRA_TITLE_ID, R.string.data_usage_disabled_dialog_4g_title);
1305 break;
1306 }
Jeff Sharkeya662e492011-06-18 21:57:06 -07001307 case MATCH_MOBILE_ALL: {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001308 args.putInt(EXTRA_TITLE_ID, R.string.data_usage_disabled_dialog_mobile_title);
1309 break;
1310 }
1311 }
1312
1313 final PolicyLimitFragment dialog = new PolicyLimitFragment();
1314 dialog.setArguments(args);
1315 dialog.setTargetFragment(parent, 0);
1316 dialog.show(parent.getFragmentManager(), TAG_POLICY_LIMIT);
1317 }
1318
1319 @Override
1320 public Dialog onCreateDialog(Bundle savedInstanceState) {
1321 final Context context = getActivity();
1322
1323 final int titleId = getArguments().getInt(EXTRA_TITLE_ID);
1324
1325 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1326 builder.setTitle(titleId);
1327 builder.setMessage(R.string.data_usage_disabled_dialog);
1328
1329 builder.setPositiveButton(android.R.string.ok, null);
1330 builder.setNegativeButton(R.string.data_usage_disabled_dialog_enable,
1331 new DialogInterface.OnClickListener() {
1332 public void onClick(DialogInterface dialog, int which) {
1333 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1334 if (target != null) {
1335 // TODO: consider "allow 100mb more data", or
1336 // only bypass limit for current cycle.
1337 target.setPolicyLimitBytes(LIMIT_DISABLED);
1338 }
1339 }
1340 });
1341
1342 return builder.create();
1343 }
1344 }
1345
1346 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001347 * Dialog to request user confirmation before setting
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001348 * {@link Settings.Secure#DATA_ROAMING}.
1349 */
1350 public static class ConfirmDataRoamingFragment extends DialogFragment {
1351 public static void show(DataUsageSummary parent) {
1352 final Bundle args = new Bundle();
1353
1354 final ConfirmDataRoamingFragment dialog = new ConfirmDataRoamingFragment();
1355 dialog.setTargetFragment(parent, 0);
1356 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_ROAMING);
1357 }
1358
1359 @Override
1360 public Dialog onCreateDialog(Bundle savedInstanceState) {
1361 final Context context = getActivity();
1362
1363 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1364 builder.setTitle(R.string.roaming_reenable_title);
1365 builder.setMessage(R.string.roaming_warning);
1366
1367 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1368 public void onClick(DialogInterface dialog, int which) {
1369 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1370 if (target != null) {
1371 target.setDataRoaming(true);
1372 }
1373 }
1374 });
1375 builder.setNegativeButton(android.R.string.cancel, null);
1376
1377 return builder.create();
1378 }
1379 }
1380
1381 /**
1382 * Dialog to request user confirmation before setting
1383 * {@link ConnectivityManager#setBackgroundDataSetting(boolean)}.
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001384 */
1385 public static class ConfirmRestrictFragment extends DialogFragment {
1386 public static void show(DataUsageSummary parent) {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001387 final Bundle args = new Bundle();
1388
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001389 final ConfirmRestrictFragment dialog = new ConfirmRestrictFragment();
1390 dialog.setTargetFragment(parent, 0);
1391 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_RESTRICT);
1392 }
1393
1394 @Override
1395 public Dialog onCreateDialog(Bundle savedInstanceState) {
1396 final Context context = getActivity();
1397
1398 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001399 builder.setTitle(R.string.data_usage_restrict_background_title);
1400 builder.setMessage(R.string.data_usage_restrict_background);
1401
1402 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1403 public void onClick(DialogInterface dialog, int which) {
1404 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1405 if (target != null) {
1406 target.setRestrictBackground(true);
1407 }
1408 }
1409 });
1410 builder.setNegativeButton(android.R.string.cancel, null);
1411
1412 return builder.create();
1413 }
1414 }
1415
1416 /**
1417 * Dialog to request user confirmation before setting
1418 * {@link #POLICY_REJECT_METERED_BACKGROUND}.
1419 */
1420 public static class ConfirmAppRestrictFragment extends DialogFragment {
1421 public static void show(DataUsageSummary parent) {
1422 final ConfirmAppRestrictFragment dialog = new ConfirmAppRestrictFragment();
1423 dialog.setTargetFragment(parent, 0);
1424 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_APP_RESTRICT);
1425 }
1426
1427 @Override
1428 public Dialog onCreateDialog(Bundle savedInstanceState) {
1429 final Context context = getActivity();
1430
1431 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001432 builder.setTitle(R.string.data_usage_app_restrict_dialog_title);
1433 builder.setMessage(R.string.data_usage_app_restrict_dialog);
1434
1435 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1436 public void onClick(DialogInterface dialog, int which) {
1437 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1438 if (target != null) {
1439 target.setAppRestrictBackground(true);
1440 }
1441 }
1442 });
1443 builder.setNegativeButton(android.R.string.cancel, null);
1444
1445 return builder.create();
1446 }
1447 }
1448
1449 /**
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001450 * Compute default tab that should be selected, based on
1451 * {@link NetworkPolicyManager#EXTRA_NETWORK_TEMPLATE} extra.
1452 */
1453 private static String computeTabFromIntent(Intent intent) {
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001454 final int networkTemplate = intent.getIntExtra(EXTRA_NETWORK_TEMPLATE, MATCH_MOBILE_ALL);
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001455 switch (networkTemplate) {
Jeff Sharkeya662e492011-06-18 21:57:06 -07001456 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001457 return TAB_3G;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001458 case MATCH_MOBILE_4G:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001459 return TAB_4G;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001460 case MATCH_MOBILE_ALL:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001461 return TAB_MOBILE;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001462 case MATCH_WIFI:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001463 return TAB_WIFI;
1464 default:
1465 return null;
1466 }
1467 }
1468
1469 /**
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001470 * Resolve best descriptive label for the given UID.
1471 */
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001472 public static CharSequence resolveLabelForUid(Context context, int uid) {
1473 final Resources res = context.getResources();
1474 final PackageManager pm = context.getPackageManager();
1475
1476 // handle special case labels
1477 switch (uid) {
1478 case android.os.Process.SYSTEM_UID:
1479 return res.getText(R.string.process_kernel_label);
1480 case TrafficStats.UID_REMOVED:
1481 return res.getText(R.string.data_usage_uninstalled_apps);
1482 }
1483
1484 // otherwise fall back to using packagemanager labels
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001485 final String[] packageNames = pm.getPackagesForUid(uid);
1486 final int length = packageNames != null ? packageNames.length : 0;
1487
1488 CharSequence label = pm.getNameForUid(uid);
1489 try {
1490 if (length == 1) {
1491 final ApplicationInfo info = pm.getApplicationInfo(packageNames[0], 0);
1492 label = info.loadLabel(pm);
1493 } else if (length > 1) {
1494 for (String packageName : packageNames) {
1495 final PackageInfo info = pm.getPackageInfo(packageName, 0);
1496 if (info.sharedUserLabel != 0) {
1497 label = pm.getText(packageName, info.sharedUserLabel, info.applicationInfo);
1498 if (!TextUtils.isEmpty(label)) {
1499 break;
1500 }
1501 }
1502 }
1503 }
1504 } catch (NameNotFoundException e) {
1505 }
1506
1507 if (TextUtils.isEmpty(label)) {
1508 label = Integer.toString(uid);
1509 }
1510 return label;
1511 }
1512
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001513 /**
1514 * Test if device has a mobile data radio.
1515 */
1516 private static boolean hasMobileRadio(Context context) {
1517 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1518 Context.CONNECTIVITY_SERVICE);
1519
1520 // mobile devices should have MOBILE network tracker regardless of
1521 // connection status.
1522 return conn.getNetworkInfo(TYPE_MOBILE) != null;
1523 }
1524
1525 /**
1526 * Test if device has a mobile 4G data radio.
1527 */
1528 private static boolean hasMobile4gRadio(Context context) {
1529 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1530 Context.CONNECTIVITY_SERVICE);
1531 final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
1532 Context.TELEPHONY_SERVICE);
1533
1534 // WiMAX devices should have WiMAX network tracker regardless of
1535 // connection status.
1536 final boolean hasWimax = conn.getNetworkInfo(TYPE_WIMAX) != null;
1537 final boolean hasLte = telephony.getLteOnCdmaMode() == Phone.LTE_ON_CDMA_TRUE;
1538 return hasWimax || hasLte;
1539 }
1540
1541 /**
1542 * Test if device has a Wi-Fi data radio.
1543 */
1544 private static boolean hasWifiRadio(Context context) {
1545 return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI);
1546 }
1547
1548 /**
1549 * Inflate a {@link Preference} style layout, adding the given {@link View}
1550 * widget into {@link android.R.id#widget_frame}.
1551 */
1552 private static View inflatePreference(LayoutInflater inflater, ViewGroup root, View widget) {
1553 final View view = inflater.inflate(R.layout.preference, root, false);
1554 final LinearLayout widgetFrame = (LinearLayout) view.findViewById(
1555 android.R.id.widget_frame);
1556 widgetFrame.addView(widget, new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
1557 return view;
1558 }
1559
1560 /**
1561 * Set {@link android.R.id#title} for a preference view inflated with
Jeff Sharkey52c3f442011-06-23 00:39:38 -07001562 * {@link #inflatePreference(LayoutInflater, ViewGroup, View)}.
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001563 */
1564 private static void setPreferenceTitle(View parent, int resId) {
1565 final TextView title = (TextView) parent.findViewById(android.R.id.title);
1566 title.setText(resId);
1567 }
1568
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001569 /**
1570 * Set {@link android.R.id#summary} for a preference view inflated with
1571 * {@link #inflatePreference(LayoutInflater, ViewGroup, View)}.
1572 */
1573 private static void setPreferenceSummary(View parent, int resId) {
1574 final TextView summary = (TextView) parent.findViewById(android.R.id.summary);
1575 summary.setVisibility(View.VISIBLE);
1576 summary.setText(resId);
1577 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001578}