blob: e27227f301b60a8842e191ea5dff5e88e0eca554 [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 Sharkey8a503642011-06-10 13:31:21 -070019import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
20import static android.net.NetworkPolicyManager.computeNextCycleBoundary;
21import static android.net.TrafficStats.TEMPLATE_MOBILE_3G_LOWER;
22import static android.net.TrafficStats.TEMPLATE_MOBILE_4G;
23import static android.net.TrafficStats.TEMPLATE_MOBILE_ALL;
24import static android.net.TrafficStats.TEMPLATE_WIFI;
25import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070026
27import android.app.Fragment;
28import android.content.Context;
29import android.content.pm.PackageManager;
Jeff Sharkey8a503642011-06-10 13:31:21 -070030import android.net.INetworkPolicyManager;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070031import android.net.INetworkStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -070032import android.net.NetworkPolicy;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070033import android.net.NetworkStats;
34import android.net.NetworkStatsHistory;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070035import android.os.Bundle;
36import android.os.RemoteException;
37import android.os.ServiceManager;
Jeff Sharkey8a503642011-06-10 13:31:21 -070038import android.preference.CheckBoxPreference;
39import android.preference.Preference;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070040import android.text.format.DateUtils;
41import android.text.format.Formatter;
Jeff Sharkey8a503642011-06-10 13:31:21 -070042import android.text.format.Time;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070043import android.util.Log;
44import android.view.LayoutInflater;
Jeff Sharkey8a503642011-06-10 13:31:21 -070045import android.view.Menu;
46import android.view.MenuInflater;
47import android.view.MenuItem;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070048import android.view.View;
Jeff Sharkey8a503642011-06-10 13:31:21 -070049import android.view.View.OnClickListener;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070050import android.view.ViewGroup;
Jeff Sharkey8a503642011-06-10 13:31:21 -070051import android.widget.AbsListView;
52import android.widget.AdapterView;
53import android.widget.AdapterView.OnItemClickListener;
54import android.widget.AdapterView.OnItemSelectedListener;
55import android.widget.ArrayAdapter;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070056import android.widget.BaseAdapter;
Jeff Sharkey8a503642011-06-10 13:31:21 -070057import android.widget.LinearLayout;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070058import android.widget.ListView;
Jeff Sharkey8a503642011-06-10 13:31:21 -070059import android.widget.Spinner;
60import android.widget.TabHost;
61import android.widget.TabHost.OnTabChangeListener;
62import android.widget.TabHost.TabContentFactory;
63import android.widget.TabHost.TabSpec;
64import android.widget.TabWidget;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070065import android.widget.TextView;
66
Jeff Sharkey8a503642011-06-10 13:31:21 -070067import com.android.settings.widget.DataUsageChartView;
68import com.android.settings.widget.DataUsageChartView.DataUsageChartListener;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070069import com.google.android.collect.Lists;
70
71import java.util.ArrayList;
Jeff Sharkey8a503642011-06-10 13:31:21 -070072import java.util.Arrays;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070073import java.util.Collections;
Jeff Sharkey8a503642011-06-10 13:31:21 -070074import java.util.Locale;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070075
76public class DataUsageSummary extends Fragment {
77 private static final String TAG = "DataUsage";
Jeff Sharkey8a503642011-06-10 13:31:21 -070078 private static final boolean LOGD = true;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070079
Jeff Sharkey8a503642011-06-10 13:31:21 -070080 private static final int TEMPLATE_INVALID = -1;
81
82 private static final String TAB_3G = "3g";
83 private static final String TAB_4G = "4g";
84 private static final String TAB_MOBILE = "mobile";
85 private static final String TAB_WIFI = "wifi";
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070086
87 private static final long KB_IN_BYTES = 1024;
88 private static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
89 private static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
90
91 private INetworkStatsService mStatsService;
Jeff Sharkey8a503642011-06-10 13:31:21 -070092 private INetworkPolicyManager mPolicyService;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070093
Jeff Sharkey8a503642011-06-10 13:31:21 -070094 private TabHost mTabHost;
95 private TabWidget mTabWidget;
96 private ListView mListView;
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -070097 private DataUsageAdapter mAdapter;
98
Jeff Sharkey8a503642011-06-10 13:31:21 -070099 private View mHeader;
100 private LinearLayout mSwitches;
101
102 private CheckBoxPreference mDataEnabled;
103 private CheckBoxPreference mDisableAtLimit;
104 private View mDataEnabledView;
105 private View mDisableAtLimitView;
106
107 private DataUsageChartView mChart;
108
109 private Spinner mCycleSpinner;
110 private CycleAdapter mCycleAdapter;
111
112 private boolean mSplit4G = false;
113 private boolean mShowWifi = false;
114
115 private int mTemplate = TEMPLATE_INVALID;
116
117 private NetworkPolicy mPolicy;
118 private NetworkStatsHistory mHistory;
119
120 // TODO: policy service should always provide valid stub policy
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700121
122 @Override
Jeff Sharkey8a503642011-06-10 13:31:21 -0700123 public void onCreate(Bundle savedInstanceState) {
124 super.onCreate(savedInstanceState);
125 setHasOptionsMenu(true);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700126
127 mStatsService = INetworkStatsService.Stub.asInterface(
128 ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
Jeff Sharkey8a503642011-06-10 13:31:21 -0700129 mPolicyService = INetworkPolicyManager.Stub.asInterface(
130 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
131 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700132
Jeff Sharkey8a503642011-06-10 13:31:21 -0700133 @Override
134 public View onCreateView(LayoutInflater inflater, ViewGroup container,
135 Bundle savedInstanceState) {
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700136
Jeff Sharkey8a503642011-06-10 13:31:21 -0700137 final Context context = inflater.getContext();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700138 final View view = inflater.inflate(R.layout.data_usage_summary, container, false);
139
Jeff Sharkey8a503642011-06-10 13:31:21 -0700140 mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
141 mTabWidget = (TabWidget) view.findViewById(android.R.id.tabs);
142 mListView = (ListView) view.findViewById(android.R.id.list);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700143
Jeff Sharkey8a503642011-06-10 13:31:21 -0700144 mTabHost.setup();
145 mTabHost.setOnTabChangedListener(mTabListener);
146
147 mHeader = inflater.inflate(R.layout.data_usage_header, mListView, false);
148 mListView.addHeaderView(mHeader, null, false);
149
150 mDataEnabled = new CheckBoxPreference(context);
151 mDisableAtLimit = new CheckBoxPreference(context);
152
153 // kick refresh once to force-create views
154 refreshPreferenceViews();
155
156 // TODO: remove once thin preferences are supported (48dip)
157 mDataEnabledView.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, 72));
158 mDisableAtLimitView.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, 72));
159
160 mDataEnabledView.setOnClickListener(mDataEnabledListener);
161 mDisableAtLimitView.setOnClickListener(mDisableAtLimitListener);
162
163 mSwitches = (LinearLayout) mHeader.findViewById(R.id.switches);
164 mSwitches.addView(mDataEnabledView);
165 mSwitches.addView(mDisableAtLimitView);
166
167 mCycleSpinner = (Spinner) mHeader.findViewById(R.id.cycles);
168 mCycleAdapter = new CycleAdapter(context);
169 mCycleSpinner.setAdapter(mCycleAdapter);
170 mCycleSpinner.setOnItemSelectedListener(mCycleListener);
171
172 mChart = new DataUsageChartView(context);
173 mChart.setListener(mChartListener);
174 mChart.setLayoutParams(new AbsListView.LayoutParams(MATCH_PARENT, 350));
175 mListView.addHeaderView(mChart, null, false);
176
177 mAdapter = new DataUsageAdapter();
178 mListView.setOnItemClickListener(mListListener);
179 mListView.setAdapter(mAdapter);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700180
181 return view;
182 }
183
184 @Override
185 public void onResume() {
186 super.onResume();
187
Jeff Sharkey8a503642011-06-10 13:31:21 -0700188 // this kicks off chain reaction which creates tabs, binds the body to
189 // selected network, and binds chart, cycles and detail list.
190 updateTabs();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700191 }
192
Jeff Sharkey8a503642011-06-10 13:31:21 -0700193 @Override
194 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
195 inflater.inflate(R.menu.data_usage, menu);
196 }
197
198 @Override
199 public boolean onOptionsItemSelected(MenuItem item) {
200 // TODO: persist checked-ness of options to restore tabs later
201
202 switch (item.getItemId()) {
203 case R.id.action_split_4g: {
204 mSplit4G = !item.isChecked();
205 item.setChecked(mSplit4G);
206 updateTabs();
207 return true;
208 }
209 case R.id.action_show_wifi: {
210 mShowWifi = !item.isChecked();
211 item.setChecked(mShowWifi);
212 updateTabs();
213 return true;
214 }
215 }
216 return false;
217 }
218
219 /**
220 * Rebuild all tabs based on {@link #mSplit4G} and {@link #mShowWifi},
221 * hiding the tabs entirely when applicable. Selects first tab, and kicks
222 * off a full rebind of body contents.
223 */
224 private void updateTabs() {
225 // TODO: persist/restore if user wants mobile split, or wifi visibility
226
227 final boolean tabsVisible = mSplit4G || mShowWifi;
228 mTabWidget.setVisibility(tabsVisible ? View.VISIBLE : View.GONE);
229 mTabHost.clearAllTabs();
230
231 if (mSplit4G) {
232 mTabHost.addTab(buildTabSpec(TAB_3G, R.string.data_usage_tab_3g));
233 mTabHost.addTab(buildTabSpec(TAB_4G, R.string.data_usage_tab_4g));
234 }
235
236 if (mShowWifi) {
237 if (!mSplit4G) {
238 mTabHost.addTab(buildTabSpec(TAB_MOBILE, R.string.data_usage_tab_mobile));
239 }
240 mTabHost.addTab(buildTabSpec(TAB_WIFI, R.string.data_usage_tab_wifi));
241 }
242
243 if (mTabWidget.getTabCount() > 0) {
244 // select first tab, which will kick off updateBody()
245 mTabHost.setCurrentTab(0);
246 } else {
247 // no tabs shown; update body manually
248 updateBody();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700249 }
250 }
251
Jeff Sharkey8a503642011-06-10 13:31:21 -0700252 /**
253 * Factory that provide empty {@link View} to make {@link TabHost} happy.
254 */
255 private TabContentFactory mEmptyTabContent = new TabContentFactory() {
256 /** {@inheritDoc} */
257 public View createTabContent(String tag) {
258 return new View(mTabHost.getContext());
259 }
260 };
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700261
Jeff Sharkey8a503642011-06-10 13:31:21 -0700262 /**
263 * Build {@link TabSpec} with thin indicator, and empty content.
264 */
265 private TabSpec buildTabSpec(String tag, int titleRes) {
266 final LayoutInflater inflater = LayoutInflater.from(mTabWidget.getContext());
267 final View indicator = inflater.inflate(
268 R.layout.tab_indicator_thin_holo, mTabWidget, false);
269 final TextView title = (TextView) indicator.findViewById(android.R.id.title);
270 title.setText(titleRes);
271 return mTabHost.newTabSpec(tag).setIndicator(indicator).setContent(mEmptyTabContent);
272 }
273
274 private OnTabChangeListener mTabListener = new OnTabChangeListener() {
275 /** {@inheritDoc} */
276 public void onTabChanged(String tabId) {
277 // user changed tab; update body
278 updateBody();
279 }
280 };
281
282 /**
283 * Update body content based on current tab. Loads
284 * {@link NetworkStatsHistory} and {@link NetworkPolicy} from system, and
285 * binds them to visible controls.
286 */
287 private void updateBody() {
288 final String tabTag = mTabHost.getCurrentTabTag();
289 final String currentTab = tabTag != null ? tabTag : TAB_MOBILE;
290
291 if (LOGD) Log.d(TAG, "updateBody() with currentTab=" + currentTab);
292
293 if (TAB_WIFI.equals(currentTab)) {
294 // wifi doesn't have any controls
295 mDataEnabledView.setVisibility(View.GONE);
296 mDisableAtLimitView.setVisibility(View.GONE);
297 mTemplate = TEMPLATE_WIFI;
298
299 } else {
300 // make sure we show for non-wifi
301 mDataEnabledView.setVisibility(View.VISIBLE);
302 mDisableAtLimitView.setVisibility(View.VISIBLE);
303 }
304
305 if (TAB_MOBILE.equals(currentTab)) {
306 mDataEnabled.setTitle(R.string.data_usage_enable_mobile);
307 mDisableAtLimit.setTitle(R.string.data_usage_disable_mobile_limit);
308 mTemplate = TEMPLATE_MOBILE_ALL;
309
310 } else if (TAB_3G.equals(currentTab)) {
311 mDataEnabled.setTitle(R.string.data_usage_enable_3g);
312 mDisableAtLimit.setTitle(R.string.data_usage_disable_3g_limit);
313 mTemplate = TEMPLATE_MOBILE_3G_LOWER;
314
315 } else if (TAB_4G.equals(currentTab)) {
316 mDataEnabled.setTitle(R.string.data_usage_enable_4g);
317 mDisableAtLimit.setTitle(R.string.data_usage_disable_4g_limit);
318 mTemplate = TEMPLATE_MOBILE_4G;
319
320 }
321
322 // TODO: populate checkbox based on radio preferences
323 mDataEnabled.setChecked(true);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700324
325 try {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700326 // load policy and stats for current template
327 mPolicy = mPolicyService.getNetworkPolicy(mTemplate, null);
328 mHistory = mStatsService.getHistoryForNetwork(mTemplate);
329 } catch (RemoteException e) {
330 // since we can't do much without policy or history, and we don't
331 // want to leave with half-baked UI, we bail hard.
332 throw new RuntimeException("problem reading network policy or stats", e);
333 }
334
335 // TODO: eventually service will always provide stub policy
336 if (mPolicy == null) {
337 mPolicy = new NetworkPolicy(1, 4 * GB_IN_BYTES, -1);
338 }
339
340 // bind chart to historical stats
341 mChart.bindNetworkPolicy(mPolicy);
342 mChart.bindNetworkStats(mHistory);
343
344 // generate cycle list based on policy and available history
345 updateCycleList();
346
347 // reflect policy limit in checkbox
348 mDisableAtLimit.setChecked(mPolicy.limitBytes != -1);
349
350 // force scroll to top of body
351 mListView.smoothScrollToPosition(0);
352
353 // kick preference views so they rebind from changes above
354 refreshPreferenceViews();
355 }
356
357 /**
358 * Return full time bounds (earliest and latest time recorded) of the given
359 * {@link NetworkStatsHistory}.
360 */
361 private static long[] getHistoryBounds(NetworkStatsHistory history) {
362 final long currentTime = System.currentTimeMillis();
363
364 long start = currentTime;
365 long end = currentTime;
366 if (history.bucketCount > 0) {
367 start = history.bucketStart[0];
368 end = history.bucketStart[history.bucketCount - 1];
369 }
370
371 return new long[] { start, end };
372 }
373
374 /**
375 * Rebuild {@link #mCycleAdapter} based on {@link NetworkPolicy#cycleDay}
376 * and available {@link NetworkStatsHistory} data. Always selects the newest
377 * item, updating the inspection range on {@link #mChart}.
378 */
379 private void updateCycleList() {
380 mCycleAdapter.clear();
381
382 final Context context = mCycleSpinner.getContext();
383
384 final long[] bounds = getHistoryBounds(mHistory);
385 final long historyStart = bounds[0];
386 final long historyEnd = bounds[1];
387
388 // find the next cycle boundary
389 long cycleEnd = computeNextCycleBoundary(historyEnd, mPolicy);
390
391 int guardCount = 0;
392
393 // walk backwards, generating all valid cycle ranges
394 while (cycleEnd > historyStart) {
395 final long cycleStart = computeLastCycleBoundary(cycleEnd, mPolicy);
396 Log.d(TAG, "generating cs=" + cycleStart + " to ce=" + cycleEnd + " waiting for hs="
397 + historyStart);
398 mCycleAdapter.add(new CycleItem(context, cycleStart, cycleEnd));
399 cycleEnd = cycleStart;
400
401 // TODO: remove this guard once we have better testing
402 if (guardCount++ > 50) {
403 Log.wtf(TAG, "stuck generating ranges for bounds=" + Arrays.toString(bounds)
404 + " and policy=" + mPolicy);
405 }
406 }
407
408 // one last cycle entry to change date
409 mCycleAdapter.add(new CycleChangeItem(context));
410
411 // force pick the current cycle (first item)
412 mCycleSpinner.setSelection(0);
413 mCycleListener.onItemSelected(mCycleSpinner, null, 0, 0);
414 }
415
416 /**
417 * Force rebind of hijacked {@link Preference} views.
418 */
419 private void refreshPreferenceViews() {
420 mDataEnabledView = mDataEnabled.getView(mDataEnabledView, mListView);
421 mDisableAtLimitView = mDisableAtLimit.getView(mDisableAtLimitView, mListView);
422 }
423
424 private OnClickListener mDataEnabledListener = new OnClickListener() {
425 /** {@inheritDoc} */
426 public void onClick(View v) {
427 mDataEnabled.setChecked(!mDataEnabled.isChecked());
428 refreshPreferenceViews();
429
430 // TODO: wire up to telephony to enable/disable radios
431 }
432 };
433
434 private OnClickListener mDisableAtLimitListener = new OnClickListener() {
435 /** {@inheritDoc} */
436 public void onClick(View v) {
437 final boolean disableAtLimit = !mDisableAtLimit.isChecked();
438 mDisableAtLimit.setChecked(disableAtLimit);
439 refreshPreferenceViews();
440
441 // TODO: push updated policy to service
442 // TODO: show interstitial warning dialog to user
443 final long limitBytes = disableAtLimit ? 5 * GB_IN_BYTES : -1;
444 mPolicy = new NetworkPolicy(mPolicy.cycleDay, mPolicy.warningBytes, limitBytes);
445 mChart.bindNetworkPolicy(mPolicy);
446 }
447 };
448
449 private OnItemClickListener mListListener = new OnItemClickListener() {
450 /** {@inheritDoc} */
451 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
452 final Object object = parent.getItemAtPosition(position);
453
454 // TODO: show app details
455 Log.d(TAG, "showing app details for " + object);
456 }
457 };
458
459 private OnItemSelectedListener mCycleListener = new OnItemSelectedListener() {
460 /** {@inheritDoc} */
461 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
462 final CycleItem cycle = (CycleItem) parent.getItemAtPosition(position);
463 if (cycle instanceof CycleChangeItem) {
464 // TODO: show "define cycle" dialog
465 // also reset back to first cycle
466 Log.d(TAG, "CHANGE CYCLE DIALOG!!");
467
468 } else {
469 if (LOGD) Log.d(TAG, "shoiwng cycle " + cycle);
470
471 // update chart to show selected cycle, and update detail data
472 // to match updated sweep bounds.
473 final long[] bounds = getHistoryBounds(mHistory);
474 mChart.setVisibleRange(cycle.start, cycle.end, bounds[1]);
475
476 updateDetailData();
477 }
478 }
479
480 /** {@inheritDoc} */
481 public void onNothingSelected(AdapterView<?> parent) {
482 // ignored
483 }
484 };
485
486 /**
487 * Update {@link #mAdapter} with sorted list of applications data usage,
488 * based on current inspection from {@link #mChart}.
489 */
490 private void updateDetailData() {
491 if (LOGD) Log.d(TAG, "updateDetailData()");
492
493 try {
494 final long[] range = mChart.getInspectRange();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700495 final NetworkStats stats = mStatsService.getSummaryForAllUid(
Jeff Sharkey8a503642011-06-10 13:31:21 -0700496 range[0], range[1], mTemplate);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700497 mAdapter.bindStats(stats);
498 } catch (RemoteException e) {
499 Log.w(TAG, "problem reading stats");
500 }
501 }
502
Jeff Sharkey8a503642011-06-10 13:31:21 -0700503 private DataUsageChartListener mChartListener = new DataUsageChartListener() {
504 /** {@inheritDoc} */
505 public void onInspectRangeChanged() {
506 if (LOGD) Log.d(TAG, "onInspectRangeChanged()");
507 updateDetailData();
508 }
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700509
Jeff Sharkey8a503642011-06-10 13:31:21 -0700510 /** {@inheritDoc} */
511 public void onLimitsChanged() {
512 if (LOGD) Log.d(TAG, "onLimitsChanged()");
513
514 // redefine policy and persist into service
515 // TODO: kick this onto background thread, since service touches disk
516
517 // TODO: remove this mPolicy null check, since later service will
518 // always define baseline value.
519 final int cycleDay = mPolicy != null ? mPolicy.cycleDay : 1;
520 final long warningBytes = mChart.getWarningBytes();
521 final long limitBytes = mDisableAtLimit.isChecked() ? -1 : mChart.getLimitBytes();
522
523 mPolicy = new NetworkPolicy(cycleDay, warningBytes, limitBytes);
524 if (LOGD) Log.d(TAG, "persisting policy=" + mPolicy);
525
526 try {
527 mPolicyService.setNetworkPolicy(mTemplate, null, mPolicy);
528 } catch (RemoteException e) {
529 Log.w(TAG, "problem persisting policy", e);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700530 }
531 }
532 };
533
534
535 /**
Jeff Sharkey8a503642011-06-10 13:31:21 -0700536 * List item that reflects a specific data usage cycle.
537 */
538 public static class CycleItem {
539 public CharSequence label;
540 public long start;
541 public long end;
542
543 private static final StringBuilder sBuilder = new StringBuilder(50);
544 private static final java.util.Formatter sFormatter = new java.util.Formatter(
545 sBuilder, Locale.getDefault());
546
547 CycleItem(CharSequence label) {
548 this.label = label;
549 }
550
551 public CycleItem(Context context, long start, long end) {
552 this.label = formatDateRangeUtc(context, start, end);
553 this.start = start;
554 this.end = end;
555 }
556
557 private static String formatDateRangeUtc(Context context, long start, long end) {
558 synchronized (sBuilder) {
559 sBuilder.setLength(0);
560 return DateUtils.formatDateRange(context, sFormatter, start, end,
561 DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH,
562 Time.TIMEZONE_UTC).toString();
563 }
564 }
565
566 @Override
567 public String toString() {
568 return label.toString();
569 }
570 }
571
572 /**
573 * Special-case data usage cycle that triggers dialog to change
574 * {@link NetworkPolicy#cycleDay}.
575 */
576 public static class CycleChangeItem extends CycleItem {
577 public CycleChangeItem(Context context) {
578 super(context.getString(R.string.data_usage_change_cycle));
579 }
580 }
581
582 public static class CycleAdapter extends ArrayAdapter<CycleItem> {
583 public CycleAdapter(Context context) {
584 super(context, android.R.layout.simple_spinner_item);
585 setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
586 }
587 }
588
589 /**
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700590 * Adapter of applications, sorted by total usage descending.
591 */
592 public static class DataUsageAdapter extends BaseAdapter {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700593 private ArrayList<AppUsageItem> mItems = Lists.newArrayList();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700594
Jeff Sharkey8a503642011-06-10 13:31:21 -0700595 private static class AppUsageItem implements Comparable<AppUsageItem> {
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700596 public int uid;
597 public long total;
598
599 /** {@inheritDoc} */
Jeff Sharkey8a503642011-06-10 13:31:21 -0700600 public int compareTo(AppUsageItem another) {
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700601 return Long.compare(another.total, total);
602 }
603 }
604
605 public void bindStats(NetworkStats stats) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700606 mItems.clear();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700607
608 for (int i = 0; i < stats.length(); i++) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700609 final AppUsageItem item = new AppUsageItem();
610 item.uid = stats.uid[i];
611 item.total = stats.rx[i] + stats.tx[i];
612 mItems.add(item);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700613 }
614
Jeff Sharkey8a503642011-06-10 13:31:21 -0700615 Collections.sort(mItems);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700616 notifyDataSetChanged();
617 }
618
619 @Override
620 public int getCount() {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700621 return mItems.size();
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700622 }
623
624 @Override
625 public Object getItem(int position) {
Jeff Sharkey8a503642011-06-10 13:31:21 -0700626 return mItems.get(position);
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700627 }
628
629 @Override
630 public long getItemId(int position) {
631 return position;
632 }
633
634 @Override
635 public View getView(int position, View convertView, ViewGroup parent) {
636 if (convertView == null) {
637 convertView = LayoutInflater.from(parent.getContext()).inflate(
638 android.R.layout.simple_list_item_2, parent, false);
639 }
640
641 final Context context = parent.getContext();
642 final PackageManager pm = context.getPackageManager();
643
644 final TextView text1 = (TextView) convertView.findViewById(android.R.id.text1);
645 final TextView text2 = (TextView) convertView.findViewById(android.R.id.text2);
646
Jeff Sharkey8a503642011-06-10 13:31:21 -0700647 final AppUsageItem item = mItems.get(position);
648 text1.setText(pm.getNameForUid(item.uid));
649 text2.setText(Formatter.formatFileSize(context, item.total));
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700650
651 return convertView;
652 }
653
654 }
655
656
Jeff Sharkeyab2d8d32011-05-30 16:19:56 -0700657}