blob: d87080f4482405d087e0fd4ea929337f4e6ea6f4 [file] [log] [blame]
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settings;
18
Jeff Sharkey9549e9f2011-07-14 20:01:13 -070019import static android.net.ConnectivityManager.TYPE_ETHERNET;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070020import static android.net.ConnectivityManager.TYPE_MOBILE;
21import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -070022import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -070023import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070024import static android.net.NetworkPolicyManager.POLICY_NONE;
25import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkey8a503642011-06-10 13:31:21 -070026import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
27import static android.net.NetworkPolicyManager.computeNextCycleBoundary;
Jeff Sharkeya662e492011-06-18 21:57:06 -070028import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
29import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
30import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
31import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -070032import static android.net.NetworkTemplate.buildTemplateEthernet;
33import static android.net.NetworkTemplate.buildTemplateMobile3gLower;
34import static android.net.NetworkTemplate.buildTemplateMobile4g;
35import static android.net.NetworkTemplate.buildTemplateMobileAll;
36import static android.net.NetworkTemplate.buildTemplateWifi;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070037import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070038
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070039import android.animation.LayoutTransition;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070040import android.app.AlertDialog;
41import android.app.Dialog;
42import android.app.DialogFragment;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070043import android.app.Fragment;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070044import android.app.FragmentTransaction;
Jeff Sharkey398b18f2011-07-10 18:56:30 -070045import android.app.LoaderManager.LoaderCallbacks;
Jeff Sharkey9fab0da2011-07-09 17:52:31 -070046import android.content.ContentResolver;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070047import android.content.Context;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070048import android.content.DialogInterface;
Jeff Sharkey4dfa6602011-06-13 00:42:03 -070049import android.content.Intent;
Jeff Sharkey398b18f2011-07-10 18:56:30 -070050import android.content.Loader;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070051import android.content.SharedPreferences;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070052import android.content.pm.ApplicationInfo;
53import android.content.pm.PackageInfo;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070054import android.content.pm.PackageManager;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070055import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -070056import android.content.res.Resources;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070057import android.net.ConnectivityManager;
Jeff Sharkey8a503642011-06-10 13:31:21 -070058import android.net.INetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070059import android.net.INetworkStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -070060import android.net.NetworkPolicy;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -070061import android.net.NetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070062import android.net.NetworkStats;
63import android.net.NetworkStatsHistory;
Jeff Sharkeya662e492011-06-18 21:57:06 -070064import android.net.NetworkTemplate;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -070065import android.net.TrafficStats;
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -070066import android.os.AsyncTask;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070067import android.os.Bundle;
68import android.os.RemoteException;
69import android.os.ServiceManager;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -070070import android.os.SystemProperties;
Jeff Sharkey8a503642011-06-10 13:31:21 -070071import android.preference.Preference;
Jeff Sharkey9fab0da2011-07-09 17:52:31 -070072import android.provider.Settings;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -070073import android.telephony.TelephonyManager;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070074import android.text.TextUtils;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070075import android.text.format.DateUtils;
76import android.text.format.Formatter;
Jeff Sharkey8a503642011-06-10 13:31:21 -070077import android.text.format.Time;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070078import android.util.Log;
79import android.view.LayoutInflater;
Jeff Sharkey8a503642011-06-10 13:31:21 -070080import android.view.Menu;
81import android.view.MenuInflater;
82import android.view.MenuItem;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070083import android.view.View;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070084import android.view.View.OnClickListener;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070085import android.view.ViewGroup;
Jeff Sharkey2af35fb2011-06-24 17:30:27 -070086import android.view.ViewTreeObserver.OnGlobalLayoutListener;
Jeff Sharkey8a503642011-06-10 13:31:21 -070087import android.widget.AdapterView;
88import android.widget.AdapterView.OnItemClickListener;
89import android.widget.AdapterView.OnItemSelectedListener;
90import android.widget.ArrayAdapter;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070091import android.widget.BaseAdapter;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070092import android.widget.Button;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070093import android.widget.CheckBox;
94import android.widget.CompoundButton;
95import android.widget.CompoundButton.OnCheckedChangeListener;
Jeff Sharkey8a503642011-06-10 13:31:21 -070096import android.widget.LinearLayout;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070097import android.widget.ListView;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070098import android.widget.NumberPicker;
Jeff Sharkey2412b0f2011-07-17 20:31:40 -070099import android.widget.ProgressBar;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700100import android.widget.Spinner;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700101import android.widget.Switch;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700102import android.widget.TabHost;
103import android.widget.TabHost.OnTabChangeListener;
104import android.widget.TabHost.TabContentFactory;
105import android.widget.TabHost.TabSpec;
106import android.widget.TabWidget;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700107import android.widget.TextView;
108
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700109import com.android.internal.telephony.Phone;
Jeff Sharkeya662e492011-06-18 21:57:06 -0700110import com.android.settings.net.NetworkPolicyEditor;
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700111import com.android.settings.net.SummaryForAllUidLoader;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700112import com.android.settings.widget.DataUsageChartView;
113import com.android.settings.widget.DataUsageChartView.DataUsageChartListener;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700114import com.google.android.collect.Lists;
115
116import java.util.ArrayList;
117import java.util.Collections;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700118import java.util.Locale;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700119
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700120import libcore.util.Objects;
121
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700122/**
123 * Panel show data usage history across various networks, including options to
124 * inspect based on usage cycle and control through {@link NetworkPolicy}.
125 */
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700126public class DataUsageSummary extends Fragment {
127 private static final String TAG = "DataUsage";
Jeff Sharkey8a503642011-06-10 13:31:21 -0700128 private static final boolean LOGD = true;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700129
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700130 // TODO: remove this testing code
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700131 private static final boolean TEST_ANIM = false;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700132 private static final boolean TEST_RADIOS = false;
133 private static final String TEST_RADIOS_PROP = "test.radios";
134
Jeff Sharkey8a503642011-06-10 13:31:21 -0700135 private static final String TAB_3G = "3g";
136 private static final String TAB_4G = "4g";
137 private static final String TAB_MOBILE = "mobile";
138 private static final String TAB_WIFI = "wifi";
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700139 private static final String TAB_ETHERNET = "ethernet";
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700140
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700141 private static final String TAG_CONFIRM_ROAMING = "confirmRoaming";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700142 private static final String TAG_CONFIRM_LIMIT = "confirmLimit";
143 private static final String TAG_CYCLE_EDITOR = "cycleEditor";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700144 private static final String TAG_CONFIRM_RESTRICT = "confirmRestrict";
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700145 private static final String TAG_CONFIRM_APP_RESTRICT = "confirmAppRestrict";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700146 private static final String TAG_APP_DETAILS = "appDetails";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700147
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700148 private static final int LOADER_SUMMARY = 2;
149
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700150 private static final long KB_IN_BYTES = 1024;
151 private static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
152 private static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
153
154 private INetworkStatsService mStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700155 private INetworkPolicyManager mPolicyService;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700156 private ConnectivityManager mConnService;
157
158 private static final String PREF_FILE = "data_usage";
159 private static final String PREF_SHOW_WIFI = "show_wifi";
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700160 private static final String PREF_SHOW_ETHERNET = "show_ethernet";
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700161
162 private SharedPreferences mPrefs;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700163
Jeff Sharkey8a503642011-06-10 13:31:21 -0700164 private TabHost mTabHost;
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700165 private ViewGroup mTabsContainer;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700166 private TabWidget mTabWidget;
167 private ListView mListView;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700168 private DataUsageAdapter mAdapter;
169
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700170 private ViewGroup mHeader;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700171
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700172 private ViewGroup mNetworkSwitchesContainer;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700173 private LinearLayout mNetworkSwitches;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700174 private Switch mDataEnabled;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700175 private View mDataEnabledView;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700176 private CheckBox mDisableAtLimit;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700177 private View mDisableAtLimitView;
178
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700179 private View mCycleView;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700180 private Spinner mCycleSpinner;
181 private CycleAdapter mCycleAdapter;
182
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700183 private DataUsageChartView mChart;
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700184 private TextView mUsageSummary;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700185
186 private View mAppDetail;
187 private TextView mAppTitle;
188 private TextView mAppSubtitle;
189 private Button mAppSettings;
190
191 private LinearLayout mAppSwitches;
192 private CheckBox mAppRestrict;
193 private View mAppRestrictView;
194
Jeff Sharkey8a503642011-06-10 13:31:21 -0700195 private boolean mShowWifi = false;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700196 private boolean mShowEthernet = false;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700197
Jeff Sharkeya662e492011-06-18 21:57:06 -0700198 private NetworkTemplate mTemplate = null;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700199
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700200 private static final int UID_NONE = -1;
201 private int mUid = UID_NONE;
202
203 private Intent mAppSettingsIntent;
204
Jeff Sharkeya662e492011-06-18 21:57:06 -0700205 private NetworkPolicyEditor mPolicyEditor;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700206
Jeff Sharkey8a503642011-06-10 13:31:21 -0700207 private NetworkStatsHistory mHistory;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700208 private NetworkStatsHistory mDetailHistory;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700209
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700210 private String mCurrentTab = null;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700211 private String mIntentTab = null;
212
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700213 private MenuItem mMenuDataRoaming;
214 private MenuItem mMenuRestrictBackground;
215
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700216 /** Flag used to ignore listeners during binding. */
217 private boolean mBinding;
218
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700219 @Override
Jeff Sharkey8a503642011-06-10 13:31:21 -0700220 public void onCreate(Bundle savedInstanceState) {
221 super.onCreate(savedInstanceState);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700222
223 mStatsService = INetworkStatsService.Stub.asInterface(
224 ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700225 mPolicyService = INetworkPolicyManager.Stub.asInterface(
226 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700227 mConnService = (ConnectivityManager) getActivity().getSystemService(
228 Context.CONNECTIVITY_SERVICE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700229
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700230 mPrefs = getActivity().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700231
Jeff Sharkeya662e492011-06-18 21:57:06 -0700232 mPolicyEditor = new NetworkPolicyEditor(mPolicyService);
233 mPolicyEditor.read();
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700234
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700235 mShowWifi = mPrefs.getBoolean(PREF_SHOW_WIFI, false);
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700236 mShowEthernet = mPrefs.getBoolean(PREF_SHOW_ETHERNET, false);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700237
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700238 setHasOptionsMenu(true);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700239 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700240
Jeff Sharkey8a503642011-06-10 13:31:21 -0700241 @Override
242 public View onCreateView(LayoutInflater inflater, ViewGroup container,
243 Bundle savedInstanceState) {
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700244
Jeff Sharkey8a503642011-06-10 13:31:21 -0700245 final Context context = inflater.getContext();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700246 final View view = inflater.inflate(R.layout.data_usage_summary, container, false);
247
Jeff Sharkey8a503642011-06-10 13:31:21 -0700248 mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700249 mTabsContainer = (ViewGroup) view.findViewById(R.id.tabs_container);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700250 mTabWidget = (TabWidget) view.findViewById(android.R.id.tabs);
251 mListView = (ListView) view.findViewById(android.R.id.list);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700252
Jeff Sharkey8a503642011-06-10 13:31:21 -0700253 mTabHost.setup();
254 mTabHost.setOnTabChangedListener(mTabListener);
255
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700256 mHeader = (ViewGroup) inflater.inflate(R.layout.data_usage_header, mListView, false);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700257 mListView.addHeaderView(mHeader, null, false);
258
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700259 {
260 // bind network switches
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700261 mNetworkSwitchesContainer = (ViewGroup) mHeader.findViewById(
262 R.id.network_switches_container);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700263 mNetworkSwitches = (LinearLayout) mHeader.findViewById(R.id.network_switches);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700264
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700265 mDataEnabled = new Switch(inflater.getContext());
266 mDataEnabledView = inflatePreference(inflater, mNetworkSwitches, mDataEnabled);
267 mDataEnabled.setOnCheckedChangeListener(mDataEnabledListener);
268 mNetworkSwitches.addView(mDataEnabledView);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700269
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700270 mDisableAtLimit = new CheckBox(inflater.getContext());
271 mDisableAtLimit.setClickable(false);
272 mDisableAtLimitView = inflatePreference(inflater, mNetworkSwitches, mDisableAtLimit);
273 mDisableAtLimitView.setOnClickListener(mDisableAtLimitListener);
274 mNetworkSwitches.addView(mDisableAtLimitView);
275 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700276
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700277 // bind cycle dropdown
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700278 mCycleView = mHeader.findViewById(R.id.cycles);
279 mCycleSpinner = (Spinner) mCycleView.findViewById(R.id.cycles_spinner);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700280 mCycleAdapter = new CycleAdapter(context);
281 mCycleSpinner.setAdapter(mCycleAdapter);
282 mCycleSpinner.setOnItemSelectedListener(mCycleListener);
283
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700284 mChart = (DataUsageChartView) mHeader.findViewById(R.id.chart);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700285 mChart.setListener(mChartListener);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700286
287 {
288 // bind app detail controls
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700289 mAppDetail = mHeader.findViewById(R.id.app_detail);
290 mAppTitle = (TextView) mAppDetail.findViewById(R.id.app_title);
291 mAppSubtitle = (TextView) mAppDetail.findViewById(R.id.app_subtitle);
292 mAppSwitches = (LinearLayout) mAppDetail.findViewById(R.id.app_switches);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700293
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700294 mAppSettings = (Button) mAppDetail.findViewById(R.id.app_settings);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700295 mAppSettings.setOnClickListener(mAppSettingsListener);
296
297 mAppRestrict = new CheckBox(inflater.getContext());
298 mAppRestrict.setClickable(false);
299 mAppRestrictView = inflatePreference(inflater, mAppSwitches, mAppRestrict);
300 setPreferenceTitle(mAppRestrictView, R.string.data_usage_app_restrict_background);
301 setPreferenceSummary(
302 mAppRestrictView, R.string.data_usage_app_restrict_background_summary);
303 mAppRestrictView.setOnClickListener(mAppRestrictListener);
304 mAppSwitches.addView(mAppRestrictView);
305 }
306
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700307 mUsageSummary = (TextView) mHeader.findViewById(R.id.usage_summary);
308
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700309 // only assign layout transitions once first layout is finished
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700310 mListView.getViewTreeObserver().addOnGlobalLayoutListener(mFirstLayoutListener);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700311
312 mAdapter = new DataUsageAdapter();
313 mListView.setOnItemClickListener(mListListener);
314 mListView.setAdapter(mAdapter);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700315
316 return view;
317 }
318
319 @Override
320 public void onResume() {
321 super.onResume();
322
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700323 // pick default tab based on incoming intent
324 final Intent intent = getActivity().getIntent();
325 mIntentTab = computeTabFromIntent(intent);
326
Jeff Sharkey8a503642011-06-10 13:31:21 -0700327 // this kicks off chain reaction which creates tabs, binds the body to
328 // selected network, and binds chart, cycles and detail list.
329 updateTabs();
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700330
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700331 // kick off background task to update stats
332 new AsyncTask<Void, Void, Void>() {
333 @Override
334 protected Void doInBackground(Void... params) {
335 try {
336 mStatsService.forceUpdate();
337 } catch (RemoteException e) {
338 }
339 return null;
340 }
341
342 @Override
343 protected void onPostExecute(Void result) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700344 if (isAdded()) {
345 updateBody();
346 }
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700347 }
348 }.execute();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700349 }
350
Jeff Sharkey8a503642011-06-10 13:31:21 -0700351 @Override
352 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
353 inflater.inflate(R.menu.data_usage, menu);
354 }
355
356 @Override
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700357 public void onPrepareOptionsMenu(Menu menu) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700358 final Context context = getActivity();
359
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700360 mMenuDataRoaming = menu.findItem(R.id.data_usage_menu_roaming);
361 mMenuDataRoaming.setVisible(hasMobileRadio(context));
362 mMenuDataRoaming.setChecked(getDataRoaming());
363
364 mMenuRestrictBackground = menu.findItem(R.id.data_usage_menu_restrict_background);
365 mMenuRestrictBackground.setChecked(getRestrictBackground());
366
367 final MenuItem split4g = menu.findItem(R.id.data_usage_menu_split_4g);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700368 split4g.setVisible(hasMobile4gRadio(context));
Jeff Sharkeya662e492011-06-18 21:57:06 -0700369 split4g.setChecked(isMobilePolicySplit());
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700370
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700371 final MenuItem showWifi = menu.findItem(R.id.data_usage_menu_show_wifi);
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700372 if (hasWifiRadio(context) && hasMobileRadio(context)) {
373 showWifi.setVisible(true);
374 showWifi.setChecked(mShowWifi);
375 } else {
376 showWifi.setVisible(false);
377 mShowWifi = true;
378 }
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700379
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700380 final MenuItem showEthernet = menu.findItem(R.id.data_usage_menu_show_ethernet);
381 if (hasEthernet(context) && hasMobileRadio(context)) {
382 showEthernet.setVisible(true);
383 showEthernet.setChecked(mShowEthernet);
384 } else {
385 showEthernet.setVisible(false);
386 mShowEthernet = true;
387 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700388 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700389
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700390 @Override
391 public boolean onOptionsItemSelected(MenuItem item) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700392 switch (item.getItemId()) {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700393 case R.id.data_usage_menu_roaming: {
394 final boolean dataRoaming = !item.isChecked();
395 if (dataRoaming) {
396 ConfirmDataRoamingFragment.show(this);
397 } else {
398 // no confirmation to disable roaming
399 setDataRoaming(false);
400 }
401 return true;
402 }
403 case R.id.data_usage_menu_restrict_background: {
404 final boolean restrictBackground = !item.isChecked();
405 if (restrictBackground) {
406 ConfirmRestrictFragment.show(this);
407 } else {
408 // no confirmation to drop restriction
409 setRestrictBackground(false);
410 }
411 return true;
412 }
413 case R.id.data_usage_menu_split_4g: {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700414 final boolean mobileSplit = !item.isChecked();
Jeff Sharkeya662e492011-06-18 21:57:06 -0700415 setMobilePolicySplit(mobileSplit);
416 item.setChecked(isMobilePolicySplit());
Jeff Sharkey8a503642011-06-10 13:31:21 -0700417 updateTabs();
418 return true;
419 }
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700420 case R.id.data_usage_menu_show_wifi: {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700421 mShowWifi = !item.isChecked();
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700422 mPrefs.edit().putBoolean(PREF_SHOW_WIFI, mShowWifi).apply();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700423 item.setChecked(mShowWifi);
424 updateTabs();
425 return true;
426 }
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700427 case R.id.data_usage_menu_show_ethernet: {
428 mShowEthernet = !item.isChecked();
429 mPrefs.edit().putBoolean(PREF_SHOW_ETHERNET, mShowEthernet).apply();
430 item.setChecked(mShowEthernet);
431 updateTabs();
432 return true;
433 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700434 }
435 return false;
436 }
437
Jeff Sharkey94a90952011-06-13 22:31:09 -0700438 @Override
439 public void onDestroyView() {
440 super.onDestroyView();
441
442 mDataEnabledView = null;
443 mDisableAtLimitView = null;
444 }
445
Jeff Sharkey8a503642011-06-10 13:31:21 -0700446 /**
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700447 * Listener to setup {@link LayoutTransition} after first layout pass.
448 */
449 private OnGlobalLayoutListener mFirstLayoutListener = new OnGlobalLayoutListener() {
450 /** {@inheritDoc} */
451 public void onGlobalLayout() {
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700452 mListView.getViewTreeObserver().removeGlobalOnLayoutListener(mFirstLayoutListener);
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700453
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700454 mTabsContainer.setLayoutTransition(buildLayoutTransition());
455 mHeader.setLayoutTransition(buildLayoutTransition());
456 mNetworkSwitchesContainer.setLayoutTransition(buildLayoutTransition());
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700457
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700458 final LayoutTransition chartTransition = buildLayoutTransition();
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700459 chartTransition.setStartDelay(LayoutTransition.APPEARING, 0);
460 chartTransition.setStartDelay(LayoutTransition.DISAPPEARING, 0);
461 mChart.setLayoutTransition(chartTransition);
462 }
463 };
464
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700465 private static LayoutTransition buildLayoutTransition() {
466 final LayoutTransition transition = new LayoutTransition();
467 if (TEST_ANIM) {
468 transition.setDuration(1500);
469 }
470 transition.setAnimateParentHierarchy(false);
471 return transition;
472 }
473
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700474 /**
Jeff Sharkeya662e492011-06-18 21:57:06 -0700475 * Rebuild all tabs based on {@link NetworkPolicyEditor} and
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700476 * {@link #mShowWifi}, hiding the tabs entirely when applicable. Selects
477 * first tab, and kicks off a full rebind of body contents.
Jeff Sharkey8a503642011-06-10 13:31:21 -0700478 */
479 private void updateTabs() {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700480 final Context context = getActivity();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700481 mTabHost.clearAllTabs();
482
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700483 final boolean mobileSplit = isMobilePolicySplit();
484 if (mobileSplit && hasMobile4gRadio(context)) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700485 mTabHost.addTab(buildTabSpec(TAB_3G, R.string.data_usage_tab_3g));
486 mTabHost.addTab(buildTabSpec(TAB_4G, R.string.data_usage_tab_4g));
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700487 } else if (hasMobileRadio(context)) {
488 mTabHost.addTab(buildTabSpec(TAB_MOBILE, R.string.data_usage_tab_mobile));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700489 }
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700490 if (mShowWifi && hasWifiRadio(context)) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700491 mTabHost.addTab(buildTabSpec(TAB_WIFI, R.string.data_usage_tab_wifi));
492 }
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700493 if (mShowEthernet && hasEthernet(context)) {
494 mTabHost.addTab(buildTabSpec(TAB_ETHERNET, R.string.data_usage_tab_ethernet));
495 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700496
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700497 final boolean multipleTabs = mTabWidget.getTabCount() > 1;
498 mTabWidget.setVisibility(multipleTabs ? View.VISIBLE : View.GONE);
499 if (mIntentTab != null) {
500 if (Objects.equal(mIntentTab, mTabHost.getCurrentTabTag())) {
501 updateBody();
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700502 } else {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700503 mTabHost.setCurrentTabByTag(mIntentTab);
504 }
505 mIntentTab = null;
506 } else {
507 if (mTabHost.getCurrentTab() == 0) {
508 updateBody();
509 } else {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700510 mTabHost.setCurrentTab(0);
511 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700512 }
513 }
514
Jeff Sharkey8a503642011-06-10 13:31:21 -0700515 /**
516 * Factory that provide empty {@link View} to make {@link TabHost} happy.
517 */
518 private TabContentFactory mEmptyTabContent = new TabContentFactory() {
519 /** {@inheritDoc} */
520 public View createTabContent(String tag) {
521 return new View(mTabHost.getContext());
522 }
523 };
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700524
Jeff Sharkey8a503642011-06-10 13:31:21 -0700525 /**
526 * Build {@link TabSpec} with thin indicator, and empty content.
527 */
528 private TabSpec buildTabSpec(String tag, int titleRes) {
529 final LayoutInflater inflater = LayoutInflater.from(mTabWidget.getContext());
530 final View indicator = inflater.inflate(
531 R.layout.tab_indicator_thin_holo, mTabWidget, false);
532 final TextView title = (TextView) indicator.findViewById(android.R.id.title);
533 title.setText(titleRes);
534 return mTabHost.newTabSpec(tag).setIndicator(indicator).setContent(mEmptyTabContent);
535 }
536
537 private OnTabChangeListener mTabListener = new OnTabChangeListener() {
538 /** {@inheritDoc} */
539 public void onTabChanged(String tabId) {
540 // user changed tab; update body
541 updateBody();
542 }
543 };
544
545 /**
546 * Update body content based on current tab. Loads
547 * {@link NetworkStatsHistory} and {@link NetworkPolicy} from system, and
548 * binds them to visible controls.
549 */
550 private void updateBody() {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700551 mBinding = true;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700552
Jeff Sharkeya662e492011-06-18 21:57:06 -0700553 final Context context = getActivity();
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700554 final String currentTab = mTabHost.getCurrentTabTag();
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700555
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700556 if (currentTab == null) {
557 Log.w(TAG, "no tab selected; hiding body");
558 mListView.setVisibility(View.GONE);
559 return;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700560 } else {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700561 mListView.setVisibility(View.VISIBLE);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700562 }
Jeff Sharkeya662e492011-06-18 21:57:06 -0700563
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700564 final boolean tabChanged = !currentTab.equals(mCurrentTab);
565 mCurrentTab = currentTab;
566
Jeff Sharkey8a503642011-06-10 13:31:21 -0700567 if (LOGD) Log.d(TAG, "updateBody() with currentTab=" + currentTab);
568
569 if (TAB_WIFI.equals(currentTab)) {
570 // wifi doesn't have any controls
571 mDataEnabledView.setVisibility(View.GONE);
572 mDisableAtLimitView.setVisibility(View.GONE);
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700573 mTemplate = buildTemplateWifi();
574
575 } else if (TAB_ETHERNET.equals(currentTab)) {
576 // ethernet doesn't have any controls
577 mDataEnabledView.setVisibility(View.GONE);
578 mDisableAtLimitView.setVisibility(View.GONE);
579 mTemplate = buildTemplateEthernet();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700580
581 } else {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700582 mDataEnabledView.setVisibility(View.VISIBLE);
583 mDisableAtLimitView.setVisibility(View.VISIBLE);
584 }
585
586 if (TAB_MOBILE.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700587 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_mobile);
588 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_mobile_limit);
589 mDataEnabled.setChecked(mConnService.getMobileDataEnabled());
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700590 mTemplate = buildTemplateMobileAll(getActiveSubscriberId(context));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700591
592 } else if (TAB_3G.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700593 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_3g);
594 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_3g_limit);
595 // TODO: bind mDataEnabled to 3G radio state
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700596 mTemplate = buildTemplateMobile3gLower(getActiveSubscriberId(context));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700597
598 } else if (TAB_4G.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700599 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_4g);
600 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_4g_limit);
601 // TODO: bind mDataEnabled to 4G radio state
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700602 mTemplate = buildTemplateMobile4g(getActiveSubscriberId(context));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700603 }
604
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700605 try {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700606 // load stats for current template
Jeff Sharkey8a503642011-06-10 13:31:21 -0700607 mHistory = mStatsService.getHistoryForNetwork(mTemplate);
608 } catch (RemoteException e) {
609 // since we can't do much without policy or history, and we don't
610 // want to leave with half-baked UI, we bail hard.
611 throw new RuntimeException("problem reading network policy or stats", e);
612 }
613
Jeff Sharkey8a503642011-06-10 13:31:21 -0700614 // bind chart to historical stats
Jeff Sharkey8a503642011-06-10 13:31:21 -0700615 mChart.bindNetworkStats(mHistory);
616
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700617 // only update policy when switching tabs
618 updatePolicy(tabChanged);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700619 updateAppDetail();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700620
621 // force scroll to top of body
622 mListView.smoothScrollToPosition(0);
623
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700624 mBinding = false;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700625 }
626
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700627 private boolean isAppDetailMode() {
628 return mUid != UID_NONE;
629 }
630
631 /**
632 * Update UID details panels to match {@link #mUid}, showing or hiding them
633 * depending on {@link #isAppDetailMode()}.
634 */
635 private void updateAppDetail() {
636 if (isAppDetailMode()) {
637 mAppDetail.setVisibility(View.VISIBLE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700638 mCycleAdapter.setChangeVisible(false);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700639 } else {
640 mAppDetail.setVisibility(View.GONE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700641 mCycleAdapter.setChangeVisible(true);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700642
643 // hide detail stats when not in detail mode
644 mChart.bindDetailNetworkStats(null);
645 return;
646 }
647
648 // remove warning/limit sweeps while in detail mode
649 mChart.bindNetworkPolicy(null);
650
651 final PackageManager pm = getActivity().getPackageManager();
652 mAppTitle.setText(pm.getNameForUid(mUid));
653
654 // enable settings button when package provides it
655 // TODO: target torwards entire UID instead of just first package
656 final String[] packageNames = pm.getPackagesForUid(mUid);
657 if (packageNames != null && packageNames.length > 0) {
658 mAppSettingsIntent = new Intent(Intent.ACTION_MANAGE_NETWORK_USAGE);
659 mAppSettingsIntent.setPackage(packageNames[0]);
660 mAppSettingsIntent.addCategory(Intent.CATEGORY_DEFAULT);
661
662 final boolean matchFound = pm.resolveActivity(mAppSettingsIntent, 0) != null;
663 mAppSettings.setEnabled(matchFound);
664
665 } else {
666 mAppSettingsIntent = null;
667 mAppSettings.setEnabled(false);
668 }
669
670 try {
671 // load stats for current uid and template
672 // TODO: read template from extras
673 mDetailHistory = mStatsService.getHistoryForUid(mTemplate, mUid, NetworkStats.TAG_NONE);
674 } catch (RemoteException e) {
675 // since we can't do much without history, and we don't want to
676 // leave with half-baked UI, we bail hard.
677 throw new RuntimeException("problem reading network stats", e);
678 }
679
680 // bind chart to historical stats
681 mChart.bindDetailNetworkStats(mDetailHistory);
682
683 updateDetailData();
684
685 final Context context = getActivity();
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700686 if (NetworkPolicyManager.isUidValidForPolicy(context, mUid) && !getRestrictBackground()) {
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700687 mAppRestrictView.setVisibility(View.VISIBLE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700688 mAppRestrict.setChecked(getAppRestrictBackground());
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700689
690 } else {
691 mAppRestrictView.setVisibility(View.GONE);
692 }
693
694 }
695
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700696 private void setPolicyCycleDay(int cycleDay) {
697 if (LOGD) Log.d(TAG, "setPolicyCycleDay()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700698 mPolicyEditor.setPolicyCycleDay(mTemplate, cycleDay);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700699 updatePolicy(true);
700 }
701
702 private void setPolicyWarningBytes(long warningBytes) {
703 if (LOGD) Log.d(TAG, "setPolicyWarningBytes()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700704 mPolicyEditor.setPolicyWarningBytes(mTemplate, warningBytes);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700705 updatePolicy(false);
706 }
707
708 private void setPolicyLimitBytes(long limitBytes) {
709 if (LOGD) Log.d(TAG, "setPolicyLimitBytes()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700710 mPolicyEditor.setPolicyLimitBytes(mTemplate, limitBytes);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700711 updatePolicy(false);
712 }
713
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700714 private boolean getDataRoaming() {
715 final ContentResolver resolver = getActivity().getContentResolver();
716 return Settings.Secure.getInt(resolver, Settings.Secure.DATA_ROAMING, 0) != 0;
717 }
718
719 private void setDataRoaming(boolean enabled) {
720 // TODO: teach telephony DataConnectionTracker to watch and apply
721 // updates when changed.
722 final ContentResolver resolver = getActivity().getContentResolver();
723 Settings.Secure.putInt(resolver, Settings.Secure.DATA_ROAMING, enabled ? 1 : 0);
724 mMenuDataRoaming.setChecked(enabled);
725 }
726
727 private boolean getRestrictBackground() {
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700728 try {
729 return mPolicyService.getRestrictBackground();
730 } catch (RemoteException e) {
731 Log.w(TAG, "problem talking with policy service: " + e);
732 return false;
733 }
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700734 }
735
736 private void setRestrictBackground(boolean restrictBackground) {
737 if (LOGD) Log.d(TAG, "setRestrictBackground()");
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700738 try {
739 mPolicyService.setRestrictBackground(restrictBackground);
740 mMenuRestrictBackground.setChecked(restrictBackground);
741 } catch (RemoteException e) {
742 Log.w(TAG, "problem talking with policy service: " + e);
743 }
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700744 }
745
746 private boolean getAppRestrictBackground() {
747 final int uidPolicy;
748 try {
749 uidPolicy = mPolicyService.getUidPolicy(mUid);
750 } catch (RemoteException e) {
751 // since we can't do much without policy, we bail hard.
752 throw new RuntimeException("problem reading network policy", e);
753 }
754
755 return (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
756 }
757
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700758 private void setAppRestrictBackground(boolean restrictBackground) {
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700759 if (LOGD) Log.d(TAG, "setAppRestrictBackground()");
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700760 try {
761 mPolicyService.setUidPolicy(
762 mUid, restrictBackground ? POLICY_REJECT_METERED_BACKGROUND : POLICY_NONE);
763 } catch (RemoteException e) {
764 throw new RuntimeException("unable to save policy", e);
765 }
766
767 mAppRestrict.setChecked(restrictBackground);
768 }
769
Jeff Sharkey8a503642011-06-10 13:31:21 -0700770 /**
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700771 * Update chart sweeps and cycle list to reflect {@link NetworkPolicy} for
772 * current {@link #mTemplate}.
773 */
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700774 private void updatePolicy(boolean refreshCycle) {
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700775 if (isAppDetailMode()) {
776 mNetworkSwitches.setVisibility(View.GONE);
777 // we fall through to update cycle list for detail mode
778 } else {
779 mNetworkSwitches.setVisibility(View.VISIBLE);
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700780
781 // when heading back to summary without cycle refresh, kick details
782 // update to repopulate list.
783 if (!refreshCycle) {
784 updateDetailData();
785 }
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700786 }
787
Jeff Sharkeya662e492011-06-18 21:57:06 -0700788 final NetworkPolicy policy = mPolicyEditor.getPolicy(mTemplate);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700789
790 // reflect policy limit in checkbox
791 mDisableAtLimit.setChecked(policy != null && policy.limitBytes != LIMIT_DISABLED);
792 mChart.bindNetworkPolicy(policy);
793
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700794 if (refreshCycle) {
795 // generate cycle list based on policy and available history
796 updateCycleList(policy);
797 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700798 }
799
800 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -0700801 * Rebuild {@link #mCycleAdapter} based on {@link NetworkPolicy#cycleDay}
802 * and available {@link NetworkStatsHistory} data. Always selects the newest
803 * item, updating the inspection range on {@link #mChart}.
804 */
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700805 private void updateCycleList(NetworkPolicy policy) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700806 mCycleAdapter.clear();
807
808 final Context context = mCycleSpinner.getContext();
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700809 long historyStart = mHistory.getStart();
810 long historyEnd = mHistory.getEnd();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700811
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700812 if (historyStart == Long.MAX_VALUE || historyEnd == Long.MIN_VALUE) {
813 historyStart = System.currentTimeMillis();
814 historyEnd = System.currentTimeMillis();
815 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700816
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700817 boolean hasCycles = false;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700818 if (policy != null) {
819 // find the next cycle boundary
820 long cycleEnd = computeNextCycleBoundary(historyEnd, policy);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700821
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700822 int guardCount = 0;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700823
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700824 // walk backwards, generating all valid cycle ranges
825 while (cycleEnd > historyStart) {
826 final long cycleStart = computeLastCycleBoundary(cycleEnd, policy);
827 Log.d(TAG, "generating cs=" + cycleStart + " to ce=" + cycleEnd + " waiting for hs="
828 + historyStart);
829 mCycleAdapter.add(new CycleItem(context, cycleStart, cycleEnd));
830 cycleEnd = cycleStart;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700831 hasCycles = true;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700832
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700833 // TODO: remove this guard once we have better testing
834 if (guardCount++ > 50) {
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700835 Log.wtf(TAG, "stuck generating ranges for historyStart=" + historyStart
836 + ", historyEnd=" + historyEnd + " and policy=" + policy);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700837 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700838 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700839
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700840 // one last cycle entry to modify policy cycle day
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700841 mCycleAdapter.setChangePossible(true);
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700842 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700843
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700844 if (!hasCycles) {
845 // no valid cycles; show all data
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700846 // TODO: offer simple ranges like "last week" etc
847 mCycleAdapter.add(new CycleItem(context, historyStart, historyEnd));
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700848 mCycleAdapter.setChangePossible(false);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700849 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700850
851 // force pick the current cycle (first item)
852 mCycleSpinner.setSelection(0);
853 mCycleListener.onItemSelected(mCycleSpinner, null, 0, 0);
854 }
855
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700856 private OnCheckedChangeListener mDataEnabledListener = new OnCheckedChangeListener() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700857 /** {@inheritDoc} */
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700858 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
859 if (mBinding) return;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700860
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700861 final boolean dataEnabled = isChecked;
862 mDataEnabled.setChecked(dataEnabled);
863
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700864 final String currentTab = mCurrentTab;
865 if (TAB_MOBILE.equals(currentTab)) {
866 mConnService.setMobileDataEnabled(dataEnabled);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700867 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700868 }
869 };
870
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700871 private View.OnClickListener mDisableAtLimitListener = new View.OnClickListener() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700872 /** {@inheritDoc} */
873 public void onClick(View v) {
874 final boolean disableAtLimit = !mDisableAtLimit.isChecked();
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700875 if (disableAtLimit) {
876 // enabling limit; show confirmation dialog which eventually
877 // calls setPolicyLimitBytes() once user confirms.
878 ConfirmLimitFragment.show(DataUsageSummary.this);
879 } else {
880 setPolicyLimitBytes(LIMIT_DISABLED);
881 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700882 }
883 };
884
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700885 private View.OnClickListener mAppRestrictListener = new View.OnClickListener() {
886 /** {@inheritDoc} */
887 public void onClick(View v) {
888 final boolean restrictBackground = !mAppRestrict.isChecked();
889
890 if (restrictBackground) {
891 // enabling restriction; show confirmation dialog which
892 // eventually calls setRestrictBackground() once user confirms.
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700893 ConfirmAppRestrictFragment.show(DataUsageSummary.this);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700894 } else {
895 setAppRestrictBackground(false);
896 }
897 }
898 };
899
900 private OnClickListener mAppSettingsListener = new OnClickListener() {
901 /** {@inheritDoc} */
902 public void onClick(View v) {
903 // TODO: target torwards entire UID instead of just first package
904 startActivity(mAppSettingsIntent);
905 }
906 };
907
Jeff Sharkey8a503642011-06-10 13:31:21 -0700908 private OnItemClickListener mListListener = new OnItemClickListener() {
909 /** {@inheritDoc} */
910 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700911 final AppUsageItem app = (AppUsageItem) parent.getItemAtPosition(position);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700912 AppDetailsFragment.show(DataUsageSummary.this, app.uid);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700913 }
914 };
915
916 private OnItemSelectedListener mCycleListener = new OnItemSelectedListener() {
917 /** {@inheritDoc} */
918 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
919 final CycleItem cycle = (CycleItem) parent.getItemAtPosition(position);
920 if (cycle instanceof CycleChangeItem) {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700921 // show cycle editor; will eventually call setPolicyCycleDay()
922 // when user finishes editing.
923 CycleEditorFragment.show(DataUsageSummary.this);
924
925 // reset spinner to something other than "change cycle..."
926 mCycleSpinner.setSelection(0);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700927
928 } else {
Jeff Sharkey8e911d72011-06-14 22:41:21 -0700929 if (LOGD) {
930 Log.d(TAG, "showing cycle " + cycle + ", start=" + cycle.start + ", end="
931 + cycle.end + "]");
932 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700933
934 // update chart to show selected cycle, and update detail data
935 // to match updated sweep bounds.
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700936 mChart.setVisibleRange(cycle.start, cycle.end);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700937
938 updateDetailData();
939 }
940 }
941
942 /** {@inheritDoc} */
943 public void onNothingSelected(AdapterView<?> parent) {
944 // ignored
945 }
946 };
947
948 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700949 * Update details based on {@link #mChart} inspection range depending on
950 * current mode. In network mode, updates {@link #mAdapter} with sorted list
951 * of applications data usage, and when {@link #isAppDetailMode()} update
952 * app details.
Jeff Sharkey8a503642011-06-10 13:31:21 -0700953 */
954 private void updateDetailData() {
955 if (LOGD) Log.d(TAG, "updateDetailData()");
956
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700957 final long start = mChart.getInspectStart();
958 final long end = mChart.getInspectEnd();
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700959 final long now = System.currentTimeMillis();
960
961 final Context context = getActivity();
962 final NetworkStatsHistory.Entry entry;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700963
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700964 if (isAppDetailMode()) {
965 if (mDetailHistory != null) {
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700966 entry = mDetailHistory.getValues(start, end, now, null);
Jeff Sharkey2412b0f2011-07-17 20:31:40 -0700967
968 mAppSubtitle.setText(
969 getString(R.string.data_usage_received_sent,
970 Formatter.formatFileSize(context, entry.rxBytes),
971 Formatter.formatFileSize(context, entry.txBytes)));
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700972 } else {
973 entry = null;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700974 }
975
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700976 getLoaderManager().destroyLoader(LOADER_SUMMARY);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700977
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700978 } else {
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700979 entry = mHistory.getValues(start, end, now, null);
980
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700981 // kick off loader for detailed stats
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700982 getLoaderManager().restartLoader(LOADER_SUMMARY,
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700983 SummaryForAllUidLoader.buildArgs(mTemplate, start, end), mSummaryForAllUid);
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700984
985 }
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700986
987 final long totalBytes = entry != null ? entry.rxBytes + entry.txBytes : 0;
988 final String totalPhrase = Formatter.formatFileSize(context, totalBytes);
989 final String rangePhrase = formatDateRangeUtc(context, start, end);
990
991 mUsageSummary.setText(
992 getString(R.string.data_usage_total_during_range, totalPhrase, rangePhrase));
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700993 }
994
995 private final LoaderCallbacks<NetworkStats> mSummaryForAllUid = new LoaderCallbacks<
996 NetworkStats>() {
997 /** {@inheritDoc} */
998 public Loader<NetworkStats> onCreateLoader(int id, Bundle args) {
999 return new SummaryForAllUidLoader(getActivity(), mStatsService, args);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001000 }
1001
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001002 /** {@inheritDoc} */
1003 public void onLoadFinished(Loader<NetworkStats> loader, NetworkStats data) {
1004 mAdapter.bindStats(data);
1005 }
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -07001006
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001007 /** {@inheritDoc} */
1008 public void onLoaderReset(Loader<NetworkStats> loader) {
1009 mAdapter.bindStats(null);
1010 }
1011 };
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001012
Jeff Sharkeya662e492011-06-18 21:57:06 -07001013 private boolean isMobilePolicySplit() {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001014 final Context context = getActivity();
1015 if (hasMobileRadio(context)) {
1016 final String subscriberId = getActiveSubscriberId(context);
1017 return mPolicyEditor.isMobilePolicySplit(subscriberId);
1018 } else {
1019 return false;
1020 }
Jeff Sharkeya662e492011-06-18 21:57:06 -07001021 }
1022
1023 private void setMobilePolicySplit(boolean split) {
1024 final String subscriberId = getActiveSubscriberId(getActivity());
1025 mPolicyEditor.setMobilePolicySplit(subscriberId, split);
1026 }
1027
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001028 private static String getActiveSubscriberId(Context context) {
1029 final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
1030 Context.TELEPHONY_SERVICE);
1031 return telephony.getSubscriberId();
1032 }
1033
Jeff Sharkey8a503642011-06-10 13:31:21 -07001034 private DataUsageChartListener mChartListener = new DataUsageChartListener() {
1035 /** {@inheritDoc} */
1036 public void onInspectRangeChanged() {
1037 if (LOGD) Log.d(TAG, "onInspectRangeChanged()");
1038 updateDetailData();
1039 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001040
Jeff Sharkey8a503642011-06-10 13:31:21 -07001041 /** {@inheritDoc} */
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001042 public void onWarningChanged() {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001043 setPolicyWarningBytes(mChart.getWarningBytes());
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001044 }
Jeff Sharkey8a503642011-06-10 13:31:21 -07001045
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001046 /** {@inheritDoc} */
1047 public void onLimitChanged() {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001048 setPolicyLimitBytes(mChart.getLimitBytes());
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001049 }
1050 };
1051
1052
1053 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -07001054 * List item that reflects a specific data usage cycle.
1055 */
1056 public static class CycleItem {
1057 public CharSequence label;
1058 public long start;
1059 public long end;
1060
Jeff Sharkey8a503642011-06-10 13:31:21 -07001061 CycleItem(CharSequence label) {
1062 this.label = label;
1063 }
1064
1065 public CycleItem(Context context, long start, long end) {
1066 this.label = formatDateRangeUtc(context, start, end);
1067 this.start = start;
1068 this.end = end;
1069 }
1070
Jeff Sharkey8a503642011-06-10 13:31:21 -07001071 @Override
1072 public String toString() {
1073 return label.toString();
1074 }
1075 }
1076
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001077 private static final StringBuilder sBuilder = new StringBuilder(50);
1078 private static final java.util.Formatter sFormatter = new java.util.Formatter(
1079 sBuilder, Locale.getDefault());
1080
1081 private static String formatDateRangeUtc(Context context, long start, long end) {
1082 synchronized (sBuilder) {
1083 int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH;
1084 if (Time.getJulianDay(start, 0) == Time.getJulianDay(end, 0)) {
1085 // when times are on same day, include time detail
1086 flags |= DateUtils.FORMAT_SHOW_TIME;
1087 }
1088
1089 sBuilder.setLength(0);
1090 return DateUtils.formatDateRange(
1091 context, sFormatter, start, end, flags, Time.TIMEZONE_UTC).toString();
1092 }
1093 }
1094
Jeff Sharkey8a503642011-06-10 13:31:21 -07001095 /**
1096 * Special-case data usage cycle that triggers dialog to change
1097 * {@link NetworkPolicy#cycleDay}.
1098 */
1099 public static class CycleChangeItem extends CycleItem {
1100 public CycleChangeItem(Context context) {
1101 super(context.getString(R.string.data_usage_change_cycle));
1102 }
1103 }
1104
1105 public static class CycleAdapter extends ArrayAdapter<CycleItem> {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001106 private boolean mChangePossible = false;
1107 private boolean mChangeVisible = false;
1108
1109 private final CycleChangeItem mChangeItem;
1110
Jeff Sharkey8a503642011-06-10 13:31:21 -07001111 public CycleAdapter(Context context) {
1112 super(context, android.R.layout.simple_spinner_item);
1113 setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001114 mChangeItem = new CycleChangeItem(context);
1115 }
1116
1117 public void setChangePossible(boolean possible) {
1118 mChangePossible = possible;
1119 updateChange();
1120 }
1121
1122 public void setChangeVisible(boolean visible) {
1123 mChangeVisible = visible;
1124 updateChange();
1125 }
1126
1127 private void updateChange() {
1128 remove(mChangeItem);
1129 if (mChangePossible && mChangeVisible) {
1130 add(mChangeItem);
1131 }
Jeff Sharkey8a503642011-06-10 13:31:21 -07001132 }
1133 }
1134
Jeff Sharkey4dfa6602011-06-13 00:42:03 -07001135 private static class AppUsageItem implements Comparable<AppUsageItem> {
1136 public int uid;
1137 public long total;
1138
1139 /** {@inheritDoc} */
1140 public int compareTo(AppUsageItem another) {
1141 return Long.compare(another.total, total);
1142 }
1143 }
1144
Jeff Sharkey8a503642011-06-10 13:31:21 -07001145 /**
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001146 * Adapter of applications, sorted by total usage descending.
1147 */
1148 public static class DataUsageAdapter extends BaseAdapter {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001149 private ArrayList<AppUsageItem> mItems = Lists.newArrayList();
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001150 private long mLargest;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001151
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001152 /**
1153 * Bind the given {@link NetworkStats}, or {@code null} to clear list.
1154 */
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001155 public void bindStats(NetworkStats stats) {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001156 mItems.clear();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001157
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001158 if (stats != null) {
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001159 final AppUsageItem systemItem = new AppUsageItem();
1160 systemItem.uid = android.os.Process.SYSTEM_UID;
1161
Jeff Sharkeyebae6592011-07-12 13:53:11 -07001162 NetworkStats.Entry entry = null;
1163 for (int i = 0; i < stats.size(); i++) {
1164 entry = stats.getValues(i, entry);
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001165
1166 final boolean isApp = entry.uid >= android.os.Process.FIRST_APPLICATION_UID
1167 && entry.uid <= android.os.Process.LAST_APPLICATION_UID;
1168 if (isApp || entry.uid == TrafficStats.UID_REMOVED) {
1169 final AppUsageItem item = new AppUsageItem();
1170 item.uid = entry.uid;
1171 item.total = entry.rxBytes + entry.txBytes;
1172 mItems.add(item);
1173 } else {
1174 systemItem.total += entry.rxBytes + entry.txBytes;
1175 }
1176 }
1177
1178 if (systemItem.total > 0) {
1179 mItems.add(systemItem);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001180 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001181 }
1182
Jeff Sharkey8a503642011-06-10 13:31:21 -07001183 Collections.sort(mItems);
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001184 mLargest = (mItems.size() > 0) ? mItems.get(0).total : 0;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001185 notifyDataSetChanged();
1186 }
1187
1188 @Override
1189 public int getCount() {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001190 return mItems.size();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001191 }
1192
1193 @Override
1194 public Object getItem(int position) {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001195 return mItems.get(position);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001196 }
1197
1198 @Override
1199 public long getItemId(int position) {
1200 return position;
1201 }
1202
1203 @Override
1204 public View getView(int position, View convertView, ViewGroup parent) {
1205 if (convertView == null) {
1206 convertView = LayoutInflater.from(parent.getContext()).inflate(
Jeff Sharkey52c3f442011-06-23 00:39:38 -07001207 R.layout.data_usage_item, parent, false);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001208 }
1209
1210 final Context context = parent.getContext();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001211
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001212 final TextView title = (TextView) convertView.findViewById(android.R.id.title);
1213 final TextView summary = (TextView) convertView.findViewById(android.R.id.summary);
1214 final ProgressBar progress = (ProgressBar) convertView.findViewById(
1215 android.R.id.progress);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001216
Jeff Sharkey8a503642011-06-10 13:31:21 -07001217 final AppUsageItem item = mItems.get(position);
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001218 title.setText(resolveLabelForUid(context, item.uid));
1219 summary.setText(Formatter.formatFileSize(context, item.total));
1220
1221 final int percentTotal = mLargest != 0 ? (int) (item.total * 100 / mLargest) : 0;
1222 progress.setProgress(percentTotal);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001223
1224 return convertView;
1225 }
1226
1227 }
1228
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001229 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001230 * Empty {@link Fragment} that controls display of UID details in
1231 * {@link DataUsageSummary}.
1232 */
1233 public static class AppDetailsFragment extends Fragment {
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001234 private static final String EXTRA_UID = "uid";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001235
1236 public static void show(DataUsageSummary parent, int uid) {
1237 final Bundle args = new Bundle();
1238 args.putInt(EXTRA_UID, uid);
1239
1240 final AppDetailsFragment fragment = new AppDetailsFragment();
1241 fragment.setArguments(args);
1242 fragment.setTargetFragment(parent, 0);
1243
1244 final FragmentTransaction ft = parent.getFragmentManager().beginTransaction();
1245 ft.add(fragment, TAG_APP_DETAILS);
1246 ft.addToBackStack(TAG_APP_DETAILS);
1247 ft.commit();
1248 }
1249
1250 @Override
1251 public void onStart() {
1252 super.onStart();
1253 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1254 target.mUid = getArguments().getInt(EXTRA_UID);
1255 target.updateBody();
1256 }
1257
1258 @Override
1259 public void onStop() {
1260 super.onStop();
1261 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1262 target.mUid = UID_NONE;
1263 target.updateBody();
1264 }
1265 }
1266
1267 /**
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001268 * Dialog to request user confirmation before setting
1269 * {@link NetworkPolicy#limitBytes}.
1270 */
1271 public static class ConfirmLimitFragment extends DialogFragment {
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001272 private static final String EXTRA_MESSAGE_ID = "messageId";
1273 private static final String EXTRA_LIMIT_BYTES = "limitBytes";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001274
1275 public static void show(DataUsageSummary parent) {
1276 final Bundle args = new Bundle();
1277
1278 // TODO: customize default limits based on network template
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001279 final String currentTab = parent.mCurrentTab;
1280 if (TAB_3G.equals(currentTab)) {
1281 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_3g);
1282 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
1283 } else if (TAB_4G.equals(currentTab)) {
1284 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_4g);
1285 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
1286 } else if (TAB_MOBILE.equals(currentTab)) {
1287 args.putInt(EXTRA_MESSAGE_ID, R.string.data_usage_limit_dialog_mobile);
1288 args.putLong(EXTRA_LIMIT_BYTES, 5 * GB_IN_BYTES);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001289 }
1290
1291 final ConfirmLimitFragment dialog = new ConfirmLimitFragment();
1292 dialog.setArguments(args);
1293 dialog.setTargetFragment(parent, 0);
1294 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_LIMIT);
1295 }
1296
1297 @Override
1298 public Dialog onCreateDialog(Bundle savedInstanceState) {
1299 final Context context = getActivity();
1300
1301 final int messageId = getArguments().getInt(EXTRA_MESSAGE_ID);
1302 final long limitBytes = getArguments().getLong(EXTRA_LIMIT_BYTES);
1303
1304 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1305 builder.setTitle(R.string.data_usage_limit_dialog_title);
1306 builder.setMessage(messageId);
1307
1308 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1309 public void onClick(DialogInterface dialog, int which) {
1310 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1311 if (target != null) {
1312 target.setPolicyLimitBytes(limitBytes);
1313 }
1314 }
1315 });
1316
1317 return builder.create();
1318 }
1319 }
1320
1321 /**
1322 * Dialog to edit {@link NetworkPolicy#cycleDay}.
1323 */
1324 public static class CycleEditorFragment extends DialogFragment {
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001325 private static final String EXTRA_CYCLE_DAY = "cycleDay";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001326
1327 public static void show(DataUsageSummary parent) {
Jeff Sharkeya662e492011-06-18 21:57:06 -07001328 final NetworkPolicy policy = parent.mPolicyEditor.getPolicy(parent.mTemplate);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001329 final Bundle args = new Bundle();
1330 args.putInt(CycleEditorFragment.EXTRA_CYCLE_DAY, policy.cycleDay);
1331
1332 final CycleEditorFragment dialog = new CycleEditorFragment();
1333 dialog.setArguments(args);
1334 dialog.setTargetFragment(parent, 0);
1335 dialog.show(parent.getFragmentManager(), TAG_CYCLE_EDITOR);
1336 }
1337
1338 @Override
1339 public Dialog onCreateDialog(Bundle savedInstanceState) {
1340 final Context context = getActivity();
1341
1342 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1343 final LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext());
1344
1345 final View view = dialogInflater.inflate(R.layout.data_usage_cycle_editor, null, false);
1346 final NumberPicker cycleDayPicker = (NumberPicker) view.findViewById(R.id.cycle_day);
1347
1348 final int oldCycleDay = getArguments().getInt(EXTRA_CYCLE_DAY, 1);
1349
1350 cycleDayPicker.setMinValue(1);
1351 cycleDayPicker.setMaxValue(31);
1352 cycleDayPicker.setValue(oldCycleDay);
1353 cycleDayPicker.setWrapSelectorWheel(true);
1354
1355 builder.setTitle(R.string.data_usage_cycle_editor_title);
1356 builder.setView(view);
1357
1358 builder.setPositiveButton(R.string.data_usage_cycle_editor_positive,
1359 new DialogInterface.OnClickListener() {
1360 public void onClick(DialogInterface dialog, int which) {
1361 final int cycleDay = cycleDayPicker.getValue();
1362 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1363 if (target != null) {
1364 target.setPolicyCycleDay(cycleDay);
1365 }
1366 }
1367 });
1368
1369 return builder.create();
1370 }
1371 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001372
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001373 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001374 * Dialog to request user confirmation before setting
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001375 * {@link Settings.Secure#DATA_ROAMING}.
1376 */
1377 public static class ConfirmDataRoamingFragment extends DialogFragment {
1378 public static void show(DataUsageSummary parent) {
1379 final Bundle args = new Bundle();
1380
1381 final ConfirmDataRoamingFragment dialog = new ConfirmDataRoamingFragment();
1382 dialog.setTargetFragment(parent, 0);
1383 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_ROAMING);
1384 }
1385
1386 @Override
1387 public Dialog onCreateDialog(Bundle savedInstanceState) {
1388 final Context context = getActivity();
1389
1390 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1391 builder.setTitle(R.string.roaming_reenable_title);
1392 builder.setMessage(R.string.roaming_warning);
1393
1394 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1395 public void onClick(DialogInterface dialog, int which) {
1396 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1397 if (target != null) {
1398 target.setDataRoaming(true);
1399 }
1400 }
1401 });
1402 builder.setNegativeButton(android.R.string.cancel, null);
1403
1404 return builder.create();
1405 }
1406 }
1407
1408 /**
1409 * Dialog to request user confirmation before setting
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001410 * {@link INetworkPolicyManager#setRestrictBackground(boolean)}.
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001411 */
1412 public static class ConfirmRestrictFragment extends DialogFragment {
1413 public static void show(DataUsageSummary parent) {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001414 final Bundle args = new Bundle();
1415
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001416 final ConfirmRestrictFragment dialog = new ConfirmRestrictFragment();
1417 dialog.setTargetFragment(parent, 0);
1418 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_RESTRICT);
1419 }
1420
1421 @Override
1422 public Dialog onCreateDialog(Bundle savedInstanceState) {
1423 final Context context = getActivity();
1424
1425 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001426 builder.setTitle(R.string.data_usage_restrict_background_title);
1427 builder.setMessage(R.string.data_usage_restrict_background);
1428
1429 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1430 public void onClick(DialogInterface dialog, int which) {
1431 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1432 if (target != null) {
1433 target.setRestrictBackground(true);
1434 }
1435 }
1436 });
1437 builder.setNegativeButton(android.R.string.cancel, null);
1438
1439 return builder.create();
1440 }
1441 }
1442
1443 /**
1444 * Dialog to request user confirmation before setting
1445 * {@link #POLICY_REJECT_METERED_BACKGROUND}.
1446 */
1447 public static class ConfirmAppRestrictFragment extends DialogFragment {
1448 public static void show(DataUsageSummary parent) {
1449 final ConfirmAppRestrictFragment dialog = new ConfirmAppRestrictFragment();
1450 dialog.setTargetFragment(parent, 0);
1451 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_APP_RESTRICT);
1452 }
1453
1454 @Override
1455 public Dialog onCreateDialog(Bundle savedInstanceState) {
1456 final Context context = getActivity();
1457
1458 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001459 builder.setTitle(R.string.data_usage_app_restrict_dialog_title);
1460 builder.setMessage(R.string.data_usage_app_restrict_dialog);
1461
1462 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1463 public void onClick(DialogInterface dialog, int which) {
1464 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1465 if (target != null) {
1466 target.setAppRestrictBackground(true);
1467 }
1468 }
1469 });
1470 builder.setNegativeButton(android.R.string.cancel, null);
1471
1472 return builder.create();
1473 }
1474 }
1475
1476 /**
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001477 * Compute default tab that should be selected, based on
1478 * {@link NetworkPolicyManager#EXTRA_NETWORK_TEMPLATE} extra.
1479 */
1480 private static String computeTabFromIntent(Intent intent) {
Jeff Sharkey271ec8a2011-07-20 16:59:16 -07001481 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
1482 if (template == null) return null;
1483
1484 switch (template.getMatchRule()) {
Jeff Sharkeya662e492011-06-18 21:57:06 -07001485 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001486 return TAB_3G;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001487 case MATCH_MOBILE_4G:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001488 return TAB_4G;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001489 case MATCH_MOBILE_ALL:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001490 return TAB_MOBILE;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001491 case MATCH_WIFI:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001492 return TAB_WIFI;
1493 default:
1494 return null;
1495 }
1496 }
1497
1498 /**
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001499 * Resolve best descriptive label for the given UID.
1500 */
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001501 public static CharSequence resolveLabelForUid(Context context, int uid) {
1502 final Resources res = context.getResources();
1503 final PackageManager pm = context.getPackageManager();
1504
1505 // handle special case labels
1506 switch (uid) {
1507 case android.os.Process.SYSTEM_UID:
1508 return res.getText(R.string.process_kernel_label);
1509 case TrafficStats.UID_REMOVED:
1510 return res.getText(R.string.data_usage_uninstalled_apps);
1511 }
1512
1513 // otherwise fall back to using packagemanager labels
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001514 final String[] packageNames = pm.getPackagesForUid(uid);
1515 final int length = packageNames != null ? packageNames.length : 0;
1516
1517 CharSequence label = pm.getNameForUid(uid);
1518 try {
1519 if (length == 1) {
1520 final ApplicationInfo info = pm.getApplicationInfo(packageNames[0], 0);
1521 label = info.loadLabel(pm);
1522 } else if (length > 1) {
1523 for (String packageName : packageNames) {
1524 final PackageInfo info = pm.getPackageInfo(packageName, 0);
1525 if (info.sharedUserLabel != 0) {
1526 label = pm.getText(packageName, info.sharedUserLabel, info.applicationInfo);
1527 if (!TextUtils.isEmpty(label)) {
1528 break;
1529 }
1530 }
1531 }
1532 }
1533 } catch (NameNotFoundException e) {
1534 }
1535
1536 if (TextUtils.isEmpty(label)) {
1537 label = Integer.toString(uid);
1538 }
1539 return label;
1540 }
1541
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001542 /**
1543 * Test if device has a mobile data radio.
1544 */
1545 private static boolean hasMobileRadio(Context context) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001546 if (TEST_RADIOS) {
1547 return SystemProperties.get(TEST_RADIOS_PROP).contains("mobile");
1548 }
1549
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001550 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1551 Context.CONNECTIVITY_SERVICE);
1552
1553 // mobile devices should have MOBILE network tracker regardless of
1554 // connection status.
1555 return conn.getNetworkInfo(TYPE_MOBILE) != null;
1556 }
1557
1558 /**
1559 * Test if device has a mobile 4G data radio.
1560 */
1561 private static boolean hasMobile4gRadio(Context context) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001562 if (TEST_RADIOS) {
1563 return SystemProperties.get(TEST_RADIOS_PROP).contains("4g");
1564 }
1565
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001566 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1567 Context.CONNECTIVITY_SERVICE);
1568 final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
1569 Context.TELEPHONY_SERVICE);
1570
1571 // WiMAX devices should have WiMAX network tracker regardless of
1572 // connection status.
1573 final boolean hasWimax = conn.getNetworkInfo(TYPE_WIMAX) != null;
1574 final boolean hasLte = telephony.getLteOnCdmaMode() == Phone.LTE_ON_CDMA_TRUE;
1575 return hasWimax || hasLte;
1576 }
1577
1578 /**
1579 * Test if device has a Wi-Fi data radio.
1580 */
1581 private static boolean hasWifiRadio(Context context) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001582 if (TEST_RADIOS) {
1583 return SystemProperties.get(TEST_RADIOS_PROP).contains("wifi");
1584 }
1585
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001586 return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI);
1587 }
1588
1589 /**
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001590 * Test if device has an ethernet network connection.
1591 */
1592 private static boolean hasEthernet(Context context) {
1593 if (TEST_RADIOS) {
1594 return SystemProperties.get(TEST_RADIOS_PROP).contains("ethernet");
1595 }
1596
1597 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1598 Context.CONNECTIVITY_SERVICE);
1599 return conn.getNetworkInfo(TYPE_ETHERNET) != null;
1600 }
1601
1602 /**
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001603 * Inflate a {@link Preference} style layout, adding the given {@link View}
1604 * widget into {@link android.R.id#widget_frame}.
1605 */
1606 private static View inflatePreference(LayoutInflater inflater, ViewGroup root, View widget) {
1607 final View view = inflater.inflate(R.layout.preference, root, false);
1608 final LinearLayout widgetFrame = (LinearLayout) view.findViewById(
1609 android.R.id.widget_frame);
1610 widgetFrame.addView(widget, new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
1611 return view;
1612 }
1613
1614 /**
1615 * Set {@link android.R.id#title} for a preference view inflated with
Jeff Sharkey52c3f442011-06-23 00:39:38 -07001616 * {@link #inflatePreference(LayoutInflater, ViewGroup, View)}.
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001617 */
1618 private static void setPreferenceTitle(View parent, int resId) {
1619 final TextView title = (TextView) parent.findViewById(android.R.id.title);
1620 title.setText(resId);
1621 }
1622
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001623 /**
1624 * Set {@link android.R.id#summary} for a preference view inflated with
1625 * {@link #inflatePreference(LayoutInflater, ViewGroup, View)}.
1626 */
1627 private static void setPreferenceSummary(View parent, int resId) {
1628 final TextView summary = (TextView) parent.findViewById(android.R.id.summary);
1629 summary.setVisibility(View.VISIBLE);
1630 summary.setText(resId);
1631 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001632}