blob: a6170c744ea4051c40341708218c6fe2d617cf7a [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 Sharkey54d0af52011-08-11 18:26:57 -070028import static android.net.NetworkStats.SET_DEFAULT;
29import static android.net.NetworkStats.SET_FOREGROUND;
Jeff Sharkey1ae43f92011-08-03 17:16:09 -070030import static android.net.NetworkStats.TAG_NONE;
31import static android.net.NetworkStatsHistory.FIELD_RX_BYTES;
32import static android.net.NetworkStatsHistory.FIELD_TX_BYTES;
Jeff Sharkeya662e492011-06-18 21:57:06 -070033import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
34import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
35import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
36import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -070037import static android.net.NetworkTemplate.buildTemplateEthernet;
38import static android.net.NetworkTemplate.buildTemplateMobile3gLower;
39import static android.net.NetworkTemplate.buildTemplateMobile4g;
40import static android.net.NetworkTemplate.buildTemplateMobileAll;
41import static android.net.NetworkTemplate.buildTemplateWifi;
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -070042import static android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
43import static android.text.format.DateUtils.FORMAT_SHOW_DATE;
44import static android.text.format.Time.TIMEZONE_UTC;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070045import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070046import static com.android.settings.Utils.prepareCustomPreferencesList;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070047
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070048import android.animation.LayoutTransition;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070049import android.app.AlertDialog;
50import android.app.Dialog;
51import android.app.DialogFragment;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070052import android.app.Fragment;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070053import android.app.FragmentTransaction;
Jeff Sharkey398b18f2011-07-10 18:56:30 -070054import android.app.LoaderManager.LoaderCallbacks;
Jeff Sharkey9fab0da2011-07-09 17:52:31 -070055import android.content.ContentResolver;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070056import android.content.Context;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -070057import android.content.DialogInterface;
Jeff Sharkey4dfa6602011-06-13 00:42:03 -070058import android.content.Intent;
Jeff Sharkey398b18f2011-07-10 18:56:30 -070059import android.content.Loader;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070060import android.content.SharedPreferences;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070061import android.content.pm.ApplicationInfo;
62import android.content.pm.PackageInfo;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070063import android.content.pm.PackageManager;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070064import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -070065import android.content.res.Resources;
Jeff Sharkey54d0af52011-08-11 18:26:57 -070066import android.graphics.Color;
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -070067import android.graphics.drawable.Drawable;
Jeff Sharkey29d56b32011-06-20 17:06:52 -070068import android.net.ConnectivityManager;
Jeff Sharkey8a503642011-06-10 13:31:21 -070069import android.net.INetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070070import android.net.INetworkStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -070071import android.net.NetworkPolicy;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -070072import android.net.NetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070073import android.net.NetworkStats;
74import android.net.NetworkStatsHistory;
Jeff Sharkeya662e492011-06-18 21:57:06 -070075import android.net.NetworkTemplate;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -070076import android.net.TrafficStats;
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -070077import android.os.AsyncTask;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070078import android.os.Bundle;
Jeff Sharkey1ae43f92011-08-03 17:16:09 -070079import android.os.INetworkManagementService;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070080import android.os.RemoteException;
81import android.os.ServiceManager;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -070082import android.os.SystemProperties;
Jeff Sharkey8a503642011-06-10 13:31:21 -070083import android.preference.Preference;
Jeff Sharkey9fab0da2011-07-09 17:52:31 -070084import android.provider.Settings;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -070085import android.telephony.TelephonyManager;
Jeff Sharkey8e911d72011-06-14 22:41:21 -070086import android.text.TextUtils;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070087import android.text.format.DateUtils;
88import android.text.format.Formatter;
89import android.util.Log;
Jeff Sharkey54d0af52011-08-11 18:26:57 -070090import android.util.SparseArray;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070091import android.view.LayoutInflater;
Jeff Sharkey8a503642011-06-10 13:31:21 -070092import android.view.Menu;
93import android.view.MenuInflater;
94import android.view.MenuItem;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070095import android.view.View;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -070096import android.view.View.OnClickListener;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070097import android.view.ViewGroup;
Jeff Sharkey2af35fb2011-06-24 17:30:27 -070098import android.view.ViewTreeObserver.OnGlobalLayoutListener;
Jeff Sharkey8a503642011-06-10 13:31:21 -070099import android.widget.AdapterView;
100import android.widget.AdapterView.OnItemClickListener;
101import android.widget.AdapterView.OnItemSelectedListener;
102import android.widget.ArrayAdapter;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700103import android.widget.BaseAdapter;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700104import android.widget.Button;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700105import android.widget.CheckBox;
106import android.widget.CompoundButton;
107import android.widget.CompoundButton.OnCheckedChangeListener;
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -0700108import android.widget.ImageView;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700109import android.widget.LinearLayout;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700110import android.widget.ListView;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700111import android.widget.NumberPicker;
Jeff Sharkey2412b0f2011-07-17 20:31:40 -0700112import android.widget.ProgressBar;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700113import android.widget.Spinner;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700114import android.widget.Switch;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700115import android.widget.TabHost;
116import android.widget.TabHost.OnTabChangeListener;
117import android.widget.TabHost.TabContentFactory;
118import android.widget.TabHost.TabSpec;
119import android.widget.TabWidget;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700120import android.widget.TextView;
121
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700122import com.android.internal.telephony.Phone;
Jeff Sharkeya662e492011-06-18 21:57:06 -0700123import com.android.settings.net.NetworkPolicyEditor;
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700124import com.android.settings.net.SummaryForAllUidLoader;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700125import com.android.settings.widget.DataUsageChartView;
126import com.android.settings.widget.DataUsageChartView.DataUsageChartListener;
Jeff Sharkey54d0af52011-08-11 18:26:57 -0700127import com.android.settings.widget.PieChartView;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700128import com.google.android.collect.Lists;
129
130import java.util.ArrayList;
131import java.util.Collections;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700132import java.util.Locale;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700133
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700134import libcore.util.Objects;
135
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700136/**
137 * Panel show data usage history across various networks, including options to
138 * inspect based on usage cycle and control through {@link NetworkPolicy}.
139 */
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700140public class DataUsageSummary extends Fragment {
141 private static final String TAG = "DataUsage";
Jeff Sharkey8a503642011-06-10 13:31:21 -0700142 private static final boolean LOGD = true;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700143
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700144 // TODO: remove this testing code
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700145 private static final boolean TEST_ANIM = false;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700146 private static final boolean TEST_RADIOS = false;
147 private static final String TEST_RADIOS_PROP = "test.radios";
148
Jeff Sharkey8a503642011-06-10 13:31:21 -0700149 private static final String TAB_3G = "3g";
150 private static final String TAB_4G = "4g";
151 private static final String TAB_MOBILE = "mobile";
152 private static final String TAB_WIFI = "wifi";
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700153 private static final String TAB_ETHERNET = "ethernet";
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700154
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700155 private static final String TAG_CONFIRM_ROAMING = "confirmRoaming";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700156 private static final String TAG_CONFIRM_LIMIT = "confirmLimit";
157 private static final String TAG_CYCLE_EDITOR = "cycleEditor";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700158 private static final String TAG_CONFIRM_RESTRICT = "confirmRestrict";
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700159 private static final String TAG_CONFIRM_APP_RESTRICT = "confirmAppRestrict";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700160 private static final String TAG_APP_DETAILS = "appDetails";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700161
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700162 private static final int LOADER_SUMMARY = 2;
163
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700164 private static final long KB_IN_BYTES = 1024;
165 private static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
166 private static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
167
Jeff Sharkey1ae43f92011-08-03 17:16:09 -0700168 private INetworkManagementService mNetworkService;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700169 private INetworkStatsService mStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700170 private INetworkPolicyManager mPolicyService;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700171 private ConnectivityManager mConnService;
172
173 private static final String PREF_FILE = "data_usage";
174 private static final String PREF_SHOW_WIFI = "show_wifi";
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700175 private static final String PREF_SHOW_ETHERNET = "show_ethernet";
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700176
177 private SharedPreferences mPrefs;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700178
Jeff Sharkey8a503642011-06-10 13:31:21 -0700179 private TabHost mTabHost;
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700180 private ViewGroup mTabsContainer;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700181 private TabWidget mTabWidget;
182 private ListView mListView;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700183 private DataUsageAdapter mAdapter;
184
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700185 private ViewGroup mHeader;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700186
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700187 private ViewGroup mNetworkSwitchesContainer;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700188 private LinearLayout mNetworkSwitches;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700189 private Switch mDataEnabled;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700190 private View mDataEnabledView;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700191 private CheckBox mDisableAtLimit;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700192 private View mDisableAtLimitView;
193
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700194 private View mCycleView;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700195 private Spinner mCycleSpinner;
196 private CycleAdapter mCycleAdapter;
197
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700198 private DataUsageChartView mChart;
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700199 private TextView mUsageSummary;
Jeff Sharkeye2afc0f2011-08-01 15:29:30 -0700200 private TextView mEmpty;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700201
202 private View mAppDetail;
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -0700203 private ImageView mAppIcon;
204 private ViewGroup mAppTitles;
Jeff Sharkey54d0af52011-08-11 18:26:57 -0700205 private PieChartView mAppPieChart;
206 private TextView mAppForeground;
207 private TextView mAppBackground;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700208 private Button mAppSettings;
209
210 private LinearLayout mAppSwitches;
211 private CheckBox mAppRestrict;
212 private View mAppRestrictView;
213
Jeff Sharkey8a503642011-06-10 13:31:21 -0700214 private boolean mShowWifi = false;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700215 private boolean mShowEthernet = false;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700216
Jeff Sharkeya662e492011-06-18 21:57:06 -0700217 private NetworkTemplate mTemplate = null;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700218
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700219 private static final int UID_NONE = -1;
220 private int mUid = UID_NONE;
221
222 private Intent mAppSettingsIntent;
223
Jeff Sharkeya662e492011-06-18 21:57:06 -0700224 private NetworkPolicyEditor mPolicyEditor;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700225
Jeff Sharkey8a503642011-06-10 13:31:21 -0700226 private NetworkStatsHistory mHistory;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700227 private NetworkStatsHistory mDetailHistory;
Jeff Sharkey54d0af52011-08-11 18:26:57 -0700228 private NetworkStatsHistory mDetailHistoryDefault;
229 private NetworkStatsHistory mDetailHistoryForeground;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700230
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700231 private String mCurrentTab = null;
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700232 private String mIntentTab = null;
233
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700234 private MenuItem mMenuDataRoaming;
235 private MenuItem mMenuRestrictBackground;
236
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700237 /** Flag used to ignore listeners during binding. */
238 private boolean mBinding;
239
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700240 @Override
Jeff Sharkey8a503642011-06-10 13:31:21 -0700241 public void onCreate(Bundle savedInstanceState) {
242 super.onCreate(savedInstanceState);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700243
Jeff Sharkey1ae43f92011-08-03 17:16:09 -0700244 mNetworkService = INetworkManagementService.Stub.asInterface(
245 ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700246 mStatsService = INetworkStatsService.Stub.asInterface(
247 ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700248 mPolicyService = INetworkPolicyManager.Stub.asInterface(
249 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700250 mConnService = (ConnectivityManager) getActivity().getSystemService(
251 Context.CONNECTIVITY_SERVICE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700252
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700253 mPrefs = getActivity().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700254
Jeff Sharkeya662e492011-06-18 21:57:06 -0700255 mPolicyEditor = new NetworkPolicyEditor(mPolicyService);
256 mPolicyEditor.read();
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700257
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700258 mShowWifi = mPrefs.getBoolean(PREF_SHOW_WIFI, false);
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700259 mShowEthernet = mPrefs.getBoolean(PREF_SHOW_ETHERNET, false);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700260
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700261 setHasOptionsMenu(true);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700262 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700263
Jeff Sharkey8a503642011-06-10 13:31:21 -0700264 @Override
265 public View onCreateView(LayoutInflater inflater, ViewGroup container,
266 Bundle savedInstanceState) {
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700267
Jeff Sharkey8a503642011-06-10 13:31:21 -0700268 final Context context = inflater.getContext();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700269 final View view = inflater.inflate(R.layout.data_usage_summary, container, false);
270
Jeff Sharkey8a503642011-06-10 13:31:21 -0700271 mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700272 mTabsContainer = (ViewGroup) view.findViewById(R.id.tabs_container);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700273 mTabWidget = (TabWidget) view.findViewById(android.R.id.tabs);
274 mListView = (ListView) view.findViewById(android.R.id.list);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700275
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700276 // adjust padding around tabwidget as needed
277 prepareCustomPreferencesList(container, view, mListView);
278
Jeff Sharkey8a503642011-06-10 13:31:21 -0700279 mTabHost.setup();
280 mTabHost.setOnTabChangedListener(mTabListener);
281
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700282 mHeader = (ViewGroup) inflater.inflate(R.layout.data_usage_header, mListView, false);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700283 mListView.addHeaderView(mHeader, null, false);
284
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700285 {
286 // bind network switches
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700287 mNetworkSwitchesContainer = (ViewGroup) mHeader.findViewById(
288 R.id.network_switches_container);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700289 mNetworkSwitches = (LinearLayout) mHeader.findViewById(R.id.network_switches);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700290
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700291 mDataEnabled = new Switch(inflater.getContext());
292 mDataEnabledView = inflatePreference(inflater, mNetworkSwitches, mDataEnabled);
293 mDataEnabled.setOnCheckedChangeListener(mDataEnabledListener);
294 mNetworkSwitches.addView(mDataEnabledView);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700295
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700296 mDisableAtLimit = new CheckBox(inflater.getContext());
297 mDisableAtLimit.setClickable(false);
298 mDisableAtLimitView = inflatePreference(inflater, mNetworkSwitches, mDisableAtLimit);
299 mDisableAtLimitView.setOnClickListener(mDisableAtLimitListener);
300 mNetworkSwitches.addView(mDisableAtLimitView);
301 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700302
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700303 // bind cycle dropdown
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700304 mCycleView = mHeader.findViewById(R.id.cycles);
305 mCycleSpinner = (Spinner) mCycleView.findViewById(R.id.cycles_spinner);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700306 mCycleAdapter = new CycleAdapter(context);
307 mCycleSpinner.setAdapter(mCycleAdapter);
308 mCycleSpinner.setOnItemSelectedListener(mCycleListener);
309
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700310 mChart = (DataUsageChartView) mHeader.findViewById(R.id.chart);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700311 mChart.setListener(mChartListener);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700312
313 {
314 // bind app detail controls
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700315 mAppDetail = mHeader.findViewById(R.id.app_detail);
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -0700316 mAppIcon = (ImageView) mAppDetail.findViewById(R.id.app_icon);
317 mAppTitles = (ViewGroup) mAppDetail.findViewById(R.id.app_titles);
Jeff Sharkey54d0af52011-08-11 18:26:57 -0700318 mAppPieChart = (PieChartView) mAppDetail.findViewById(R.id.app_pie_chart);
319 mAppForeground = (TextView) mAppDetail.findViewById(R.id.app_foreground);
320 mAppBackground = (TextView) mAppDetail.findViewById(R.id.app_background);
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700321 mAppSwitches = (LinearLayout) mAppDetail.findViewById(R.id.app_switches);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700322
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700323 mAppSettings = (Button) mAppDetail.findViewById(R.id.app_settings);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700324 mAppSettings.setOnClickListener(mAppSettingsListener);
325
326 mAppRestrict = new CheckBox(inflater.getContext());
327 mAppRestrict.setClickable(false);
328 mAppRestrictView = inflatePreference(inflater, mAppSwitches, mAppRestrict);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700329 mAppRestrictView.setOnClickListener(mAppRestrictListener);
330 mAppSwitches.addView(mAppRestrictView);
331 }
332
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700333 mUsageSummary = (TextView) mHeader.findViewById(R.id.usage_summary);
Jeff Sharkeye2afc0f2011-08-01 15:29:30 -0700334 mEmpty = (TextView) mHeader.findViewById(android.R.id.empty);
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700335
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700336 // only assign layout transitions once first layout is finished
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700337 mListView.getViewTreeObserver().addOnGlobalLayoutListener(mFirstLayoutListener);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700338
339 mAdapter = new DataUsageAdapter();
340 mListView.setOnItemClickListener(mListListener);
341 mListView.setAdapter(mAdapter);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700342
343 return view;
344 }
345
346 @Override
347 public void onResume() {
348 super.onResume();
349
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700350 // pick default tab based on incoming intent
351 final Intent intent = getActivity().getIntent();
352 mIntentTab = computeTabFromIntent(intent);
353
Jeff Sharkey8a503642011-06-10 13:31:21 -0700354 // this kicks off chain reaction which creates tabs, binds the body to
355 // selected network, and binds chart, cycles and detail list.
356 updateTabs();
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700357
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700358 // kick off background task to update stats
359 new AsyncTask<Void, Void, Void>() {
360 @Override
361 protected Void doInBackground(Void... params) {
362 try {
363 mStatsService.forceUpdate();
364 } catch (RemoteException e) {
365 }
366 return null;
367 }
368
369 @Override
370 protected void onPostExecute(Void result) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700371 if (isAdded()) {
372 updateBody();
373 }
Jeff Sharkey398b18f2011-07-10 18:56:30 -0700374 }
375 }.execute();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700376 }
377
Jeff Sharkey8a503642011-06-10 13:31:21 -0700378 @Override
379 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
380 inflater.inflate(R.menu.data_usage, menu);
381 }
382
383 @Override
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700384 public void onPrepareOptionsMenu(Menu menu) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700385 final Context context = getActivity();
386
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700387 mMenuDataRoaming = menu.findItem(R.id.data_usage_menu_roaming);
388 mMenuDataRoaming.setVisible(hasMobileRadio(context));
389 mMenuDataRoaming.setChecked(getDataRoaming());
390
391 mMenuRestrictBackground = menu.findItem(R.id.data_usage_menu_restrict_background);
392 mMenuRestrictBackground.setChecked(getRestrictBackground());
393
394 final MenuItem split4g = menu.findItem(R.id.data_usage_menu_split_4g);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700395 split4g.setVisible(hasMobile4gRadio(context));
Jeff Sharkeya662e492011-06-18 21:57:06 -0700396 split4g.setChecked(isMobilePolicySplit());
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700397
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700398 final MenuItem showWifi = menu.findItem(R.id.data_usage_menu_show_wifi);
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700399 if (hasWifiRadio(context) && hasMobileRadio(context)) {
400 showWifi.setVisible(true);
401 showWifi.setChecked(mShowWifi);
402 } else {
403 showWifi.setVisible(false);
404 mShowWifi = true;
405 }
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700406
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700407 final MenuItem showEthernet = menu.findItem(R.id.data_usage_menu_show_ethernet);
408 if (hasEthernet(context) && hasMobileRadio(context)) {
409 showEthernet.setVisible(true);
410 showEthernet.setChecked(mShowEthernet);
411 } else {
412 showEthernet.setVisible(false);
413 mShowEthernet = true;
414 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700415 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700416
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700417 @Override
418 public boolean onOptionsItemSelected(MenuItem item) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700419 switch (item.getItemId()) {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700420 case R.id.data_usage_menu_roaming: {
421 final boolean dataRoaming = !item.isChecked();
422 if (dataRoaming) {
423 ConfirmDataRoamingFragment.show(this);
424 } else {
425 // no confirmation to disable roaming
426 setDataRoaming(false);
427 }
428 return true;
429 }
430 case R.id.data_usage_menu_restrict_background: {
431 final boolean restrictBackground = !item.isChecked();
432 if (restrictBackground) {
433 ConfirmRestrictFragment.show(this);
434 } else {
435 // no confirmation to drop restriction
436 setRestrictBackground(false);
437 }
438 return true;
439 }
440 case R.id.data_usage_menu_split_4g: {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700441 final boolean mobileSplit = !item.isChecked();
Jeff Sharkeya662e492011-06-18 21:57:06 -0700442 setMobilePolicySplit(mobileSplit);
443 item.setChecked(isMobilePolicySplit());
Jeff Sharkey8a503642011-06-10 13:31:21 -0700444 updateTabs();
445 return true;
446 }
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700447 case R.id.data_usage_menu_show_wifi: {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700448 mShowWifi = !item.isChecked();
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700449 mPrefs.edit().putBoolean(PREF_SHOW_WIFI, mShowWifi).apply();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700450 item.setChecked(mShowWifi);
451 updateTabs();
452 return true;
453 }
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700454 case R.id.data_usage_menu_show_ethernet: {
455 mShowEthernet = !item.isChecked();
456 mPrefs.edit().putBoolean(PREF_SHOW_ETHERNET, mShowEthernet).apply();
457 item.setChecked(mShowEthernet);
458 updateTabs();
459 return true;
460 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700461 }
462 return false;
463 }
464
Jeff Sharkey94a90952011-06-13 22:31:09 -0700465 @Override
466 public void onDestroyView() {
467 super.onDestroyView();
468
469 mDataEnabledView = null;
470 mDisableAtLimitView = null;
471 }
472
Jeff Sharkey8a503642011-06-10 13:31:21 -0700473 /**
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700474 * Listener to setup {@link LayoutTransition} after first layout pass.
475 */
476 private OnGlobalLayoutListener mFirstLayoutListener = new OnGlobalLayoutListener() {
477 /** {@inheritDoc} */
478 public void onGlobalLayout() {
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700479 mListView.getViewTreeObserver().removeGlobalOnLayoutListener(mFirstLayoutListener);
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700480
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700481 mTabsContainer.setLayoutTransition(buildLayoutTransition());
482 mHeader.setLayoutTransition(buildLayoutTransition());
483 mNetworkSwitchesContainer.setLayoutTransition(buildLayoutTransition());
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700484
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700485 final LayoutTransition chartTransition = buildLayoutTransition();
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700486 chartTransition.setStartDelay(LayoutTransition.APPEARING, 0);
487 chartTransition.setStartDelay(LayoutTransition.DISAPPEARING, 0);
488 mChart.setLayoutTransition(chartTransition);
489 }
490 };
491
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700492 private static LayoutTransition buildLayoutTransition() {
493 final LayoutTransition transition = new LayoutTransition();
494 if (TEST_ANIM) {
495 transition.setDuration(1500);
496 }
497 transition.setAnimateParentHierarchy(false);
498 return transition;
499 }
500
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700501 /**
Jeff Sharkeya662e492011-06-18 21:57:06 -0700502 * Rebuild all tabs based on {@link NetworkPolicyEditor} and
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700503 * {@link #mShowWifi}, hiding the tabs entirely when applicable. Selects
504 * first tab, and kicks off a full rebind of body contents.
Jeff Sharkey8a503642011-06-10 13:31:21 -0700505 */
506 private void updateTabs() {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700507 final Context context = getActivity();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700508 mTabHost.clearAllTabs();
509
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700510 final boolean mobileSplit = isMobilePolicySplit();
511 if (mobileSplit && hasMobile4gRadio(context)) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700512 mTabHost.addTab(buildTabSpec(TAB_3G, R.string.data_usage_tab_3g));
513 mTabHost.addTab(buildTabSpec(TAB_4G, R.string.data_usage_tab_4g));
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700514 } else if (hasMobileRadio(context)) {
515 mTabHost.addTab(buildTabSpec(TAB_MOBILE, R.string.data_usage_tab_mobile));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700516 }
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700517 if (mShowWifi && hasWifiRadio(context)) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700518 mTabHost.addTab(buildTabSpec(TAB_WIFI, R.string.data_usage_tab_wifi));
519 }
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700520 if (mShowEthernet && hasEthernet(context)) {
521 mTabHost.addTab(buildTabSpec(TAB_ETHERNET, R.string.data_usage_tab_ethernet));
522 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700523
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700524 final boolean multipleTabs = mTabWidget.getTabCount() > 1;
525 mTabWidget.setVisibility(multipleTabs ? View.VISIBLE : View.GONE);
526 if (mIntentTab != null) {
527 if (Objects.equal(mIntentTab, mTabHost.getCurrentTabTag())) {
528 updateBody();
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700529 } else {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700530 mTabHost.setCurrentTabByTag(mIntentTab);
531 }
532 mIntentTab = null;
533 } else {
534 if (mTabHost.getCurrentTab() == 0) {
535 updateBody();
536 } else {
Jeff Sharkeydd6efe12011-06-15 10:31:41 -0700537 mTabHost.setCurrentTab(0);
538 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700539 }
540 }
541
Jeff Sharkey8a503642011-06-10 13:31:21 -0700542 /**
543 * Factory that provide empty {@link View} to make {@link TabHost} happy.
544 */
545 private TabContentFactory mEmptyTabContent = new TabContentFactory() {
546 /** {@inheritDoc} */
547 public View createTabContent(String tag) {
548 return new View(mTabHost.getContext());
549 }
550 };
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700551
Jeff Sharkey8a503642011-06-10 13:31:21 -0700552 /**
553 * Build {@link TabSpec} with thin indicator, and empty content.
554 */
555 private TabSpec buildTabSpec(String tag, int titleRes) {
Jeff Sharkey54d0af52011-08-11 18:26:57 -0700556 return mTabHost.newTabSpec(tag).setIndicator(getText(titleRes)).setContent(
557 mEmptyTabContent);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700558 }
559
560 private OnTabChangeListener mTabListener = new OnTabChangeListener() {
561 /** {@inheritDoc} */
562 public void onTabChanged(String tabId) {
563 // user changed tab; update body
564 updateBody();
565 }
566 };
567
568 /**
569 * Update body content based on current tab. Loads
570 * {@link NetworkStatsHistory} and {@link NetworkPolicy} from system, and
571 * binds them to visible controls.
572 */
573 private void updateBody() {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700574 mBinding = true;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700575
Jeff Sharkeya662e492011-06-18 21:57:06 -0700576 final Context context = getActivity();
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700577 final String currentTab = mTabHost.getCurrentTabTag();
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700578
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700579 if (currentTab == null) {
580 Log.w(TAG, "no tab selected; hiding body");
581 mListView.setVisibility(View.GONE);
582 return;
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700583 } else {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700584 mListView.setVisibility(View.VISIBLE);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700585 }
Jeff Sharkeya662e492011-06-18 21:57:06 -0700586
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700587 final boolean tabChanged = !currentTab.equals(mCurrentTab);
588 mCurrentTab = currentTab;
589
Jeff Sharkey8a503642011-06-10 13:31:21 -0700590 if (LOGD) Log.d(TAG, "updateBody() with currentTab=" + currentTab);
591
Jeff Sharkey131f9d62011-08-17 17:08:19 -0700592 mDataEnabledView.setVisibility(View.VISIBLE);
593 mDisableAtLimitView.setVisibility(View.VISIBLE);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700594
595 if (TAB_MOBILE.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700596 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_mobile);
597 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_mobile_limit);
598 mDataEnabled.setChecked(mConnService.getMobileDataEnabled());
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700599 mTemplate = buildTemplateMobileAll(getActiveSubscriberId(context));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700600
601 } else if (TAB_3G.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700602 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_3g);
603 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_3g_limit);
604 // TODO: bind mDataEnabled to 3G radio state
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700605 mTemplate = buildTemplateMobile3gLower(getActiveSubscriberId(context));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700606
607 } else if (TAB_4G.equals(currentTab)) {
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700608 setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_4g);
609 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_4g_limit);
610 // TODO: bind mDataEnabled to 4G radio state
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700611 mTemplate = buildTemplateMobile4g(getActiveSubscriberId(context));
Jeff Sharkey131f9d62011-08-17 17:08:19 -0700612
613 } else if (TAB_WIFI.equals(currentTab)) {
614 mDataEnabledView.setVisibility(View.GONE);
615 setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_wifi_limit);
616 mTemplate = buildTemplateWifi();
617
618 } else if (TAB_ETHERNET.equals(currentTab)) {
619 // ethernet doesn't have any controls
620 mDataEnabledView.setVisibility(View.GONE);
621 mDisableAtLimitView.setVisibility(View.GONE);
622 mTemplate = buildTemplateEthernet();
623
624 } else {
625 throw new IllegalStateException("unknown tab: " + currentTab);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700626 }
627
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700628 try {
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700629 // load stats for current template
Jeff Sharkey1ae43f92011-08-03 17:16:09 -0700630 mHistory = mStatsService.getHistoryForNetwork(
631 mTemplate, FIELD_RX_BYTES | FIELD_TX_BYTES);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700632 } catch (RemoteException e) {
633 // since we can't do much without policy or history, and we don't
634 // want to leave with half-baked UI, we bail hard.
635 throw new RuntimeException("problem reading network policy or stats", e);
636 }
637
Jeff Sharkey8a503642011-06-10 13:31:21 -0700638 // bind chart to historical stats
Jeff Sharkey8a503642011-06-10 13:31:21 -0700639 mChart.bindNetworkStats(mHistory);
640
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700641 // only update policy when switching tabs
642 updatePolicy(tabChanged);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700643 updateAppDetail();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700644
645 // force scroll to top of body
646 mListView.smoothScrollToPosition(0);
647
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700648 mBinding = false;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700649 }
650
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700651 private boolean isAppDetailMode() {
652 return mUid != UID_NONE;
653 }
654
655 /**
656 * Update UID details panels to match {@link #mUid}, showing or hiding them
657 * depending on {@link #isAppDetailMode()}.
658 */
659 private void updateAppDetail() {
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -0700660 final Context context = getActivity();
661 final PackageManager pm = context.getPackageManager();
662 final LayoutInflater inflater = getActivity().getLayoutInflater();
663
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700664 if (isAppDetailMode()) {
665 mAppDetail.setVisibility(View.VISIBLE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700666 mCycleAdapter.setChangeVisible(false);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700667 } else {
668 mAppDetail.setVisibility(View.GONE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700669 mCycleAdapter.setChangeVisible(true);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700670
Jeff Sharkey54d0af52011-08-11 18:26:57 -0700671 mDetailHistory = null;
672 mDetailHistoryDefault = null;
673 mDetailHistoryForeground = null;
674
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700675 // hide detail stats when not in detail mode
676 mChart.bindDetailNetworkStats(null);
677 return;
678 }
679
680 // remove warning/limit sweeps while in detail mode
681 mChart.bindNetworkPolicy(null);
682
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -0700683 // show icon and all labels appearing under this app
684 final UidDetail detail = resolveDetailForUid(context, mUid);
685 mAppIcon.setImageDrawable(detail.icon);
686
687 mAppTitles.removeAllViews();
688 if (detail.detailLabels != null) {
689 for (CharSequence label : detail.detailLabels) {
690 mAppTitles.addView(inflateAppTitle(inflater, mAppTitles, label));
691 }
692 } else {
693 mAppTitles.addView(inflateAppTitle(inflater, mAppTitles, detail.label));
694 }
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700695
696 // enable settings button when package provides it
697 // TODO: target torwards entire UID instead of just first package
698 final String[] packageNames = pm.getPackagesForUid(mUid);
699 if (packageNames != null && packageNames.length > 0) {
700 mAppSettingsIntent = new Intent(Intent.ACTION_MANAGE_NETWORK_USAGE);
701 mAppSettingsIntent.setPackage(packageNames[0]);
702 mAppSettingsIntent.addCategory(Intent.CATEGORY_DEFAULT);
703
704 final boolean matchFound = pm.resolveActivity(mAppSettingsIntent, 0) != null;
705 mAppSettings.setEnabled(matchFound);
706
707 } else {
708 mAppSettingsIntent = null;
709 mAppSettings.setEnabled(false);
710 }
711
712 try {
713 // load stats for current uid and template
Jeff Sharkey54d0af52011-08-11 18:26:57 -0700714 mDetailHistoryDefault = mStatsService.getHistoryForUid(
715 mTemplate, mUid, SET_DEFAULT, TAG_NONE, FIELD_RX_BYTES | FIELD_TX_BYTES);
716 mDetailHistoryForeground = mStatsService.getHistoryForUid(
717 mTemplate, mUid, SET_FOREGROUND, TAG_NONE, FIELD_RX_BYTES | FIELD_TX_BYTES);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700718 } catch (RemoteException e) {
719 // since we can't do much without history, and we don't want to
720 // leave with half-baked UI, we bail hard.
721 throw new RuntimeException("problem reading network stats", e);
722 }
723
Jeff Sharkey54d0af52011-08-11 18:26:57 -0700724 mDetailHistory = new NetworkStatsHistory(mDetailHistoryForeground.getBucketDuration());
725 mDetailHistory.recordEntireHistory(mDetailHistoryDefault);
726 mDetailHistory.recordEntireHistory(mDetailHistoryForeground);
727
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700728 // bind chart to historical stats
729 mChart.bindDetailNetworkStats(mDetailHistory);
730
731 updateDetailData();
732
Jeff Sharkey1ae43f92011-08-03 17:16:09 -0700733 if (NetworkPolicyManager.isUidValidForPolicy(context, mUid) && !getRestrictBackground()
734 && isBandwidthControlEnabled()) {
Jeff Sharkey30dde0f2011-08-17 15:08:12 -0700735 setPreferenceTitle(mAppRestrictView, R.string.data_usage_app_restrict_background);
736 setPreferenceSummary(mAppRestrictView,
737 getString(R.string.data_usage_app_restrict_background_summary,
738 buildLimitedNetworksList()));
739
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700740 mAppRestrictView.setVisibility(View.VISIBLE);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700741 mAppRestrict.setChecked(getAppRestrictBackground());
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700742
743 } else {
744 mAppRestrictView.setVisibility(View.GONE);
745 }
746
747 }
748
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700749 private void setPolicyCycleDay(int cycleDay) {
750 if (LOGD) Log.d(TAG, "setPolicyCycleDay()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700751 mPolicyEditor.setPolicyCycleDay(mTemplate, cycleDay);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700752 updatePolicy(true);
753 }
754
755 private void setPolicyWarningBytes(long warningBytes) {
756 if (LOGD) Log.d(TAG, "setPolicyWarningBytes()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700757 mPolicyEditor.setPolicyWarningBytes(mTemplate, warningBytes);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700758 updatePolicy(false);
759 }
760
761 private void setPolicyLimitBytes(long limitBytes) {
762 if (LOGD) Log.d(TAG, "setPolicyLimitBytes()");
Jeff Sharkeya662e492011-06-18 21:57:06 -0700763 mPolicyEditor.setPolicyLimitBytes(mTemplate, limitBytes);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700764 updatePolicy(false);
765 }
766
Jeff Sharkey1ae43f92011-08-03 17:16:09 -0700767 private boolean isNetworkPolicyModifiable() {
768 return isBandwidthControlEnabled() && mDataEnabled.isChecked();
769 }
770
771 private boolean isBandwidthControlEnabled() {
772 try {
773 return mNetworkService.isBandwidthControlEnabled();
774 } catch (RemoteException e) {
775 Log.w(TAG, "problem talking with INetworkManagementService: " + e);
776 return false;
777 }
778 }
779
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700780 private boolean getDataRoaming() {
781 final ContentResolver resolver = getActivity().getContentResolver();
782 return Settings.Secure.getInt(resolver, Settings.Secure.DATA_ROAMING, 0) != 0;
783 }
784
785 private void setDataRoaming(boolean enabled) {
786 // TODO: teach telephony DataConnectionTracker to watch and apply
787 // updates when changed.
788 final ContentResolver resolver = getActivity().getContentResolver();
789 Settings.Secure.putInt(resolver, Settings.Secure.DATA_ROAMING, enabled ? 1 : 0);
790 mMenuDataRoaming.setChecked(enabled);
791 }
792
793 private boolean getRestrictBackground() {
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700794 try {
795 return mPolicyService.getRestrictBackground();
796 } catch (RemoteException e) {
797 Log.w(TAG, "problem talking with policy service: " + e);
798 return false;
799 }
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700800 }
801
802 private void setRestrictBackground(boolean restrictBackground) {
803 if (LOGD) Log.d(TAG, "setRestrictBackground()");
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700804 try {
805 mPolicyService.setRestrictBackground(restrictBackground);
806 mMenuRestrictBackground.setChecked(restrictBackground);
807 } catch (RemoteException e) {
808 Log.w(TAG, "problem talking with policy service: " + e);
809 }
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700810 }
811
812 private boolean getAppRestrictBackground() {
813 final int uidPolicy;
814 try {
815 uidPolicy = mPolicyService.getUidPolicy(mUid);
816 } catch (RemoteException e) {
817 // since we can't do much without policy, we bail hard.
818 throw new RuntimeException("problem reading network policy", e);
819 }
820
821 return (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
822 }
823
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700824 private void setAppRestrictBackground(boolean restrictBackground) {
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -0700825 if (LOGD) Log.d(TAG, "setAppRestrictBackground()");
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700826 try {
827 mPolicyService.setUidPolicy(
828 mUid, restrictBackground ? POLICY_REJECT_METERED_BACKGROUND : POLICY_NONE);
829 } catch (RemoteException e) {
830 throw new RuntimeException("unable to save policy", e);
831 }
832
833 mAppRestrict.setChecked(restrictBackground);
834 }
835
Jeff Sharkey8a503642011-06-10 13:31:21 -0700836 /**
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700837 * Update chart sweeps and cycle list to reflect {@link NetworkPolicy} for
838 * current {@link #mTemplate}.
839 */
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700840 private void updatePolicy(boolean refreshCycle) {
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700841 if (isAppDetailMode()) {
842 mNetworkSwitches.setVisibility(View.GONE);
843 // we fall through to update cycle list for detail mode
844 } else {
845 mNetworkSwitches.setVisibility(View.VISIBLE);
Jeff Sharkey2af35fb2011-06-24 17:30:27 -0700846
847 // when heading back to summary without cycle refresh, kick details
848 // update to repopulate list.
849 if (!refreshCycle) {
850 updateDetailData();
851 }
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700852 }
853
Jeff Sharkey131f9d62011-08-17 17:08:19 -0700854 final NetworkPolicy policy = mPolicyEditor.getPolicy(mTemplate, true);
Jeff Sharkey1ae43f92011-08-03 17:16:09 -0700855 if (isNetworkPolicyModifiable()) {
856 mDisableAtLimitView.setVisibility(View.VISIBLE);
857 mDisableAtLimit.setChecked(policy != null && policy.limitBytes != LIMIT_DISABLED);
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -0700858 if (!isAppDetailMode()) {
859 mChart.bindNetworkPolicy(policy);
860 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700861
Jeff Sharkey1ae43f92011-08-03 17:16:09 -0700862 } else {
863 // controls are disabled; don't bind warning/limit sweeps
864 mDisableAtLimitView.setVisibility(View.GONE);
865 mChart.bindNetworkPolicy(null);
866 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700867
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700868 if (refreshCycle) {
869 // generate cycle list based on policy and available history
870 updateCycleList(policy);
871 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700872 }
873
874 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -0700875 * Rebuild {@link #mCycleAdapter} based on {@link NetworkPolicy#cycleDay}
876 * and available {@link NetworkStatsHistory} data. Always selects the newest
877 * item, updating the inspection range on {@link #mChart}.
878 */
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700879 private void updateCycleList(NetworkPolicy policy) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700880 mCycleAdapter.clear();
881
882 final Context context = mCycleSpinner.getContext();
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700883 long historyStart = mHistory.getStart();
884 long historyEnd = mHistory.getEnd();
Jeff Sharkey8a503642011-06-10 13:31:21 -0700885
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700886 if (historyStart == Long.MAX_VALUE || historyEnd == Long.MIN_VALUE) {
887 historyStart = System.currentTimeMillis();
888 historyEnd = System.currentTimeMillis();
889 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700890
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700891 boolean hasCycles = false;
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700892 if (policy != null) {
893 // find the next cycle boundary
894 long cycleEnd = computeNextCycleBoundary(historyEnd, policy);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700895
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700896 int guardCount = 0;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700897
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700898 // walk backwards, generating all valid cycle ranges
899 while (cycleEnd > historyStart) {
900 final long cycleStart = computeLastCycleBoundary(cycleEnd, policy);
901 Log.d(TAG, "generating cs=" + cycleStart + " to ce=" + cycleEnd + " waiting for hs="
902 + historyStart);
903 mCycleAdapter.add(new CycleItem(context, cycleStart, cycleEnd));
904 cycleEnd = cycleStart;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700905 hasCycles = true;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700906
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700907 // TODO: remove this guard once we have better testing
908 if (guardCount++ > 50) {
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700909 Log.wtf(TAG, "stuck generating ranges for historyStart=" + historyStart
910 + ", historyEnd=" + historyEnd + " and policy=" + policy);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700911 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700912 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700913
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700914 // one last cycle entry to modify policy cycle day
Jeff Sharkey1ae43f92011-08-03 17:16:09 -0700915 mCycleAdapter.setChangePossible(isNetworkPolicyModifiable());
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700916 }
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700917
Jeff Sharkey518bc9d2011-07-12 20:20:46 -0700918 if (!hasCycles) {
919 // no valid cycles; show all data
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700920 // TODO: offer simple ranges like "last week" etc
921 mCycleAdapter.add(new CycleItem(context, historyStart, historyEnd));
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700922 mCycleAdapter.setChangePossible(false);
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -0700923 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700924
925 // force pick the current cycle (first item)
926 mCycleSpinner.setSelection(0);
927 mCycleListener.onItemSelected(mCycleSpinner, null, 0, 0);
928 }
929
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700930 private OnCheckedChangeListener mDataEnabledListener = new OnCheckedChangeListener() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700931 /** {@inheritDoc} */
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700932 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
933 if (mBinding) return;
Jeff Sharkey8a503642011-06-10 13:31:21 -0700934
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700935 final boolean dataEnabled = isChecked;
936 mDataEnabled.setChecked(dataEnabled);
937
Jeff Sharkey9549e9f2011-07-14 20:01:13 -0700938 final String currentTab = mCurrentTab;
939 if (TAB_MOBILE.equals(currentTab)) {
940 mConnService.setMobileDataEnabled(dataEnabled);
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700941 }
Jeff Sharkey1ae43f92011-08-03 17:16:09 -0700942
943 // rebind policy to match radio state
944 updatePolicy(true);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700945 }
946 };
947
Jeff Sharkey29d56b32011-06-20 17:06:52 -0700948 private View.OnClickListener mDisableAtLimitListener = new View.OnClickListener() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700949 /** {@inheritDoc} */
950 public void onClick(View v) {
951 final boolean disableAtLimit = !mDisableAtLimit.isChecked();
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700952 if (disableAtLimit) {
953 // enabling limit; show confirmation dialog which eventually
954 // calls setPolicyLimitBytes() once user confirms.
955 ConfirmLimitFragment.show(DataUsageSummary.this);
956 } else {
957 setPolicyLimitBytes(LIMIT_DISABLED);
958 }
Jeff Sharkey8a503642011-06-10 13:31:21 -0700959 }
960 };
961
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700962 private View.OnClickListener mAppRestrictListener = new View.OnClickListener() {
963 /** {@inheritDoc} */
964 public void onClick(View v) {
965 final boolean restrictBackground = !mAppRestrict.isChecked();
966
967 if (restrictBackground) {
968 // enabling restriction; show confirmation dialog which
969 // eventually calls setRestrictBackground() once user confirms.
Jeff Sharkey9fab0da2011-07-09 17:52:31 -0700970 ConfirmAppRestrictFragment.show(DataUsageSummary.this);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700971 } else {
972 setAppRestrictBackground(false);
973 }
974 }
975 };
976
977 private OnClickListener mAppSettingsListener = new OnClickListener() {
978 /** {@inheritDoc} */
979 public void onClick(View v) {
980 // TODO: target torwards entire UID instead of just first package
981 startActivity(mAppSettingsIntent);
982 }
983 };
984
Jeff Sharkey8a503642011-06-10 13:31:21 -0700985 private OnItemClickListener mListListener = new OnItemClickListener() {
986 /** {@inheritDoc} */
987 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Jeff Sharkey4dfa6602011-06-13 00:42:03 -0700988 final AppUsageItem app = (AppUsageItem) parent.getItemAtPosition(position);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -0700989 AppDetailsFragment.show(DataUsageSummary.this, app.uid);
Jeff Sharkey8a503642011-06-10 13:31:21 -0700990 }
991 };
992
993 private OnItemSelectedListener mCycleListener = new OnItemSelectedListener() {
994 /** {@inheritDoc} */
995 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
996 final CycleItem cycle = (CycleItem) parent.getItemAtPosition(position);
997 if (cycle instanceof CycleChangeItem) {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -0700998 // show cycle editor; will eventually call setPolicyCycleDay()
999 // when user finishes editing.
1000 CycleEditorFragment.show(DataUsageSummary.this);
1001
1002 // reset spinner to something other than "change cycle..."
1003 mCycleSpinner.setSelection(0);
Jeff Sharkey8a503642011-06-10 13:31:21 -07001004
1005 } else {
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001006 if (LOGD) {
1007 Log.d(TAG, "showing cycle " + cycle + ", start=" + cycle.start + ", end="
1008 + cycle.end + "]");
1009 }
Jeff Sharkey8a503642011-06-10 13:31:21 -07001010
1011 // update chart to show selected cycle, and update detail data
1012 // to match updated sweep bounds.
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001013 mChart.setVisibleRange(cycle.start, cycle.end);
Jeff Sharkey8a503642011-06-10 13:31:21 -07001014
1015 updateDetailData();
1016 }
1017 }
1018
1019 /** {@inheritDoc} */
1020 public void onNothingSelected(AdapterView<?> parent) {
1021 // ignored
1022 }
1023 };
1024
1025 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001026 * Update details based on {@link #mChart} inspection range depending on
1027 * current mode. In network mode, updates {@link #mAdapter} with sorted list
1028 * of applications data usage, and when {@link #isAppDetailMode()} update
1029 * app details.
Jeff Sharkey8a503642011-06-10 13:31:21 -07001030 */
1031 private void updateDetailData() {
1032 if (LOGD) Log.d(TAG, "updateDetailData()");
1033
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001034 final long start = mChart.getInspectStart();
1035 final long end = mChart.getInspectEnd();
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001036 final long now = System.currentTimeMillis();
1037
1038 final Context context = getActivity();
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001039
Jeff Sharkey54d0af52011-08-11 18:26:57 -07001040 NetworkStatsHistory.Entry entry = null;
1041 if (isAppDetailMode() && mDetailHistory != null) {
1042 // bind foreground/background to piechart and labels
1043 entry = mDetailHistoryDefault.getValues(start, end, now, entry);
1044 final long defaultBytes = entry.rxBytes + entry.txBytes;
1045 entry = mDetailHistoryForeground.getValues(start, end, now, entry);
1046 final long foregroundBytes = entry.rxBytes + entry.txBytes;
1047
1048 mAppPieChart.setOriginAngle(175);
1049
1050 mAppPieChart.removeAllSlices();
1051 mAppPieChart.addSlice(foregroundBytes, Color.parseColor("#d88d3a"));
1052 mAppPieChart.addSlice(defaultBytes, Color.parseColor("#666666"));
1053
1054 mAppPieChart.generatePath();
1055
1056 mAppBackground.setText(Formatter.formatFileSize(context, defaultBytes));
1057 mAppForeground.setText(Formatter.formatFileSize(context, foregroundBytes));
1058
1059 // and finally leave with summary data for label below
1060 entry = mDetailHistory.getValues(start, end, now, null);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001061
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001062 getLoaderManager().destroyLoader(LOADER_SUMMARY);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001063
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001064 } else {
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001065 entry = mHistory.getValues(start, end, now, null);
1066
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001067 // kick off loader for detailed stats
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001068 getLoaderManager().restartLoader(LOADER_SUMMARY,
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001069 SummaryForAllUidLoader.buildArgs(mTemplate, start, end), mSummaryForAllUid);
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001070 }
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001071
1072 final long totalBytes = entry != null ? entry.rxBytes + entry.txBytes : 0;
1073 final String totalPhrase = Formatter.formatFileSize(context, totalBytes);
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001074 final String rangePhrase = formatDateRange(context, start, end, false);
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001075
1076 mUsageSummary.setText(
1077 getString(R.string.data_usage_total_during_range, totalPhrase, rangePhrase));
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001078 }
1079
1080 private final LoaderCallbacks<NetworkStats> mSummaryForAllUid = new LoaderCallbacks<
1081 NetworkStats>() {
1082 /** {@inheritDoc} */
1083 public Loader<NetworkStats> onCreateLoader(int id, Bundle args) {
1084 return new SummaryForAllUidLoader(getActivity(), mStatsService, args);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001085 }
1086
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001087 /** {@inheritDoc} */
1088 public void onLoadFinished(Loader<NetworkStats> loader, NetworkStats data) {
1089 mAdapter.bindStats(data);
Jeff Sharkeye2afc0f2011-08-01 15:29:30 -07001090 updateEmptyVisible();
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001091 }
Jeff Sharkeyaa5260e2011-06-14 23:21:59 -07001092
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001093 /** {@inheritDoc} */
1094 public void onLoaderReset(Loader<NetworkStats> loader) {
1095 mAdapter.bindStats(null);
Jeff Sharkeye2afc0f2011-08-01 15:29:30 -07001096 updateEmptyVisible();
1097 }
1098
1099 private void updateEmptyVisible() {
1100 final boolean isEmpty = mAdapter.isEmpty() && !isAppDetailMode();
1101 mEmpty.setVisibility(isEmpty ? View.VISIBLE : View.GONE);
Jeff Sharkey398b18f2011-07-10 18:56:30 -07001102 }
1103 };
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001104
Jeff Sharkeya662e492011-06-18 21:57:06 -07001105 private boolean isMobilePolicySplit() {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001106 final Context context = getActivity();
1107 if (hasMobileRadio(context)) {
1108 final String subscriberId = getActiveSubscriberId(context);
1109 return mPolicyEditor.isMobilePolicySplit(subscriberId);
1110 } else {
1111 return false;
1112 }
Jeff Sharkeya662e492011-06-18 21:57:06 -07001113 }
1114
1115 private void setMobilePolicySplit(boolean split) {
1116 final String subscriberId = getActiveSubscriberId(getActivity());
1117 mPolicyEditor.setMobilePolicySplit(subscriberId, split);
1118 }
1119
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001120 private static String getActiveSubscriberId(Context context) {
1121 final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
1122 Context.TELEPHONY_SERVICE);
1123 return telephony.getSubscriberId();
1124 }
1125
Jeff Sharkey8a503642011-06-10 13:31:21 -07001126 private DataUsageChartListener mChartListener = new DataUsageChartListener() {
1127 /** {@inheritDoc} */
1128 public void onInspectRangeChanged() {
1129 if (LOGD) Log.d(TAG, "onInspectRangeChanged()");
1130 updateDetailData();
1131 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001132
Jeff Sharkey8a503642011-06-10 13:31:21 -07001133 /** {@inheritDoc} */
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001134 public void onWarningChanged() {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001135 setPolicyWarningBytes(mChart.getWarningBytes());
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001136 }
Jeff Sharkey8a503642011-06-10 13:31:21 -07001137
Jeff Sharkey05cc0cc2011-06-12 23:11:24 -07001138 /** {@inheritDoc} */
1139 public void onLimitChanged() {
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001140 setPolicyLimitBytes(mChart.getLimitBytes());
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001141 }
1142 };
1143
1144
1145 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -07001146 * List item that reflects a specific data usage cycle.
1147 */
1148 public static class CycleItem {
1149 public CharSequence label;
1150 public long start;
1151 public long end;
1152
Jeff Sharkey8a503642011-06-10 13:31:21 -07001153 CycleItem(CharSequence label) {
1154 this.label = label;
1155 }
1156
1157 public CycleItem(Context context, long start, long end) {
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001158 this.label = formatDateRange(context, start, end, true);
Jeff Sharkey8a503642011-06-10 13:31:21 -07001159 this.start = start;
1160 this.end = end;
1161 }
1162
Jeff Sharkey8a503642011-06-10 13:31:21 -07001163 @Override
1164 public String toString() {
1165 return label.toString();
1166 }
1167 }
1168
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001169 private static final StringBuilder sBuilder = new StringBuilder(50);
1170 private static final java.util.Formatter sFormatter = new java.util.Formatter(
1171 sBuilder, Locale.getDefault());
1172
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001173 public static String formatDateRange(Context context, long start, long end, boolean utcTime) {
1174 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
1175 final String timezone = utcTime ? TIMEZONE_UTC : null;
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001176
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001177 synchronized (sBuilder) {
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001178 sBuilder.setLength(0);
Jeff Sharkeye2afc0f2011-08-01 15:29:30 -07001179 return DateUtils
1180 .formatDateRange(context, sFormatter, start, end, flags, timezone).toString();
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001181 }
1182 }
1183
Jeff Sharkey8a503642011-06-10 13:31:21 -07001184 /**
1185 * Special-case data usage cycle that triggers dialog to change
1186 * {@link NetworkPolicy#cycleDay}.
1187 */
1188 public static class CycleChangeItem extends CycleItem {
1189 public CycleChangeItem(Context context) {
1190 super(context.getString(R.string.data_usage_change_cycle));
1191 }
1192 }
1193
1194 public static class CycleAdapter extends ArrayAdapter<CycleItem> {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001195 private boolean mChangePossible = false;
1196 private boolean mChangeVisible = false;
1197
1198 private final CycleChangeItem mChangeItem;
1199
Jeff Sharkey8a503642011-06-10 13:31:21 -07001200 public CycleAdapter(Context context) {
1201 super(context, android.R.layout.simple_spinner_item);
1202 setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001203 mChangeItem = new CycleChangeItem(context);
1204 }
1205
1206 public void setChangePossible(boolean possible) {
1207 mChangePossible = possible;
1208 updateChange();
1209 }
1210
1211 public void setChangeVisible(boolean visible) {
1212 mChangeVisible = visible;
1213 updateChange();
1214 }
1215
1216 private void updateChange() {
1217 remove(mChangeItem);
1218 if (mChangePossible && mChangeVisible) {
1219 add(mChangeItem);
1220 }
Jeff Sharkey8a503642011-06-10 13:31:21 -07001221 }
1222 }
1223
Jeff Sharkey4dfa6602011-06-13 00:42:03 -07001224 private static class AppUsageItem implements Comparable<AppUsageItem> {
1225 public int uid;
1226 public long total;
1227
1228 /** {@inheritDoc} */
1229 public int compareTo(AppUsageItem another) {
1230 return Long.compare(another.total, total);
1231 }
1232 }
1233
Jeff Sharkey8a503642011-06-10 13:31:21 -07001234 /**
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001235 * Adapter of applications, sorted by total usage descending.
1236 */
1237 public static class DataUsageAdapter extends BaseAdapter {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001238 private ArrayList<AppUsageItem> mItems = Lists.newArrayList();
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001239 private long mLargest;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001240
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001241 /**
1242 * Bind the given {@link NetworkStats}, or {@code null} to clear list.
1243 */
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001244 public void bindStats(NetworkStats stats) {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001245 mItems.clear();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001246
Jeff Sharkey54d0af52011-08-11 18:26:57 -07001247 final AppUsageItem systemItem = new AppUsageItem();
1248 systemItem.uid = android.os.Process.SYSTEM_UID;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001249
Jeff Sharkey54d0af52011-08-11 18:26:57 -07001250 final SparseArray<AppUsageItem> knownUids = new SparseArray<AppUsageItem>();
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001251
Jeff Sharkey54d0af52011-08-11 18:26:57 -07001252 NetworkStats.Entry entry = null;
1253 final int size = stats != null ? stats.size() : 0;
1254 for (int i = 0; i < size; i++) {
1255 entry = stats.getValues(i, entry);
1256
1257 final int uid = entry.uid;
1258 final boolean isApp = uid >= android.os.Process.FIRST_APPLICATION_UID
1259 && uid <= android.os.Process.LAST_APPLICATION_UID;
1260 if (isApp || uid == TrafficStats.UID_REMOVED) {
1261 AppUsageItem item = knownUids.get(uid);
1262 if (item == null) {
1263 item = new AppUsageItem();
1264 item.uid = uid;
1265 knownUids.put(uid, item);
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001266 mItems.add(item);
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001267 }
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001268
Jeff Sharkey54d0af52011-08-11 18:26:57 -07001269 item.total += entry.rxBytes + entry.txBytes;
1270 } else {
1271 systemItem.total += entry.rxBytes + entry.txBytes;
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001272 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001273 }
1274
Jeff Sharkey54d0af52011-08-11 18:26:57 -07001275 if (systemItem.total > 0) {
1276 mItems.add(systemItem);
1277 }
1278
Jeff Sharkey8a503642011-06-10 13:31:21 -07001279 Collections.sort(mItems);
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001280 mLargest = (mItems.size() > 0) ? mItems.get(0).total : 0;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001281 notifyDataSetChanged();
1282 }
1283
1284 @Override
1285 public int getCount() {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001286 return mItems.size();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001287 }
1288
1289 @Override
1290 public Object getItem(int position) {
Jeff Sharkey8a503642011-06-10 13:31:21 -07001291 return mItems.get(position);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001292 }
1293
1294 @Override
1295 public long getItemId(int position) {
Jeff Sharkeye2afc0f2011-08-01 15:29:30 -07001296 return mItems.get(position).uid;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001297 }
1298
1299 @Override
1300 public View getView(int position, View convertView, ViewGroup parent) {
1301 if (convertView == null) {
1302 convertView = LayoutInflater.from(parent.getContext()).inflate(
Jeff Sharkey52c3f442011-06-23 00:39:38 -07001303 R.layout.data_usage_item, parent, false);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001304 }
1305
1306 final Context context = parent.getContext();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001307
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001308 final ImageView icon = (ImageView) convertView.findViewById(android.R.id.icon);
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001309 final TextView title = (TextView) convertView.findViewById(android.R.id.title);
1310 final TextView summary = (TextView) convertView.findViewById(android.R.id.summary);
1311 final ProgressBar progress = (ProgressBar) convertView.findViewById(
1312 android.R.id.progress);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001313
Jeff Sharkey8a503642011-06-10 13:31:21 -07001314 final AppUsageItem item = mItems.get(position);
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001315 final UidDetail detail = resolveDetailForUid(context, item.uid);
1316
1317 icon.setImageDrawable(detail.icon);
1318 title.setText(detail.label);
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001319 summary.setText(Formatter.formatFileSize(context, item.total));
1320
1321 final int percentTotal = mLargest != 0 ? (int) (item.total * 100 / mLargest) : 0;
1322 progress.setProgress(percentTotal);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001323
1324 return convertView;
1325 }
1326
1327 }
1328
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001329 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001330 * Empty {@link Fragment} that controls display of UID details in
1331 * {@link DataUsageSummary}.
1332 */
1333 public static class AppDetailsFragment extends Fragment {
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001334 private static final String EXTRA_UID = "uid";
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001335
1336 public static void show(DataUsageSummary parent, int uid) {
1337 final Bundle args = new Bundle();
1338 args.putInt(EXTRA_UID, uid);
1339
1340 final AppDetailsFragment fragment = new AppDetailsFragment();
1341 fragment.setArguments(args);
1342 fragment.setTargetFragment(parent, 0);
1343
1344 final FragmentTransaction ft = parent.getFragmentManager().beginTransaction();
1345 ft.add(fragment, TAG_APP_DETAILS);
1346 ft.addToBackStack(TAG_APP_DETAILS);
1347 ft.commit();
1348 }
1349
1350 @Override
1351 public void onStart() {
1352 super.onStart();
1353 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1354 target.mUid = getArguments().getInt(EXTRA_UID);
1355 target.updateBody();
1356 }
1357
1358 @Override
1359 public void onStop() {
1360 super.onStop();
1361 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1362 target.mUid = UID_NONE;
1363 target.updateBody();
1364 }
1365 }
1366
1367 /**
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001368 * Dialog to request user confirmation before setting
1369 * {@link NetworkPolicy#limitBytes}.
1370 */
1371 public static class ConfirmLimitFragment extends DialogFragment {
Jeff Sharkey131f9d62011-08-17 17:08:19 -07001372 private static final String EXTRA_MESSAGE = "message";
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001373 private static final String EXTRA_LIMIT_BYTES = "limitBytes";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001374
1375 public static void show(DataUsageSummary parent) {
Jeff Sharkey131f9d62011-08-17 17:08:19 -07001376 final Resources res = parent.getResources();
1377
1378 final CharSequence message;
1379 final long limitBytes;
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001380
1381 // TODO: customize default limits based on network template
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001382 final String currentTab = parent.mCurrentTab;
1383 if (TAB_3G.equals(currentTab)) {
Jeff Sharkey131f9d62011-08-17 17:08:19 -07001384 message = buildDialogMessage(res, R.string.data_usage_tab_3g);
1385 limitBytes = 5 * GB_IN_BYTES;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001386 } else if (TAB_4G.equals(currentTab)) {
Jeff Sharkey131f9d62011-08-17 17:08:19 -07001387 message = buildDialogMessage(res, R.string.data_usage_tab_4g);
1388 limitBytes = 5 * GB_IN_BYTES;
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001389 } else if (TAB_MOBILE.equals(currentTab)) {
Jeff Sharkey131f9d62011-08-17 17:08:19 -07001390 message = buildDialogMessage(res, R.string.data_usage_list_mobile);
1391 limitBytes = 5 * GB_IN_BYTES;
1392 } else if (TAB_WIFI.equals(currentTab)) {
1393 message = buildDialogMessage(res, R.string.data_usage_tab_wifi);
1394 limitBytes = 5 * GB_IN_BYTES;
1395 } else {
1396 throw new IllegalArgumentException("unknown current tab: " + currentTab);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001397 }
1398
Jeff Sharkey131f9d62011-08-17 17:08:19 -07001399 final Bundle args = new Bundle();
1400 args.putCharSequence(EXTRA_MESSAGE, message);
1401 args.putLong(EXTRA_LIMIT_BYTES, limitBytes);
1402
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001403 final ConfirmLimitFragment dialog = new ConfirmLimitFragment();
1404 dialog.setArguments(args);
1405 dialog.setTargetFragment(parent, 0);
1406 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_LIMIT);
1407 }
1408
Jeff Sharkey131f9d62011-08-17 17:08:19 -07001409 private static CharSequence buildDialogMessage(Resources res, int networkResId) {
1410 return res.getString(R.string.data_usage_limit_dialog, res.getString(networkResId));
1411 }
1412
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001413 @Override
1414 public Dialog onCreateDialog(Bundle savedInstanceState) {
1415 final Context context = getActivity();
1416
Jeff Sharkey131f9d62011-08-17 17:08:19 -07001417 final CharSequence message = getArguments().getCharSequence(EXTRA_MESSAGE);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001418 final long limitBytes = getArguments().getLong(EXTRA_LIMIT_BYTES);
1419
1420 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1421 builder.setTitle(R.string.data_usage_limit_dialog_title);
Jeff Sharkey131f9d62011-08-17 17:08:19 -07001422 builder.setMessage(message);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001423
1424 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1425 public void onClick(DialogInterface dialog, int which) {
1426 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1427 if (target != null) {
1428 target.setPolicyLimitBytes(limitBytes);
1429 }
1430 }
1431 });
1432
1433 return builder.create();
1434 }
1435 }
1436
1437 /**
1438 * Dialog to edit {@link NetworkPolicy#cycleDay}.
1439 */
1440 public static class CycleEditorFragment extends DialogFragment {
Jeff Sharkey2412b0f2011-07-17 20:31:40 -07001441 private static final String EXTRA_CYCLE_DAY = "cycleDay";
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001442
1443 public static void show(DataUsageSummary parent) {
Jeff Sharkey131f9d62011-08-17 17:08:19 -07001444 final NetworkPolicy policy = parent.mPolicyEditor.getPolicy(parent.mTemplate, false);
Jeff Sharkey4c72ae52011-06-14 15:01:18 -07001445 final Bundle args = new Bundle();
1446 args.putInt(CycleEditorFragment.EXTRA_CYCLE_DAY, policy.cycleDay);
1447
1448 final CycleEditorFragment dialog = new CycleEditorFragment();
1449 dialog.setArguments(args);
1450 dialog.setTargetFragment(parent, 0);
1451 dialog.show(parent.getFragmentManager(), TAG_CYCLE_EDITOR);
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);
1459 final LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext());
1460
1461 final View view = dialogInflater.inflate(R.layout.data_usage_cycle_editor, null, false);
1462 final NumberPicker cycleDayPicker = (NumberPicker) view.findViewById(R.id.cycle_day);
1463
1464 final int oldCycleDay = getArguments().getInt(EXTRA_CYCLE_DAY, 1);
1465
1466 cycleDayPicker.setMinValue(1);
1467 cycleDayPicker.setMaxValue(31);
1468 cycleDayPicker.setValue(oldCycleDay);
1469 cycleDayPicker.setWrapSelectorWheel(true);
1470
1471 builder.setTitle(R.string.data_usage_cycle_editor_title);
1472 builder.setView(view);
1473
1474 builder.setPositiveButton(R.string.data_usage_cycle_editor_positive,
1475 new DialogInterface.OnClickListener() {
1476 public void onClick(DialogInterface dialog, int which) {
1477 final int cycleDay = cycleDayPicker.getValue();
1478 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1479 if (target != null) {
1480 target.setPolicyCycleDay(cycleDay);
1481 }
1482 }
1483 });
1484
1485 return builder.create();
1486 }
1487 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001488
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001489 /**
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001490 * Dialog to request user confirmation before setting
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001491 * {@link Settings.Secure#DATA_ROAMING}.
1492 */
1493 public static class ConfirmDataRoamingFragment extends DialogFragment {
1494 public static void show(DataUsageSummary parent) {
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001495 final ConfirmDataRoamingFragment dialog = new ConfirmDataRoamingFragment();
1496 dialog.setTargetFragment(parent, 0);
1497 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_ROAMING);
1498 }
1499
1500 @Override
1501 public Dialog onCreateDialog(Bundle savedInstanceState) {
1502 final Context context = getActivity();
1503
1504 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
1505 builder.setTitle(R.string.roaming_reenable_title);
1506 builder.setMessage(R.string.roaming_warning);
1507
1508 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1509 public void onClick(DialogInterface dialog, int which) {
1510 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1511 if (target != null) {
1512 target.setDataRoaming(true);
1513 }
1514 }
1515 });
1516 builder.setNegativeButton(android.R.string.cancel, null);
1517
1518 return builder.create();
1519 }
1520 }
1521
1522 /**
1523 * Dialog to request user confirmation before setting
Jeff Sharkeyd360e5e2011-07-26 19:30:26 -07001524 * {@link INetworkPolicyManager#setRestrictBackground(boolean)}.
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001525 */
1526 public static class ConfirmRestrictFragment extends DialogFragment {
1527 public static void show(DataUsageSummary parent) {
1528 final ConfirmRestrictFragment dialog = new ConfirmRestrictFragment();
1529 dialog.setTargetFragment(parent, 0);
1530 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_RESTRICT);
1531 }
1532
1533 @Override
1534 public Dialog onCreateDialog(Bundle savedInstanceState) {
1535 final Context context = getActivity();
1536
1537 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001538 builder.setTitle(R.string.data_usage_restrict_background_title);
Jeff Sharkey30dde0f2011-08-17 15:08:12 -07001539
1540 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1541 if (target != null) {
1542 final CharSequence limitedNetworks = target.buildLimitedNetworksList();
1543 builder.setMessage(
1544 getString(R.string.data_usage_restrict_background, limitedNetworks));
1545 }
Jeff Sharkey9fab0da2011-07-09 17:52:31 -07001546
1547 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1548 public void onClick(DialogInterface dialog, int which) {
1549 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1550 if (target != null) {
1551 target.setRestrictBackground(true);
1552 }
1553 }
1554 });
1555 builder.setNegativeButton(android.R.string.cancel, null);
1556
1557 return builder.create();
1558 }
1559 }
1560
1561 /**
1562 * Dialog to request user confirmation before setting
1563 * {@link #POLICY_REJECT_METERED_BACKGROUND}.
1564 */
1565 public static class ConfirmAppRestrictFragment extends DialogFragment {
1566 public static void show(DataUsageSummary parent) {
1567 final ConfirmAppRestrictFragment dialog = new ConfirmAppRestrictFragment();
1568 dialog.setTargetFragment(parent, 0);
1569 dialog.show(parent.getFragmentManager(), TAG_CONFIRM_APP_RESTRICT);
1570 }
1571
1572 @Override
1573 public Dialog onCreateDialog(Bundle savedInstanceState) {
1574 final Context context = getActivity();
1575
1576 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001577 builder.setTitle(R.string.data_usage_app_restrict_dialog_title);
1578 builder.setMessage(R.string.data_usage_app_restrict_dialog);
1579
1580 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
1581 public void onClick(DialogInterface dialog, int which) {
1582 final DataUsageSummary target = (DataUsageSummary) getTargetFragment();
1583 if (target != null) {
1584 target.setAppRestrictBackground(true);
1585 }
1586 }
1587 });
1588 builder.setNegativeButton(android.R.string.cancel, null);
1589
1590 return builder.create();
1591 }
1592 }
1593
1594 /**
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001595 * Compute default tab that should be selected, based on
1596 * {@link NetworkPolicyManager#EXTRA_NETWORK_TEMPLATE} extra.
1597 */
1598 private static String computeTabFromIntent(Intent intent) {
Jeff Sharkey271ec8a2011-07-20 16:59:16 -07001599 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
1600 if (template == null) return null;
1601
1602 switch (template.getMatchRule()) {
Jeff Sharkeya662e492011-06-18 21:57:06 -07001603 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001604 return TAB_3G;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001605 case MATCH_MOBILE_4G:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001606 return TAB_4G;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001607 case MATCH_MOBILE_ALL:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001608 return TAB_MOBILE;
Jeff Sharkeya662e492011-06-18 21:57:06 -07001609 case MATCH_WIFI:
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001610 return TAB_WIFI;
1611 default:
1612 return null;
1613 }
1614 }
1615
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001616 public static class UidDetail {
1617 public CharSequence label;
1618 public CharSequence[] detailLabels;
1619 public Drawable icon;
1620 }
1621
Jeff Sharkeydd6efe12011-06-15 10:31:41 -07001622 /**
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001623 * Resolve best descriptive label for the given UID.
1624 */
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001625 public static UidDetail resolveDetailForUid(Context context, int uid) {
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001626 final Resources res = context.getResources();
1627 final PackageManager pm = context.getPackageManager();
1628
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001629 final UidDetail detail = new UidDetail();
1630 detail.label = pm.getNameForUid(uid);
1631 detail.icon = pm.getDefaultActivityIcon();
1632
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001633 // handle special case labels
1634 switch (uid) {
1635 case android.os.Process.SYSTEM_UID:
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001636 detail.label = res.getString(R.string.process_kernel_label);
1637 detail.icon = pm.getDefaultActivityIcon();
1638 return detail;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001639 case TrafficStats.UID_REMOVED:
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001640 detail.label = res.getString(R.string.data_usage_uninstalled_apps);
1641 detail.icon = pm.getDefaultActivityIcon();
1642 return detail;
Jeff Sharkey518bc9d2011-07-12 20:20:46 -07001643 }
1644
1645 // otherwise fall back to using packagemanager labels
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001646 final String[] packageNames = pm.getPackagesForUid(uid);
1647 final int length = packageNames != null ? packageNames.length : 0;
1648
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001649 try {
1650 if (length == 1) {
1651 final ApplicationInfo info = pm.getApplicationInfo(packageNames[0], 0);
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001652 detail.label = info.loadLabel(pm).toString();
1653 detail.icon = info.loadIcon(pm);
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001654 } else if (length > 1) {
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001655 detail.detailLabels = new CharSequence[length];
1656 for (int i = 0; i < length; i++) {
1657 final String packageName = packageNames[i];
1658 final PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
1659 final ApplicationInfo appInfo = pm.getApplicationInfo(packageName, 0);
1660
1661 detail.detailLabels[i] = appInfo.loadLabel(pm).toString();
1662 if (packageInfo.sharedUserLabel != 0) {
1663 detail.label = pm.getText(packageName, packageInfo.sharedUserLabel,
1664 packageInfo.applicationInfo).toString();
1665 detail.icon = appInfo.loadIcon(pm);
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001666 }
1667 }
1668 }
1669 } catch (NameNotFoundException e) {
1670 }
1671
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001672 if (TextUtils.isEmpty(detail.label)) {
1673 detail.label = Integer.toString(uid);
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001674 }
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001675 return detail;
Jeff Sharkey8e911d72011-06-14 22:41:21 -07001676 }
1677
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001678 /**
1679 * Test if device has a mobile data radio.
1680 */
1681 private static boolean hasMobileRadio(Context context) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001682 if (TEST_RADIOS) {
1683 return SystemProperties.get(TEST_RADIOS_PROP).contains("mobile");
1684 }
1685
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001686 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1687 Context.CONNECTIVITY_SERVICE);
1688
1689 // mobile devices should have MOBILE network tracker regardless of
1690 // connection status.
1691 return conn.getNetworkInfo(TYPE_MOBILE) != null;
1692 }
1693
1694 /**
1695 * Test if device has a mobile 4G data radio.
1696 */
1697 private static boolean hasMobile4gRadio(Context context) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001698 if (TEST_RADIOS) {
1699 return SystemProperties.get(TEST_RADIOS_PROP).contains("4g");
1700 }
1701
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001702 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1703 Context.CONNECTIVITY_SERVICE);
1704 final TelephonyManager telephony = (TelephonyManager) context.getSystemService(
1705 Context.TELEPHONY_SERVICE);
1706
1707 // WiMAX devices should have WiMAX network tracker regardless of
1708 // connection status.
1709 final boolean hasWimax = conn.getNetworkInfo(TYPE_WIMAX) != null;
1710 final boolean hasLte = telephony.getLteOnCdmaMode() == Phone.LTE_ON_CDMA_TRUE;
1711 return hasWimax || hasLte;
1712 }
1713
1714 /**
1715 * Test if device has a Wi-Fi data radio.
1716 */
1717 private static boolean hasWifiRadio(Context context) {
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001718 if (TEST_RADIOS) {
1719 return SystemProperties.get(TEST_RADIOS_PROP).contains("wifi");
1720 }
1721
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001722 return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI);
1723 }
1724
1725 /**
Jeff Sharkey9549e9f2011-07-14 20:01:13 -07001726 * Test if device has an ethernet network connection.
1727 */
1728 private static boolean hasEthernet(Context context) {
1729 if (TEST_RADIOS) {
1730 return SystemProperties.get(TEST_RADIOS_PROP).contains("ethernet");
1731 }
1732
1733 final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(
1734 Context.CONNECTIVITY_SERVICE);
1735 return conn.getNetworkInfo(TYPE_ETHERNET) != null;
1736 }
1737
1738 /**
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001739 * Inflate a {@link Preference} style layout, adding the given {@link View}
1740 * widget into {@link android.R.id#widget_frame}.
1741 */
1742 private static View inflatePreference(LayoutInflater inflater, ViewGroup root, View widget) {
1743 final View view = inflater.inflate(R.layout.preference, root, false);
1744 final LinearLayout widgetFrame = (LinearLayout) view.findViewById(
1745 android.R.id.widget_frame);
1746 widgetFrame.addView(widget, new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
1747 return view;
1748 }
1749
Jeff Sharkeyd39c6e42011-08-04 21:17:23 -07001750 private static View inflateAppTitle(
1751 LayoutInflater inflater, ViewGroup root, CharSequence label) {
1752 final TextView view = (TextView) inflater.inflate(
1753 R.layout.data_usage_app_title, root, false);
1754 view.setText(label);
1755 return view;
1756 }
1757
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001758 /**
Jeff Sharkey30dde0f2011-08-17 15:08:12 -07001759 * Build string describing currently limited networks, which defines when
1760 * background data is restricted.
1761 */
1762 private CharSequence buildLimitedNetworksList() {
1763 final Context context = getActivity();
1764 final String subscriberId = getActiveSubscriberId(context);
1765
1766 // build combined list of all limited networks
1767 final ArrayList<CharSequence> limited = Lists.newArrayList();
1768 if (mPolicyEditor.hasLimitedPolicy(buildTemplateMobileAll(subscriberId))) {
1769 limited.add(getText(R.string.data_usage_list_mobile));
1770 }
1771 if (mPolicyEditor.hasLimitedPolicy(buildTemplateMobile3gLower(subscriberId))) {
1772 limited.add(getText(R.string.data_usage_tab_3g));
1773 }
1774 if (mPolicyEditor.hasLimitedPolicy(buildTemplateMobile4g(subscriberId))) {
1775 limited.add(getText(R.string.data_usage_tab_4g));
1776 }
1777 if (mPolicyEditor.hasLimitedPolicy(buildTemplateWifi())) {
1778 limited.add(getText(R.string.data_usage_tab_wifi));
1779 }
1780 if (mPolicyEditor.hasLimitedPolicy(buildTemplateEthernet())) {
1781 limited.add(getText(R.string.data_usage_tab_ethernet));
1782 }
1783
1784 // handle case where no networks limited
1785 if (limited.isEmpty()) {
1786 limited.add(getText(R.string.data_usage_list_none));
1787 }
1788
1789 return TextUtils.join(limited);
1790 }
1791
1792 /**
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001793 * Set {@link android.R.id#title} for a preference view inflated with
Jeff Sharkey52c3f442011-06-23 00:39:38 -07001794 * {@link #inflatePreference(LayoutInflater, ViewGroup, View)}.
Jeff Sharkey29d56b32011-06-20 17:06:52 -07001795 */
1796 private static void setPreferenceTitle(View parent, int resId) {
1797 final TextView title = (TextView) parent.findViewById(android.R.id.title);
1798 title.setText(resId);
1799 }
1800
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001801 /**
1802 * Set {@link android.R.id#summary} for a preference view inflated with
1803 * {@link #inflatePreference(LayoutInflater, ViewGroup, View)}.
1804 */
Jeff Sharkey30dde0f2011-08-17 15:08:12 -07001805 private static void setPreferenceSummary(View parent, CharSequence string) {
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001806 final TextView summary = (TextView) parent.findViewById(android.R.id.summary);
1807 summary.setVisibility(View.VISIBLE);
Jeff Sharkey30dde0f2011-08-17 15:08:12 -07001808 summary.setText(string);
Jeff Sharkeyf54f4352011-06-23 22:15:54 -07001809 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -07001810}