This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
/
DataUsageSummary.java
2488 lines (2097 loc) · 94.5 KB
/
DataUsageSummary.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import static android.net.ConnectivityManager.TYPE_ETHERNET;
import static android.net.ConnectivityManager.TYPE_MOBILE;
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.net.ConnectivityManager.TYPE_WIMAX;
import static android.net.NetworkPolicy.LIMIT_DISABLED;
import static android.net.NetworkPolicy.WARNING_DISABLED;
import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
import static android.net.NetworkPolicyManager.POLICY_NONE;
import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
import static android.net.NetworkPolicyManager.computeNextCycleBoundary;
import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
import static android.net.NetworkTemplate.MATCH_WIFI;
import static android.net.NetworkTemplate.buildTemplateEthernet;
import static android.net.NetworkTemplate.buildTemplateMobile3gLower;
import static android.net.NetworkTemplate.buildTemplateMobile4g;
import static android.net.NetworkTemplate.buildTemplateMobileAll;
import static android.net.NetworkTemplate.buildTemplateWifiWildcard;
import static android.net.TrafficStats.GB_IN_BYTES;
import static android.net.TrafficStats.MB_IN_BYTES;
import static android.net.TrafficStats.UID_REMOVED;
import static android.net.TrafficStats.UID_TETHERING;
import static android.telephony.TelephonyManager.SIM_STATE_READY;
import static android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
import static android.text.format.DateUtils.FORMAT_SHOW_DATE;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static com.android.internal.util.Preconditions.checkNotNull;
import static com.android.settings.Utils.prepareCustomPreferencesList;
import android.animation.LayoutTransition;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.INetworkPolicyManager;
import android.net.INetworkStatsService;
import android.net.INetworkStatsSession;
import android.net.NetworkPolicy;
import android.net.NetworkPolicyManager;
import android.net.NetworkStats;
import android.net.NetworkStatsHistory;
import android.net.NetworkTemplate;
import android.net.TrafficStats;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.INetworkManagementService;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.os.UserManager;
import android.preference.Preference;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.format.Formatter;
import android.text.format.Time;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import com.android.internal.telephony.PhoneConstants;
import com.android.settings.drawable.InsetBoundsDrawable;
import com.android.settings.net.ChartData;
import com.android.settings.net.ChartDataLoader;
import com.android.settings.net.DataUsageMeteredSettings;
import com.android.settings.net.NetworkPolicyEditor;
import com.android.settings.net.SummaryForAllUidLoader;
import com.android.settings.net.UidDetail;
import com.android.settings.net.UidDetailProvider;
import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settings.search.Indexable;
import com.android.settings.search.SearchIndexableRaw;
import com.android.settings.widget.ChartDataUsageView;
import com.android.settings.widget.ChartDataUsageView.DataUsageChartListener;
import com.google.android.collect.Lists;
import libcore.util.Objects;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
/**
* Panel showing data usage history across various networks, including options
* to inspect based on usage cycle and control through {@link NetworkPolicy}.
*/
public class DataUsageSummary extends HighlightingFragment implements Indexable {
private static final String TAG = "DataUsage";
private static final boolean LOGD = false;
// TODO: remove this testing code
private static final boolean TEST_ANIM = false;
private static final boolean TEST_RADIOS = false;
private static final String TEST_RADIOS_PROP = "test.radios";
private static final String TEST_SUBSCRIBER_PROP = "test.subscriberid";
private static final String TAB_3G = "3g";
private static final String TAB_4G = "4g";
private static final String TAB_MOBILE = "mobile";
private static final String TAB_WIFI = "wifi";
private static final String TAB_ETHERNET = "ethernet";
private static final String TAG_CONFIRM_DATA_DISABLE = "confirmDataDisable";
private static final String TAG_CONFIRM_LIMIT = "confirmLimit";
private static final String TAG_CYCLE_EDITOR = "cycleEditor";
private static final String TAG_WARNING_EDITOR = "warningEditor";
private static final String TAG_LIMIT_EDITOR = "limitEditor";
private static final String TAG_CONFIRM_RESTRICT = "confirmRestrict";
private static final String TAG_DENIED_RESTRICT = "deniedRestrict";
private static final String TAG_CONFIRM_APP_RESTRICT = "confirmAppRestrict";
private static final String TAG_APP_DETAILS = "appDetails";
private static final String DATA_USAGE_ENABLE_MOBILE_KEY = "data_usage_enable_mobile";
private static final String DATA_USAGE_DISABLE_MOBILE_LIMIT_KEY =
"data_usage_disable_mobile_limit";
private static final String DATA_USAGE_CYCLE_KEY = "data_usage_cycle";
private static final int LOADER_CHART_DATA = 2;
private static final int LOADER_SUMMARY = 3;
private INetworkManagementService mNetworkService;
private INetworkStatsService mStatsService;
private NetworkPolicyManager mPolicyManager;
private TelephonyManager mTelephonyManager;
private INetworkStatsSession mStatsSession;
private static final String PREF_FILE = "data_usage";
private static final String PREF_SHOW_WIFI = "show_wifi";
private static final String PREF_SHOW_ETHERNET = "show_ethernet";
private SharedPreferences mPrefs;
private TabHost mTabHost;
private ViewGroup mTabsContainer;
private TabWidget mTabWidget;
private ListView mListView;
private DataUsageAdapter mAdapter;
/** Distance to inset content from sides, when needed. */
private int mInsetSide = 0;
private ViewGroup mHeader;
private ViewGroup mNetworkSwitchesContainer;
private LinearLayout mNetworkSwitches;
private boolean mDataEnabledSupported;
private Switch mDataEnabled;
private View mDataEnabledView;
private boolean mDisableAtLimitSupported;
private Switch mDisableAtLimit;
private View mDisableAtLimitView;
private View mCycleView;
private Spinner mCycleSpinner;
private CycleAdapter mCycleAdapter;
private TextView mCycleSummary;
private ChartDataUsageView mChart;
private View mDisclaimer;
private TextView mEmpty;
private View mStupidPadding;
private View mAppDetail;
private ImageView mAppIcon;
private ViewGroup mAppTitles;
private TextView mAppTotal;
private TextView mAppForeground;
private TextView mAppBackground;
private Button mAppSettings;
private LinearLayout mAppSwitches;
private Switch mAppRestrict;
private View mAppRestrictView;
private boolean mShowWifi = false;
private boolean mShowEthernet = false;
private NetworkTemplate mTemplate;
private ChartData mChartData;
private AppItem mCurrentApp = null;
private Intent mAppSettingsIntent;
private NetworkPolicyEditor mPolicyEditor;
private String mCurrentTab = null;
private String mIntentTab = null;
private MenuItem mMenuRestrictBackground;
private MenuItem mMenuShowWifi;
private MenuItem mMenuShowEthernet;
private MenuItem mMenuSimCards;
private MenuItem mMenuCellularNetworks;
/** Flag used to ignore listeners during binding. */
private boolean mBinding;
private UidDetailProvider mUidDetailProvider;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context context = getActivity();
mNetworkService = INetworkManagementService.Stub.asInterface(
ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
mStatsService = INetworkStatsService.Stub.asInterface(
ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
mPolicyManager = NetworkPolicyManager.from(context);
mTelephonyManager = TelephonyManager.from(context);
mPrefs = getActivity().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
mPolicyEditor = new NetworkPolicyEditor(mPolicyManager);
mPolicyEditor.read();
try {
if (!mNetworkService.isBandwidthControlEnabled()) {
Log.w(TAG, "No bandwidth control; leaving");
getActivity().finish();
}
} catch (RemoteException e) {
Log.w(TAG, "No bandwidth control; leaving");
getActivity().finish();
}
try {
mStatsSession = mStatsService.openSession();
} catch (RemoteException e) {
throw new RuntimeException(e);
}
mShowWifi = mPrefs.getBoolean(PREF_SHOW_WIFI, false);
mShowEthernet = mPrefs.getBoolean(PREF_SHOW_ETHERNET, false);
// override preferences when no mobile radio
if (!hasReadyMobileRadio(context)) {
mShowWifi = true;
mShowEthernet = true;
}
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context context = inflater.getContext();
final View view = inflater.inflate(R.layout.data_usage_summary, container, false);
mUidDetailProvider = new UidDetailProvider(context);
mTabHost = (TabHost) view.findViewById(android.R.id.tabhost);
mTabsContainer = (ViewGroup) view.findViewById(R.id.tabs_container);
mTabWidget = (TabWidget) view.findViewById(android.R.id.tabs);
mListView = (ListView) view.findViewById(android.R.id.list);
// decide if we need to manually inset our content, or if we should rely
// on parent container for inset.
final boolean shouldInset = mListView.getScrollBarStyle()
== View.SCROLLBARS_OUTSIDE_OVERLAY;
mInsetSide = 0;
// adjust padding around tabwidget as needed
prepareCustomPreferencesList(container, view, mListView, false);
mTabHost.setup();
mTabHost.setOnTabChangedListener(mTabListener);
mHeader = (ViewGroup) inflater.inflate(R.layout.data_usage_header, mListView, false);
mHeader.setClickable(true);
mListView.addHeaderView(new View(context), null, true);
mListView.addHeaderView(mHeader, null, true);
mListView.setItemsCanFocus(true);
if (mInsetSide > 0) {
// inset selector and divider drawables
insetListViewDrawables(mListView, mInsetSide);
mHeader.setPaddingRelative(mInsetSide, 0, mInsetSide, 0);
}
{
// bind network switches
mNetworkSwitchesContainer = (ViewGroup) mHeader.findViewById(
R.id.network_switches_container);
mNetworkSwitches = (LinearLayout) mHeader.findViewById(R.id.network_switches);
mDataEnabled = new Switch(inflater.getContext());
mDataEnabled.setClickable(false);
mDataEnabled.setFocusable(false);
mDataEnabledView = inflatePreference(inflater, mNetworkSwitches, mDataEnabled);
mDataEnabledView.setTag(R.id.preference_highlight_key,
DATA_USAGE_ENABLE_MOBILE_KEY);
mDataEnabledView.setClickable(true);
mDataEnabledView.setFocusable(true);
mDataEnabledView.setOnClickListener(mDataEnabledListener);
mNetworkSwitches.addView(mDataEnabledView);
mDisableAtLimit = new Switch(inflater.getContext());
mDisableAtLimit.setClickable(false);
mDisableAtLimit.setFocusable(false);
mDisableAtLimitView = inflatePreference(inflater, mNetworkSwitches, mDisableAtLimit);
mDisableAtLimitView.setTag(R.id.preference_highlight_key,
DATA_USAGE_DISABLE_MOBILE_LIMIT_KEY);
mDisableAtLimitView.setClickable(true);
mDisableAtLimitView.setFocusable(true);
mDisableAtLimitView.setOnClickListener(mDisableAtLimitListener);
mNetworkSwitches.addView(mDisableAtLimitView);
mCycleView = inflater.inflate(R.layout.data_usage_cycles, mNetworkSwitches, false);
mCycleView.setTag(R.id.preference_highlight_key, DATA_USAGE_CYCLE_KEY);
mCycleSpinner = (Spinner) mCycleView.findViewById(R.id.cycles_spinner);
mCycleAdapter = new CycleAdapter(context);
mCycleSpinner.setAdapter(mCycleAdapter);
mCycleSpinner.setOnItemSelectedListener(mCycleListener);
mCycleSummary = (TextView) mCycleView.findViewById(R.id.cycle_summary);
mNetworkSwitches.addView(mCycleView);
}
mChart = (ChartDataUsageView) mHeader.findViewById(R.id.chart);
mChart.setListener(mChartListener);
mChart.bindNetworkPolicy(null);
{
// bind app detail controls
mAppDetail = mHeader.findViewById(R.id.app_detail);
mAppIcon = (ImageView) mAppDetail.findViewById(R.id.app_icon);
mAppTitles = (ViewGroup) mAppDetail.findViewById(R.id.app_titles);
mAppForeground = (TextView) mAppDetail.findViewById(R.id.app_foreground);
mAppBackground = (TextView) mAppDetail.findViewById(R.id.app_background);
mAppSwitches = (LinearLayout) mAppDetail.findViewById(R.id.app_switches);
mAppSettings = (Button) mAppDetail.findViewById(R.id.app_settings);
mAppRestrict = new Switch(inflater.getContext());
mAppRestrict.setClickable(false);
mAppRestrict.setFocusable(false);
mAppRestrictView = inflatePreference(inflater, mAppSwitches, mAppRestrict);
mAppRestrictView.setClickable(true);
mAppRestrictView.setFocusable(true);
mAppRestrictView.setOnClickListener(mAppRestrictListener);
mAppSwitches.addView(mAppRestrictView);
}
mDisclaimer = mHeader.findViewById(R.id.disclaimer);
mEmpty = (TextView) mHeader.findViewById(android.R.id.empty);
mStupidPadding = mHeader.findViewById(R.id.stupid_padding);
final UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
mAdapter = new DataUsageAdapter(um, mUidDetailProvider, mInsetSide);
mListView.setOnItemClickListener(mListListener);
mListView.setAdapter(mAdapter);
return view;
}
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
// pick default tab based on incoming intent
final Intent intent = getActivity().getIntent();
mIntentTab = computeTabFromIntent(intent);
// this kicks off chain reaction which creates tabs, binds the body to
// selected network, and binds chart, cycles and detail list.
updateTabs();
}
@Override
public void onResume() {
super.onResume();
getView().post(new Runnable() {
@Override
public void run() {
highlightViewIfNeeded();
}
});
// kick off background task to update stats
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
// wait a few seconds before kicking off
Thread.sleep(2 * DateUtils.SECOND_IN_MILLIS);
mStatsService.forceUpdate();
} catch (InterruptedException e) {
} catch (RemoteException e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (isAdded()) {
updateBody();
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.data_usage, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
final Context context = getActivity();
final boolean appDetailMode = isAppDetailMode();
final boolean isOwner = ActivityManager.getCurrentUser() == UserHandle.USER_OWNER;
mMenuShowWifi = menu.findItem(R.id.data_usage_menu_show_wifi);
if (hasWifiRadio(context) && hasReadyMobileRadio(context)) {
mMenuShowWifi.setVisible(!appDetailMode);
} else {
mMenuShowWifi.setVisible(false);
}
mMenuShowEthernet = menu.findItem(R.id.data_usage_menu_show_ethernet);
if (hasEthernet(context) && hasReadyMobileRadio(context)) {
mMenuShowEthernet.setVisible(!appDetailMode);
} else {
mMenuShowEthernet.setVisible(false);
}
mMenuRestrictBackground = menu.findItem(R.id.data_usage_menu_restrict_background);
mMenuRestrictBackground.setVisible(
hasReadyMobileRadio(context) && isOwner && !appDetailMode);
final MenuItem metered = menu.findItem(R.id.data_usage_menu_metered);
if (hasReadyMobileRadio(context) || hasWifiRadio(context)) {
metered.setVisible(!appDetailMode);
} else {
metered.setVisible(false);
}
// TODO: show when multiple sims available
mMenuSimCards = menu.findItem(R.id.data_usage_menu_sim_cards);
mMenuSimCards.setVisible(false);
mMenuCellularNetworks = menu.findItem(R.id.data_usage_menu_cellular_networks);
mMenuCellularNetworks.setVisible(hasReadyMobileRadio(context)
&& !appDetailMode && isOwner);
final MenuItem help = menu.findItem(R.id.data_usage_menu_help);
String helpUrl;
if (!TextUtils.isEmpty(helpUrl = getResources().getString(R.string.help_url_data_usage))) {
HelpUtils.prepareHelpMenuItem(context, help, helpUrl);
} else {
help.setVisible(false);
}
updateMenuTitles();
}
private void updateMenuTitles() {
if (mPolicyManager.getRestrictBackground()) {
mMenuRestrictBackground.setTitle(R.string.data_usage_menu_allow_background);
} else {
mMenuRestrictBackground.setTitle(R.string.data_usage_menu_restrict_background);
}
if (mShowWifi) {
mMenuShowWifi.setTitle(R.string.data_usage_menu_hide_wifi);
} else {
mMenuShowWifi.setTitle(R.string.data_usage_menu_show_wifi);
}
if (mShowEthernet) {
mMenuShowEthernet.setTitle(R.string.data_usage_menu_hide_ethernet);
} else {
mMenuShowEthernet.setTitle(R.string.data_usage_menu_show_ethernet);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.data_usage_menu_restrict_background: {
final boolean restrictBackground = !mPolicyManager.getRestrictBackground();
if (restrictBackground) {
ConfirmRestrictFragment.show(this);
} else {
// no confirmation to drop restriction
setRestrictBackground(false);
}
return true;
}
case R.id.data_usage_menu_show_wifi: {
mShowWifi = !mShowWifi;
mPrefs.edit().putBoolean(PREF_SHOW_WIFI, mShowWifi).apply();
updateMenuTitles();
updateTabs();
return true;
}
case R.id.data_usage_menu_show_ethernet: {
mShowEthernet = !mShowEthernet;
mPrefs.edit().putBoolean(PREF_SHOW_ETHERNET, mShowEthernet).apply();
updateMenuTitles();
updateTabs();
return true;
}
case R.id.data_usage_menu_sim_cards: {
// TODO: hook up to sim cards
return true;
}
case R.id.data_usage_menu_cellular_networks: {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.android.phone",
"com.android.phone.MobileNetworkSettings"));
startActivity(intent);
return true;
}
case R.id.data_usage_menu_metered: {
final SettingsActivity sa = (SettingsActivity) getActivity();
sa.startPreferencePanel(DataUsageMeteredSettings.class.getCanonicalName(), null,
R.string.data_usage_metered_title, null, this, 0);
return true;
}
}
return false;
}
@Override
public void onDestroy() {
mDataEnabledView = null;
mDisableAtLimitView = null;
mUidDetailProvider.clearCache();
mUidDetailProvider = null;
TrafficStats.closeQuietly(mStatsSession);
super.onDestroy();
}
/**
* Build and assign {@link LayoutTransition} to various containers. Should
* only be assigned after initial layout is complete.
*/
private void ensureLayoutTransitions() {
// skip when already setup
if (mChart.getLayoutTransition() != null) return;
mTabsContainer.setLayoutTransition(buildLayoutTransition());
mHeader.setLayoutTransition(buildLayoutTransition());
mNetworkSwitchesContainer.setLayoutTransition(buildLayoutTransition());
final LayoutTransition chartTransition = buildLayoutTransition();
chartTransition.disableTransitionType(LayoutTransition.APPEARING);
chartTransition.disableTransitionType(LayoutTransition.DISAPPEARING);
mChart.setLayoutTransition(chartTransition);
}
private static LayoutTransition buildLayoutTransition() {
final LayoutTransition transition = new LayoutTransition();
if (TEST_ANIM) {
transition.setDuration(1500);
}
transition.setAnimateParentHierarchy(false);
return transition;
}
/**
* Rebuild all tabs based on {@link NetworkPolicyEditor} and
* {@link #mShowWifi}, hiding the tabs entirely when applicable. Selects
* first tab, and kicks off a full rebind of body contents.
*/
private void updateTabs() {
final Context context = getActivity();
mTabHost.clearAllTabs();
final boolean mobileSplit = isMobilePolicySplit();
if (mobileSplit && hasReadyMobile4gRadio(context)) {
mTabHost.addTab(buildTabSpec(TAB_3G, R.string.data_usage_tab_3g));
mTabHost.addTab(buildTabSpec(TAB_4G, R.string.data_usage_tab_4g));
} else if (hasReadyMobileRadio(context)) {
mTabHost.addTab(buildTabSpec(TAB_MOBILE, R.string.data_usage_tab_mobile));
}
if (mShowWifi && hasWifiRadio(context)) {
mTabHost.addTab(buildTabSpec(TAB_WIFI, R.string.data_usage_tab_wifi));
}
if (mShowEthernet && hasEthernet(context)) {
mTabHost.addTab(buildTabSpec(TAB_ETHERNET, R.string.data_usage_tab_ethernet));
}
final boolean noTabs = mTabWidget.getTabCount() == 0;
final boolean multipleTabs = mTabWidget.getTabCount() > 1;
mTabWidget.setVisibility(multipleTabs ? View.VISIBLE : View.GONE);
if (mIntentTab != null) {
if (Objects.equal(mIntentTab, mTabHost.getCurrentTabTag())) {
// already hit updateBody() when added; ignore
updateBody();
} else {
mTabHost.setCurrentTabByTag(mIntentTab);
}
mIntentTab = null;
} else if (noTabs) {
// no usable tabs, so hide body
updateBody();
} else {
// already hit updateBody() when added; ignore
}
}
/**
* Factory that provide empty {@link View} to make {@link TabHost} happy.
*/
private TabContentFactory mEmptyTabContent = new TabContentFactory() {
@Override
public View createTabContent(String tag) {
return new View(mTabHost.getContext());
}
};
/**
* Build {@link TabSpec} with thin indicator, and empty content.
*/
private TabSpec buildTabSpec(String tag, int titleRes) {
return mTabHost.newTabSpec(tag).setIndicator(getText(titleRes)).setContent(
mEmptyTabContent);
}
private OnTabChangeListener mTabListener = new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
// user changed tab; update body
updateBody();
}
};
/**
* Update body content based on current tab. Loads
* {@link NetworkStatsHistory} and {@link NetworkPolicy} from system, and
* binds them to visible controls.
*/
private void updateBody() {
mBinding = true;
if (!isAdded()) return;
final Context context = getActivity();
final String currentTab = mTabHost.getCurrentTabTag();
final boolean isOwner = ActivityManager.getCurrentUser() == UserHandle.USER_OWNER;
if (currentTab == null) {
Log.w(TAG, "no tab selected; hiding body");
mListView.setVisibility(View.GONE);
return;
} else {
mListView.setVisibility(View.VISIBLE);
}
mCurrentTab = currentTab;
if (LOGD) Log.d(TAG, "updateBody() with currentTab=" + currentTab);
mDataEnabledSupported = isOwner;
mDisableAtLimitSupported = true;
// TODO: remove mobile tabs when SIM isn't ready
if (TAB_MOBILE.equals(currentTab)) {
setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_mobile);
setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_mobile_limit);
mTemplate = buildTemplateMobileAll(getActiveSubscriberId(context));
} else if (TAB_3G.equals(currentTab)) {
setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_3g);
setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_3g_limit);
// TODO: bind mDataEnabled to 3G radio state
mTemplate = buildTemplateMobile3gLower(getActiveSubscriberId(context));
} else if (TAB_4G.equals(currentTab)) {
setPreferenceTitle(mDataEnabledView, R.string.data_usage_enable_4g);
setPreferenceTitle(mDisableAtLimitView, R.string.data_usage_disable_4g_limit);
// TODO: bind mDataEnabled to 4G radio state
mTemplate = buildTemplateMobile4g(getActiveSubscriberId(context));
} else if (TAB_WIFI.equals(currentTab)) {
// wifi doesn't have any controls
mDataEnabledSupported = false;
mDisableAtLimitSupported = false;
mTemplate = buildTemplateWifiWildcard();
} else if (TAB_ETHERNET.equals(currentTab)) {
// ethernet doesn't have any controls
mDataEnabledSupported = false;
mDisableAtLimitSupported = false;
mTemplate = buildTemplateEthernet();
} else {
throw new IllegalStateException("unknown tab: " + currentTab);
}
// kick off loader for network history
// TODO: consider chaining two loaders together instead of reloading
// network history when showing app detail.
getLoaderManager().restartLoader(LOADER_CHART_DATA,
ChartDataLoader.buildArgs(mTemplate, mCurrentApp), mChartDataCallbacks);
// detail mode can change visible menus, invalidate
getActivity().invalidateOptionsMenu();
mBinding = false;
}
private boolean isAppDetailMode() {
return mCurrentApp != null;
}
/**
* Update UID details panels to match {@link #mCurrentApp}, showing or
* hiding them depending on {@link #isAppDetailMode()}.
*/
private void updateAppDetail() {
final Context context = getActivity();
final PackageManager pm = context.getPackageManager();
final LayoutInflater inflater = getActivity().getLayoutInflater();
if (isAppDetailMode()) {
mAppDetail.setVisibility(View.VISIBLE);
mCycleAdapter.setChangeVisible(false);
} else {
mAppDetail.setVisibility(View.GONE);
mCycleAdapter.setChangeVisible(true);
// hide detail stats when not in detail mode
mChart.bindDetailNetworkStats(null);
return;
}
// remove warning/limit sweeps while in detail mode
mChart.bindNetworkPolicy(null);
// show icon and all labels appearing under this app
final int uid = mCurrentApp.key;
final UidDetail detail = mUidDetailProvider.getUidDetail(uid, true);
mAppIcon.setImageDrawable(detail.icon);
mAppTitles.removeAllViews();
View title = null;
if (detail.detailLabels != null) {
final int n = detail.detailLabels.length;
for (int i = 0; i < n; ++i) {
CharSequence label = detail.detailLabels[i];
CharSequence contentDescription = detail.detailContentDescriptions[i];
title = inflater.inflate(R.layout.data_usage_app_title, mAppTitles, false);
TextView appTitle = (TextView) title.findViewById(R.id.app_title);
appTitle.setText(label);
appTitle.setContentDescription(contentDescription);
mAppTitles.addView(title);
}
} else {
title = inflater.inflate(R.layout.data_usage_app_title, mAppTitles, false);
TextView appTitle = (TextView) title.findViewById(R.id.app_title);
appTitle.setText(detail.label);
appTitle.setContentDescription(detail.contentDescription);
mAppTitles.addView(title);
}
// Remember last slot for summary
if (title != null) {
mAppTotal = (TextView) title.findViewById(R.id.app_summary);
} else {
mAppTotal = null;
}
// enable settings button when package provides it
final String[] packageNames = pm.getPackagesForUid(uid);
if (packageNames != null && packageNames.length > 0) {
mAppSettingsIntent = new Intent(Intent.ACTION_MANAGE_NETWORK_USAGE);
mAppSettingsIntent.addCategory(Intent.CATEGORY_DEFAULT);
// Search for match across all packages
boolean matchFound = false;
for (String packageName : packageNames) {
mAppSettingsIntent.setPackage(packageName);
if (pm.resolveActivity(mAppSettingsIntent, 0) != null) {
matchFound = true;
break;
}
}
mAppSettings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!isAdded()) {
return;
}
// TODO: target towards entire UID instead of just first package
getActivity().startActivityAsUser(mAppSettingsIntent,
new UserHandle(UserHandle.getUserId(uid)));
}
});
mAppSettings.setEnabled(matchFound);
mAppSettings.setVisibility(View.VISIBLE);
} else {
mAppSettingsIntent = null;
mAppSettings.setOnClickListener(null);
mAppSettings.setVisibility(View.GONE);
}
updateDetailData();
if (UserHandle.isApp(uid) && !mPolicyManager.getRestrictBackground()
&& isBandwidthControlEnabled() && hasReadyMobileRadio(context)) {
setPreferenceTitle(mAppRestrictView, R.string.data_usage_app_restrict_background);
setPreferenceSummary(mAppRestrictView,
getString(R.string.data_usage_app_restrict_background_summary));
mAppRestrictView.setVisibility(View.VISIBLE);
mAppRestrict.setChecked(getAppRestrictBackground());
} else {
mAppRestrictView.setVisibility(View.GONE);
}
}
private void setPolicyWarningBytes(long warningBytes) {
if (LOGD) Log.d(TAG, "setPolicyWarningBytes()");
mPolicyEditor.setPolicyWarningBytes(mTemplate, warningBytes);
updatePolicy(false);
}
private void setPolicyLimitBytes(long limitBytes) {
if (LOGD) Log.d(TAG, "setPolicyLimitBytes()");
mPolicyEditor.setPolicyLimitBytes(mTemplate, limitBytes);
updatePolicy(false);
}
/**
* Local cache of value, used to work around delay when
* {@link ConnectivityManager#setMobileDataEnabled(boolean)} is async.
*/
private Boolean mMobileDataEnabled;
private boolean isMobileDataEnabled() {
if (mMobileDataEnabled != null) {
// TODO: deprecate and remove this once enabled flag is on policy
return mMobileDataEnabled;
} else {
return mTelephonyManager.getDataEnabled();
}
}
private void setMobileDataEnabled(boolean enabled) {
if (LOGD) Log.d(TAG, "setMobileDataEnabled()");
mTelephonyManager.setDataEnabled(enabled);
mMobileDataEnabled = enabled;
updatePolicy(false);
}
private boolean isNetworkPolicyModifiable(NetworkPolicy policy) {
return policy != null && isBandwidthControlEnabled() && mDataEnabled.isChecked()
&& ActivityManager.getCurrentUser() == UserHandle.USER_OWNER;
}
private boolean isBandwidthControlEnabled() {
try {
return mNetworkService.isBandwidthControlEnabled();
} catch (RemoteException e) {
Log.w(TAG, "problem talking with INetworkManagementService: " + e);
return false;
}
}
public void setRestrictBackground(boolean restrictBackground) {
mPolicyManager.setRestrictBackground(restrictBackground);
updateMenuTitles();
}
private boolean getAppRestrictBackground() {
final int uid = mCurrentApp.key;
final int uidPolicy = mPolicyManager.getUidPolicy(uid);
return (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
}
private void setAppRestrictBackground(boolean restrictBackground) {
if (LOGD) Log.d(TAG, "setAppRestrictBackground()");
final int uid = mCurrentApp.key;
mPolicyManager.setUidPolicy(
uid, restrictBackground ? POLICY_REJECT_METERED_BACKGROUND : POLICY_NONE);
mAppRestrict.setChecked(restrictBackground);
}
/**
* Update chart sweeps and cycle list to reflect {@link NetworkPolicy} for
* current {@link #mTemplate}.
*/
private void updatePolicy(boolean refreshCycle) {
boolean dataEnabledVisible = mDataEnabledSupported;
boolean disableAtLimitVisible = mDisableAtLimitSupported;
if (isAppDetailMode()) {
dataEnabledVisible = false;
disableAtLimitVisible = false;
}
// TODO: move enabled state directly into policy
if (TAB_MOBILE.equals(mCurrentTab)) {
mBinding = true;
mDataEnabled.setChecked(isMobileDataEnabled());
mBinding = false;
}
final NetworkPolicy policy = mPolicyEditor.getPolicy(mTemplate);
if (isNetworkPolicyModifiable(policy)) {
mDisableAtLimit.setChecked(policy != null && policy.limitBytes != LIMIT_DISABLED);
if (!isAppDetailMode()) {
mChart.bindNetworkPolicy(policy);
}
} else {
// controls are disabled; don't bind warning/limit sweeps
disableAtLimitVisible = false;
mChart.bindNetworkPolicy(null);
}
mDataEnabledView.setVisibility(dataEnabledVisible ? View.VISIBLE : View.GONE);
mDisableAtLimitView.setVisibility(disableAtLimitVisible ? View.VISIBLE : View.GONE);
if (refreshCycle) {
// generate cycle list based on policy and available history