diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index c526d6fc245..663f2b86f2d 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -2383,33 +2383,11 @@
android:value="com.android.settings.security.CryptKeeperSettings" />
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ android:enabled="false">
+
@@ -2419,6 +2397,24 @@
android:value="com.android.settings.datausage.DataUsageSummary" />
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/res/drawable-hdpi/ic_wps_dark.png b/res/drawable-hdpi/ic_wps_dark.png
deleted file mode 100644
index 918b0cc48bc..00000000000
Binary files a/res/drawable-hdpi/ic_wps_dark.png and /dev/null differ
diff --git a/res/drawable-hdpi/ic_wps_light.png b/res/drawable-hdpi/ic_wps_light.png
deleted file mode 100644
index 5ad9f3eaeaf..00000000000
Binary files a/res/drawable-hdpi/ic_wps_light.png and /dev/null differ
diff --git a/res/drawable-mdpi/ic_wps_dark.png b/res/drawable-mdpi/ic_wps_dark.png
deleted file mode 100644
index 77d73a808cd..00000000000
Binary files a/res/drawable-mdpi/ic_wps_dark.png and /dev/null differ
diff --git a/res/drawable-mdpi/ic_wps_light.png b/res/drawable-mdpi/ic_wps_light.png
deleted file mode 100644
index ef560fa5c39..00000000000
Binary files a/res/drawable-mdpi/ic_wps_light.png and /dev/null differ
diff --git a/res/drawable-xhdpi/ic_wps_dark.png b/res/drawable-xhdpi/ic_wps_dark.png
deleted file mode 100644
index 3ea4a3b6bcb..00000000000
Binary files a/res/drawable-xhdpi/ic_wps_dark.png and /dev/null differ
diff --git a/res/drawable-xhdpi/ic_wps_light.png b/res/drawable-xhdpi/ic_wps_light.png
deleted file mode 100644
index f913d2c00ea..00000000000
Binary files a/res/drawable-xhdpi/ic_wps_light.png and /dev/null differ
diff --git a/res/drawable-xxhdpi/ic_wps_dark.png b/res/drawable-xxhdpi/ic_wps_dark.png
deleted file mode 100644
index 8b38db86f79..00000000000
Binary files a/res/drawable-xxhdpi/ic_wps_dark.png and /dev/null differ
diff --git a/res/drawable-xxhdpi/ic_wps_light.png b/res/drawable-xxhdpi/ic_wps_light.png
deleted file mode 100644
index 00841755b76..00000000000
Binary files a/res/drawable-xxhdpi/ic_wps_light.png and /dev/null differ
diff --git a/res/layout/data_plans_sync_time_preference.xml b/res/layout/data_plans_sync_time_preference.xml
deleted file mode 100644
index bb9da905e86..00000000000
--- a/res/layout/data_plans_sync_time_preference.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
-
-
diff --git a/res/layout/manage_data_plans_preference.xml b/res/layout/manage_data_plans_preference.xml
deleted file mode 100644
index 0db5698e7cd..00000000000
--- a/res/layout/manage_data_plans_preference.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-
-
-
-
diff --git a/res/layout/styled_switch_bar.xml b/res/layout/styled_switch_bar.xml
index 1777c0f0978..3baaac39610 100644
--- a/res/layout/styled_switch_bar.xml
+++ b/res/layout/styled_switch_bar.xml
@@ -16,13 +16,13 @@
+ android:layout_height="wrap_content"
+ android:layout_width="match_parent" >
diff --git a/res/layout/wifi_wps_dialog.xml b/res/layout/wifi_wps_dialog.xml
deleted file mode 100644
index a86823d66fa..00000000000
--- a/res/layout/wifi_wps_dialog.xml
+++ /dev/null
@@ -1,66 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 5fbbf4da961..2540640f901 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1845,12 +1845,8 @@
Wi\u2011Fi doesn\u0027t turn back on automaticallyWi\u2011Fi networks
-
- WPS Push ButtonMore options
-
- WPS Pin EntryWi\u2011Fi Direct
@@ -1887,32 +1883,6 @@
Drop down list Advanced Options. Double-tap to collapse.Drop down list Advanced Options. Double-tap to expand.
-
- Wi\u2011Fi Protected Setup
-
- Starting WPS\u2026
-
- Press the Wi\u2011Fi Protected Setup button on your router. It may be called \u201cWPS\u201d or marked with this symbol:
-
- Enter pin %1$s on your Wi\u2011Fi router. The setup can take up to two minutes to complete.
-
- WPS succeeded. Connecting to the network\u2026
-
- Connected to Wi\u2011Fi network %s
-
- WPS is already in progress and can take up to two minutes to complete
-
- WPS failed. Please try again in a few minutes.
-
- The wireless router security setting (WEP) is not supported
-
- The wireless router security setting (TKIP) is not supported
-
- Authentication failure. Please try again.
-
- Another WPS session was detected. Please try again in a few minutes.
-
- Wi\u2011Fi disconnected. WPS setup canceled.Network name
@@ -5133,6 +5103,9 @@
Manage battery usage
+
+ Battery left estimate is based on your device usage
+
Estimated time left
@@ -5772,9 +5745,6 @@
Select all
-
- Manage plans
-
Data usage
@@ -7083,7 +7053,7 @@
Blink light
- On the lock screen
+ On lock screen
- Hide sensitive notification content
+ Hide sensitive content
@@ -7113,7 +7083,7 @@
- Hide sensitive work notification content
+ Hide sensitive work content
@@ -7373,7 +7343,7 @@
Let these notifications continue to interrupt when Do Not Disturb is set to Priority Only
- On the lock screen
+ On lock screenBlocked
@@ -8510,7 +8480,7 @@
Wi-Fi, Bluetooth, and mobile network are turned off. You can\'t make phone calls or connect to the internet.
-
+
Do Not Disturb is on
@@ -9369,4 +9339,6 @@
Turn on Bluetooth automatically when driving
+
+ See Android 8.0 battery settings
diff --git a/res/values/themes.xml b/res/values/themes.xml
index e0f3989eb5c..d960654f11c 100644
--- a/res/values/themes.xml
+++ b/res/values/themes.xml
@@ -17,7 +17,6 @@
-
@@ -28,7 +27,6 @@
@*android:style/PreferencePanel.Dialog@style/FingerprintLayoutTheme@*android:drawable/ic_menu_moreoverflow_material
- @drawable/ic_wps_dark0dip@color/setup_wizard_wifi_color_dark@drawable/wifi_signal
@@ -47,7 +45,6 @@
@*android:style/PreferencePanel.Dialog@style/FingerprintLayoutTheme@*android:drawable/ic_menu_moreoverflow_material
- @drawable/ic_wps_light0dip@color/setup_wizard_wifi_color_light@drawable/wifi_signal
@@ -65,7 +62,6 @@
@*android:style/PreferencePanel.Dialog@style/FingerprintLayoutTheme@*android:drawable/ic_menu_moreoverflow_material
- @drawable/ic_wps_dark0dip@color/setup_wizard_wifi_color_dark@drawable/wifi_signal
@@ -84,7 +80,6 @@
@*android:style/PreferencePanel.Dialog@style/FingerprintLayoutTheme@*android:drawable/ic_menu_moreoverflow_material
- @drawable/ic_wps_light0dip@color/setup_wizard_wifi_color_light@drawable/wifi_signal
@@ -102,7 +97,6 @@
@*android:style/PreferencePanel.Dialog@style/FingerprintLayoutTheme@*android:drawable/ic_menu_moreoverflow_material
- @drawable/ic_wps_dark0dip@color/setup_wizard_wifi_color_dark@drawable/wifi_signal
@@ -121,7 +115,6 @@
@*android:style/PreferencePanel.Dialog@style/FingerprintLayoutTheme@*android:drawable/ic_menu_moreoverflow_material
- @drawable/ic_wps_light0dip@color/setup_wizard_wifi_color_light@drawable/wifi_signal
@@ -221,7 +214,6 @@
@style/FingerprintLayoutTheme@*android:drawable/ic_menu_moreoverflow_holo_dark
- @drawable/ic_wps_light@drawable/wifi_signal?android:attr/colorAccent@drawable/wifi_friction
diff --git a/res/xml/data_plan_usage.xml b/res/xml/data_plan_usage.xml
deleted file mode 100644
index 4691198bf77..00000000000
--- a/res/xml/data_plan_usage.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-
-
-
-
diff --git a/res/xml/data_plan_usage_cell_data_preference_screen.xml b/res/xml/data_plan_usage_cell_data_preference_screen.xml
deleted file mode 100644
index 08f21c55ca4..00000000000
--- a/res/xml/data_plan_usage_cell_data_preference_screen.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
diff --git a/res/xml/data_usage_legacy.xml b/res/xml/data_usage_legacy.xml
new file mode 100644
index 00000000000..958459c2d16
--- /dev/null
+++ b/res/xml/data_usage_legacy.xml
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/res/xml/development_settings.xml b/res/xml/development_settings.xml
index 5a0d249b1e7..a88a97bc711 100644
--- a/res/xml/development_settings.xml
+++ b/res/xml/development_settings.xml
@@ -76,6 +76,11 @@
android:summary="@string/runningservices_settings_summary"
android:fragment="com.android.settings.applications.RunningServices" />
+
+
-
-
-
-
-
diff --git a/src/com/android/settings/ResetNetworkConfirm.java b/src/com/android/settings/ResetNetworkConfirm.java
index 78e83394101..8d6700cd11e 100644
--- a/src/com/android/settings/ResetNetworkConfirm.java
+++ b/src/com/android/settings/ResetNetworkConfirm.java
@@ -225,6 +225,7 @@ public class ResetNetworkConfirm extends InstrumentedFragment {
mEraseEsimTask.cancel(true /* mayInterruptIfRunning */);
mEraseEsimTask = null;
}
+ super.onDestroy();
}
@Override
diff --git a/src/com/android/settings/Settings.java b/src/com/android/settings/Settings.java
index 741bfda4a5a..599d6fbe762 100644
--- a/src/com/android/settings/Settings.java
+++ b/src/com/android/settings/Settings.java
@@ -78,8 +78,8 @@ public class Settings extends SettingsActivity {
public static class AccountSyncSettingsInAddAccountActivity extends SettingsActivity { /* empty */ }
public static class CryptKeeperSettingsActivity extends SettingsActivity { /* empty */ }
public static class DeviceAdminSettingsActivity extends SettingsActivity { /* empty */ }
- public static class DataPlanUsageSummaryActivity extends SettingsActivity { /* empty */ }
public static class DataUsageSummaryActivity extends SettingsActivity { /* empty */ }
+ public static class DataUsageSummaryLegacyActivity extends SettingsActivity { /* empty */ }
public static class MobileDataUsageListActivity extends SettingsActivity { /* empty */ }
public static class ConfigureWifiSettingsActivity extends SettingsActivity { /* empty */ }
public static class SavedAccessPointsSettingsActivity extends SettingsActivity { /* empty */ }
diff --git a/src/com/android/settings/SettingsActivity.java b/src/com/android/settings/SettingsActivity.java
index 01818e99313..eeac30291e8 100644
--- a/src/com/android/settings/SettingsActivity.java
+++ b/src/com/android/settings/SettingsActivity.java
@@ -46,6 +46,7 @@ import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceManager;
import android.text.TextUtils;
import android.transition.TransitionManager;
+import android.util.FeatureFlagUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
@@ -57,6 +58,7 @@ import com.android.internal.util.ArrayUtils;
import com.android.settings.Settings.WifiSettingsActivity;
import com.android.settings.applications.manageapplications.ManageApplications;
import com.android.settings.backup.BackupSettingsActivity;
+import com.android.settings.core.FeatureFlags;
import com.android.settings.core.gateway.SettingsGateway;
import com.android.settings.dashboard.DashboardFeatureProvider;
import com.android.settings.dashboard.DashboardSummary;
@@ -82,8 +84,6 @@ public class SettingsActivity extends SettingsDrawerActivity
// Constants for state save/restore
private static final String SAVE_KEY_CATEGORIES = ":settings:categories";
- @VisibleForTesting
- static final String SAVE_KEY_SHOW_HOME_AS_UP = ":settings:show_home_as_up";
/**
* When starting this activity, the invoking Intent can contain this extra
@@ -146,12 +146,10 @@ public class SettingsActivity extends SettingsDrawerActivity
public static final String EXTRA_HIDE_DRAWER = ":settings:hide_drawer";
public static final String META_DATA_KEY_FRAGMENT_CLASS =
- "com.android.settings.FRAGMENT_CLASS";
+ "com.android.settings.FRAGMENT_CLASS";
private static final String EXTRA_UI_OPTIONS = "settings:ui_options";
- private static final int REQUEST_SUGGESTION = 42;
-
private String mFragmentClass;
private CharSequence mInitialTitle;
@@ -183,9 +181,6 @@ public class SettingsActivity extends SettingsDrawerActivity
private Button mNextButton;
- @VisibleForTesting
- boolean mDisplayHomeAsUpEnabled;
-
private boolean mIsShowingDashboard;
private boolean mIsShortcut;
@@ -197,7 +192,6 @@ public class SettingsActivity extends SettingsDrawerActivity
private ArrayList mCategories = new ArrayList<>();
private DashboardFeatureProvider mDashboardFeatureProvider;
- private ComponentName mCurrentSuggestion;
public SwitchBar getSwitchBar() {
return mSwitchBar;
@@ -310,9 +304,6 @@ public class SettingsActivity extends SettingsDrawerActivity
mCategories.addAll(categories);
setTitleFromBackStack();
}
-
- mDisplayHomeAsUpEnabled = savedState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
-
} else {
launchSettingFragment(initialFragmentName, isSubSettings, intent);
}
@@ -337,8 +328,8 @@ public class SettingsActivity extends SettingsDrawerActivity
ActionBar actionBar = getActionBar();
if (actionBar != null) {
- actionBar.setDisplayHomeAsUpEnabled(mDisplayHomeAsUpEnabled);
- actionBar.setHomeButtonEnabled(mDisplayHomeAsUpEnabled);
+ actionBar.setDisplayHomeAsUpEnabled(true);
+ actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowTitleEnabled(!mIsShowingDashboard);
}
mSwitchBar = findViewById(R.id.switch_bar);
@@ -353,21 +344,21 @@ public class SettingsActivity extends SettingsDrawerActivity
if (buttonBar != null) {
buttonBar.setVisibility(View.VISIBLE);
- Button backButton = (Button)findViewById(R.id.back_button);
+ Button backButton = (Button) findViewById(R.id.back_button);
backButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_CANCELED, null);
finish();
}
});
- Button skipButton = (Button)findViewById(R.id.skip_button);
+ Button skipButton = (Button) findViewById(R.id.skip_button);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK, null);
finish();
}
});
- mNextButton = (Button)findViewById(R.id.next_button);
+ mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK, null);
@@ -380,8 +371,7 @@ public class SettingsActivity extends SettingsDrawerActivity
String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_NEXT_TEXT);
if (TextUtils.isEmpty(buttonText)) {
mNextButton.setVisibility(View.GONE);
- }
- else {
+ } else {
mNextButton.setText(buttonText);
}
}
@@ -389,8 +379,7 @@ public class SettingsActivity extends SettingsDrawerActivity
String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_BACK_TEXT);
if (TextUtils.isEmpty(buttonText)) {
backButton.setVisibility(View.GONE);
- }
- else {
+ } else {
backButton.setText(buttonText);
}
}
@@ -408,26 +397,17 @@ public class SettingsActivity extends SettingsDrawerActivity
@VisibleForTesting
void launchSettingFragment(String initialFragmentName, boolean isSubSettings, Intent intent) {
if (!mIsShowingDashboard && initialFragmentName != null) {
- // UP will be shown only if it is a sub settings
- if (mIsShortcut) {
- mDisplayHomeAsUpEnabled = isSubSettings;
- } else if (isSubSettings) {
- mDisplayHomeAsUpEnabled = true;
- } else {
- mDisplayHomeAsUpEnabled = false;
- }
setTitleFromIntent(intent);
Bundle initialArguments = intent.getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
switchToFragment(initialFragmentName, initialArguments, true, false,
- mInitialTitleResId, mInitialTitle, false);
+ mInitialTitleResId, mInitialTitle, false);
} else {
// Show search icon as up affordance if we are displaying the main Dashboard
- mDisplayHomeAsUpEnabled = true;
mInitialTitleResId = R.string.dashboard_title;
switchToFragment(DashboardSummary.class.getName(), null /* args */, false, false,
- mInitialTitleResId, mInitialTitle, false);
+ mInitialTitleResId, mInitialTitle, false);
}
}
@@ -509,15 +489,6 @@ public class SettingsActivity extends SettingsDrawerActivity
if (mCategories.size() > 0) {
outState.putParcelableArrayList(SAVE_KEY_CATEGORIES, mCategories);
}
-
- outState.putBoolean(SAVE_KEY_SHOW_HOME_AS_UP, mDisplayHomeAsUpEnabled);
- }
-
- @Override
- protected void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
-
- mDisplayHomeAsUpEnabled = savedInstanceState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
}
@Override
@@ -610,17 +581,17 @@ public class SettingsActivity extends SettingsDrawerActivity
* single-pane mode, a new activity will be launched in which to show the
* fragment.
*
- * @param fragmentClass Full name of the class implementing the fragment.
- * @param args Any desired arguments to supply to the fragment.
- * @param titleRes Optional resource identifier of the title of this
- * fragment.
- * @param titleText Optional text of the title of this fragment.
- * @param resultTo Optional fragment that result data should be sent to.
- * If non-null, resultTo.onActivityResult() will be called when this
- * preference panel is done. The launched panel must use
- * {@link #finishPreferencePanel(Fragment, int, Intent)} when done.
+ * @param fragmentClass Full name of the class implementing the fragment.
+ * @param args Any desired arguments to supply to the fragment.
+ * @param titleRes Optional resource identifier of the title of this
+ * fragment.
+ * @param titleText Optional text of the title of this fragment.
+ * @param resultTo Optional fragment that result data should be sent to.
+ * If non-null, resultTo.onActivityResult() will be called when this
+ * preference panel is done. The launched panel must use
+ * {@link #finishPreferencePanel(Fragment, int, Intent)} when done.
* @param resultRequestCode If resultTo is non-null, this is the caller's
- * request code to be received with the result.
+ * request code to be received with the result.
*/
public void startPreferencePanel(Fragment caller, String fragmentClass, Bundle args,
int titleRes, CharSequence titleText, Fragment resultTo, int resultRequestCode) {
@@ -639,10 +610,10 @@ public class SettingsActivity extends SettingsDrawerActivity
* activity will be launched in which to show the fragment.
*
* @param fragmentClass Full name of the class implementing the fragment.
- * @param args Any desired arguments to supply to the fragment.
- * @param titleRes Optional resource identifier of the title of this fragment.
- * @param titleText Optional text of the title of this fragment.
- * @param userHandle The user for which the panel has to be started.
+ * @param args Any desired arguments to supply to the fragment.
+ * @param titleRes Optional resource identifier of the title of this fragment.
+ * @param titleText Optional text of the title of this fragment.
+ * @param userHandle The user for which the panel has to be started.
*/
public void startPreferencePanelAsUser(Fragment caller, String fragmentClass,
Bundle args, int titleRes, CharSequence titleText, UserHandle userHandle) {
@@ -676,11 +647,11 @@ public class SettingsActivity extends SettingsDrawerActivity
/**
* Called by a preference panel fragment to finish itself.
*
- * @param caller The fragment that is asking to be finished.
+ * @param caller The fragment that is asking to be finished.
* @param resultCode Optional result code to send back to the original
- * launching fragment.
+ * launching fragment.
* @param resultData Optional result data to send back to the original
- * launching fragment.
+ * launching fragment.
*/
public void finishPreferencePanel(Fragment caller, int resultCode, Intent resultData) {
setResult(resultCode, resultData);
@@ -691,8 +662,8 @@ public class SettingsActivity extends SettingsDrawerActivity
* Start a new fragment.
*
* @param fragment The fragment to start
- * @param push If true, the current fragment will be pushed onto the back stack. If false,
- * the current fragment will be replaced.
+ * @param push If true, the current fragment will be pushed onto the back stack. If false,
+ * the current fragment will be replaced.
*/
public void startPreferenceFragment(Fragment fragment, boolean push) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
@@ -762,31 +733,11 @@ public class SettingsActivity extends SettingsDrawerActivity
pm.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH), isAdmin)
|| somethingChanged;
- boolean isDataPlanFeatureEnabled = FeatureFactory.getFactory(this)
- .getDataPlanFeatureProvider()
- .isEnabled();
-
- // When the data plan feature flag is turned on we disable DataUsageSummaryActivity
- // and enable DataPlanUsageSummaryActivity. When the feature flag is turned off we do the
- // reverse.
-
- // Disable DataUsageSummaryActivity if the data plan feature flag is turned on otherwise
- // disable DataPlanUsageSummaryActivity.
- somethingChanged = setTileEnabled(
- new ComponentName(packageName,
- isDataPlanFeatureEnabled
- ? Settings.DataUsageSummaryActivity.class.getName()
- : Settings.DataPlanUsageSummaryActivity.class.getName()),
- false /* enabled */,
- isAdmin) || somethingChanged;
// Enable DataUsageSummaryActivity if the data plan feature flag is turned on otherwise
// enable DataPlanUsageSummaryActivity.
somethingChanged = setTileEnabled(
- new ComponentName(packageName,
- isDataPlanFeatureEnabled
- ? Settings.DataPlanUsageSummaryActivity.class.getName()
- : Settings.DataUsageSummaryActivity.class.getName()),
+ new ComponentName(packageName, Settings.DataUsageSummaryActivity.class.getName()),
Utils.isBandwidthControlEnabled() /* enabled */,
isAdmin) || somethingChanged;
@@ -822,6 +773,19 @@ public class SettingsActivity extends SettingsDrawerActivity
Settings.PowerUsageSummaryLegacyActivity.class.getName()),
mBatteryPresent && !isBatterySettingsV2Enabled, isAdmin) || somethingChanged;
+ final boolean isDataUsageSettingsV2Enabled =
+ FeatureFlagUtils.isEnabled(this, FeatureFlags.DATA_USAGE_SETTINGS_V2);
+ // Enable new data usage page if v2 enabled
+ somethingChanged = setTileEnabled(new ComponentName(packageName,
+ Settings.DataUsageSummaryActivity.class.getName()),
+ Utils.isBandwidthControlEnabled() && isDataUsageSettingsV2Enabled, isAdmin)
+ || somethingChanged;
+ // Enable legacy data usage page if v2 disabled
+ somethingChanged = setTileEnabled(new ComponentName(packageName,
+ Settings.DataUsageSummaryLegacyActivity.class.getName()),
+ Utils.isBandwidthControlEnabled() && !isDataUsageSettingsV2Enabled, isAdmin)
+ || somethingChanged;
+
somethingChanged = setTileEnabled(new ComponentName(packageName,
Settings.UserSettingsActivity.class.getName()),
UserHandle.MU_ENABLED && UserManager.supportsMultipleUsers()
@@ -940,29 +904,6 @@ public class SettingsActivity extends SettingsDrawerActivity
return mNextButton;
}
- @Override
- public boolean shouldUpRecreateTask(Intent targetIntent) {
- return super.shouldUpRecreateTask(new Intent(this, SettingsActivity.class));
- }
-
- public void startSuggestion(Intent intent) {
- if (intent == null || ActivityManager.isUserAMonkey()) {
- return;
- }
- mCurrentSuggestion = intent.getComponent();
- startActivityForResult(intent, REQUEST_SUGGESTION);
- }
-
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == REQUEST_SUGGESTION && mCurrentSuggestion != null
- && resultCode != RESULT_CANCELED) {
- getPackageManager().setComponentEnabledSetting(mCurrentSuggestion,
- PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
-
@VisibleForTesting
Bitmap getBitmapFromXmlResource(int drawableRes) {
Drawable drawable = getResources().getDrawable(drawableRes, getTheme());
diff --git a/src/com/android/settings/Utils.java b/src/com/android/settings/Utils.java
index f45ac5edb25..1a321274b42 100644
--- a/src/com/android/settings/Utils.java
+++ b/src/com/android/settings/Utils.java
@@ -52,11 +52,8 @@ import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.fingerprint.FingerprintManager;
-import android.icu.text.MeasureFormat;
import android.icu.text.RelativeDateTimeFormatter;
import android.icu.text.RelativeDateTimeFormatter.RelativeUnit;
-import android.icu.util.Measure;
-import android.icu.util.MeasureUnit;
import android.icu.util.ULocale;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
@@ -88,8 +85,6 @@ import android.support.v7.preference.PreferenceScreen;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
-import android.text.SpannableStringBuilder;
-import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.TtsSpan;
@@ -112,6 +107,7 @@ import com.android.settings.wrapper.DevicePolicyManagerWrapper;
import com.android.settings.wrapper.FingerprintManagerWrapper;
import com.android.settingslib.core.instrumentation.VisibilityLoggerMixin;
+import com.android.settingslib.utils.StringUtil;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Iterator;
@@ -138,10 +134,6 @@ public final class Utils extends com.android.settingslib.Utils {
private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
- private static final int SECONDS_PER_MINUTE = 60;
- private static final int SECONDS_PER_HOUR = 60 * 60;
- private static final int SECONDS_PER_DAY = 24 * 60 * 60;
-
public static final String OS_PKG = "os";
/**
@@ -771,113 +763,6 @@ public final class Utils extends com.android.settingslib.Utils {
return tm.getSimCount() > 1;
}
- /**
- * Returns elapsed time for the given millis, in the following format:
- * 2d 5h 40m 29s
- * @param context the application context
- * @param millis the elapsed time in milli seconds
- * @param withSeconds include seconds?
- * @return the formatted elapsed time
- */
- public static CharSequence formatElapsedTime(Context context, double millis,
- boolean withSeconds) {
- SpannableStringBuilder sb = new SpannableStringBuilder();
- int seconds = (int) Math.floor(millis / 1000);
- if (!withSeconds) {
- // Round up.
- seconds += 30;
- }
-
- int days = 0, hours = 0, minutes = 0;
- if (seconds >= SECONDS_PER_DAY) {
- days = seconds / SECONDS_PER_DAY;
- seconds -= days * SECONDS_PER_DAY;
- }
- if (seconds >= SECONDS_PER_HOUR) {
- hours = seconds / SECONDS_PER_HOUR;
- seconds -= hours * SECONDS_PER_HOUR;
- }
- if (seconds >= SECONDS_PER_MINUTE) {
- minutes = seconds / SECONDS_PER_MINUTE;
- seconds -= minutes * SECONDS_PER_MINUTE;
- }
-
- final ArrayList measureList = new ArrayList(4);
- if (days > 0) {
- measureList.add(new Measure(days, MeasureUnit.DAY));
- }
- if (hours > 0) {
- measureList.add(new Measure(hours, MeasureUnit.HOUR));
- }
- if (minutes > 0) {
- measureList.add(new Measure(minutes, MeasureUnit.MINUTE));
- }
- if (withSeconds && seconds > 0) {
- measureList.add(new Measure(seconds, MeasureUnit.SECOND));
- }
- if (measureList.size() == 0) {
- // Everything addable was zero, so nothing was added. We add a zero.
- measureList.add(new Measure(0, withSeconds ? MeasureUnit.SECOND : MeasureUnit.MINUTE));
- }
- final Measure[] measureArray = measureList.toArray(new Measure[measureList.size()]);
-
- final Locale locale = context.getResources().getConfiguration().locale;
- final MeasureFormat measureFormat = MeasureFormat.getInstance(
- locale, MeasureFormat.FormatWidth.NARROW);
- sb.append(measureFormat.formatMeasures(measureArray));
-
- if (measureArray.length == 1 && MeasureUnit.MINUTE.equals(measureArray[0].getUnit())) {
- // Add ttsSpan if it only have minute value, because it will be read as "meters"
- final TtsSpan ttsSpan = new TtsSpan.MeasureBuilder().setNumber(minutes)
- .setUnit("minute").build();
- sb.setSpan(ttsSpan, 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
-
- return sb;
- }
-
- /**
- * Returns relative time for the given millis in the past, in a short format such as "2 days
- * ago", "5 hr. ago", "40 min. ago", or "29 sec. ago".
- *
- *
The unit is chosen to have good information value while only using one unit. So 27 hours
- * and 50 minutes would be formatted as "28 hr. ago", while 50 hours would be formatted as
- * "2 days ago".
- *
- * @param context the application context
- * @param millis the elapsed time in milli seconds
- * @param withSeconds include seconds?
- * @return the formatted elapsed time
- */
- public static CharSequence formatRelativeTime(Context context, double millis,
- boolean withSeconds) {
- final int seconds = (int) Math.floor(millis / 1000);
- final RelativeUnit unit;
- final int value;
- if (withSeconds && seconds < 2 * SECONDS_PER_MINUTE) {
- unit = RelativeUnit.SECONDS;
- value = seconds;
- } else if (seconds < 2 * SECONDS_PER_HOUR) {
- unit = RelativeUnit.MINUTES;
- value = (seconds + SECONDS_PER_MINUTE / 2) / SECONDS_PER_MINUTE;
- } else if (seconds < 2 * SECONDS_PER_DAY) {
- unit = RelativeUnit.HOURS;
- value = (seconds + SECONDS_PER_HOUR / 2) / SECONDS_PER_HOUR;
- } else {
- unit = RelativeUnit.DAYS;
- value = (seconds + SECONDS_PER_DAY / 2) / SECONDS_PER_DAY;
- }
-
- final Locale locale = context.getResources().getConfiguration().locale;
- final RelativeDateTimeFormatter formatter = RelativeDateTimeFormatter.getInstance(
- ULocale.forLocale(locale),
- null /* default NumberFormat */,
- RelativeDateTimeFormatter.Style.SHORT,
- android.icu.text.DisplayContext.CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE);
-
- return formatter.format(value, RelativeDateTimeFormatter.Direction.LAST, unit);
- }
-
/**
* Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
* @param userManager Instance of UserManager
diff --git a/src/com/android/settings/applications/RecentAppsPreferenceController.java b/src/com/android/settings/applications/RecentAppsPreferenceController.java
index e15671bc24a..b177225f1f2 100644
--- a/src/com/android/settings/applications/RecentAppsPreferenceController.java
+++ b/src/com/android/settings/applications/RecentAppsPreferenceController.java
@@ -38,13 +38,13 @@ import android.util.IconDrawableFactory;
import android.util.Log;
import com.android.settings.R;
-import com.android.settings.Utils;
import com.android.settings.applications.appinfo.AppInfoDashboardFragment;
import com.android.settings.core.PreferenceControllerMixin;
import com.android.settings.widget.AppPreference;
import com.android.settingslib.applications.AppUtils;
import com.android.settingslib.applications.ApplicationsState;
import com.android.settingslib.core.AbstractPreferenceController;
+import com.android.settingslib.utils.StringUtil;
import com.android.settingslib.wrapper.PackageManagerWrapper;
import java.util.ArrayList;
@@ -239,7 +239,7 @@ public class RecentAppsPreferenceController extends AbstractPreferenceController
pref.setKey(pkgName);
pref.setTitle(appEntry.label);
pref.setIcon(mIconDrawableFactory.getBadgedIcon(appEntry.info));
- pref.setSummary(Utils.formatRelativeTime(mContext,
+ pref.setSummary(StringUtil.formatRelativeTime(mContext,
System.currentTimeMillis() - stat.getLastTimeUsed(), false));
pref.setOrder(i);
pref.setOnPreferenceClickListener(preference -> {
diff --git a/src/com/android/settings/backup/BackupSettingsHelper.java b/src/com/android/settings/backup/BackupSettingsHelper.java
index b0d6cf88678..d0a029c355e 100644
--- a/src/com/android/settings/backup/BackupSettingsHelper.java
+++ b/src/com/android/settings/backup/BackupSettingsHelper.java
@@ -24,13 +24,12 @@ import android.content.Intent;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.UserHandle;
-import android.util.Log;
-
import android.support.annotation.VisibleForTesting;
+import android.util.Log;
import com.android.settings.R;
import com.android.settings.Settings.PrivacySettingsActivity;
-import com.android.settingslib.drawer.SettingsDrawerActivity;
+
import java.net.URISyntaxException;
/**
@@ -153,8 +152,7 @@ public class BackupSettingsHelper {
private Intent getIntentForDefaultBackupSettings() {
// Extra needed by {@link SettingsDrawerActivity} to show the back button navigation.
- return new Intent(mContext, PrivacySettingsActivity.class)
- .putExtra(SettingsDrawerActivity.EXTRA_SHOW_MENU, true);
+ return new Intent(mContext, PrivacySettingsActivity.class);
}
/**
diff --git a/src/com/android/settings/core/FeatureFlags.java b/src/com/android/settings/core/FeatureFlags.java
index 8fa1bb3ab28..fd756dfd40e 100644
--- a/src/com/android/settings/core/FeatureFlags.java
+++ b/src/com/android/settings/core/FeatureFlags.java
@@ -26,4 +26,5 @@ public class FeatureFlags {
public static final String ZONE_PICKER_V2 = "settings_zone_picker_v2";
public static final String ABOUT_PHONE_V2 = "settings_about_phone_v2";
public static final String BLUETOOTH_WHILE_DRIVING = "settings_bluetooth_while_driving";
+ public static final String DATA_USAGE_SETTINGS_V2 = "settings_data_usage_v2";
}
diff --git a/src/com/android/settings/core/gateway/SettingsGateway.java b/src/com/android/settings/core/gateway/SettingsGateway.java
index 19d0cd17178..76def2ca10f 100644
--- a/src/com/android/settings/core/gateway/SettingsGateway.java
+++ b/src/com/android/settings/core/gateway/SettingsGateway.java
@@ -33,16 +33,16 @@ import com.android.settings.accessibility.AccessibilitySettings;
import com.android.settings.accessibility.AccessibilitySettingsForSetupWizard;
import com.android.settings.accessibility.CaptionPropertiesFragment;
import com.android.settings.accessibility.ToggleDaltonizerPreferenceFragment;
+import com.android.settings.accounts.AccountDashboardFragment;
import com.android.settings.accounts.AccountSyncSettings;
import com.android.settings.accounts.ChooseAccountActivity;
import com.android.settings.accounts.ManagedProfileSettings;
-import com.android.settings.accounts.AccountDashboardFragment;
import com.android.settings.applications.AppAndNotificationDashboardFragment;
import com.android.settings.applications.DefaultAppSettings;
+import com.android.settings.applications.DirectoryAccessDetails;
import com.android.settings.applications.ManageDomainUrls;
import com.android.settings.applications.ProcessStatsSummary;
import com.android.settings.applications.ProcessStatsUi;
-import com.android.settings.applications.DirectoryAccessDetails;
import com.android.settings.applications.UsageAccessDetails;
import com.android.settings.applications.VrListenerSettings;
import com.android.settings.applications.appinfo.AppInfoDashboardFragment;
@@ -59,9 +59,9 @@ import com.android.settings.connecteddevice.AdvancedConnectedDeviceDashboardFrag
import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragment;
import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragmentOld;
import com.android.settings.connecteddevice.usb.UsbDetailsFragment;
-import com.android.settings.datausage.DataPlanUsageSummary;
import com.android.settings.datausage.DataUsageList;
import com.android.settings.datausage.DataUsageSummary;
+import com.android.settings.datausage.DataUsageSummaryLegacy;
import com.android.settings.deletionhelper.AutomaticStorageManagerSettings;
import com.android.settings.development.DevelopmentSettingsDashboardFragment;
import com.android.settings.deviceinfo.DeviceInfoSettings;
@@ -187,8 +187,8 @@ public class SettingsGateway {
PickupGestureSettings.class.getName(),
DoubleTwistGestureSettings.class.getName(),
CryptKeeperSettings.class.getName(),
- DataPlanUsageSummary.class.getName(),
DataUsageSummary.class.getName(),
+ DataUsageSummaryLegacy.class.getName(),
DreamSettings.class.getName(),
UserSettings.class.getName(),
NotificationAccessSettings.class.getName(),
@@ -273,7 +273,6 @@ public class SettingsGateway {
SupportDashboardActivity.class.getName(),
// Home page > Network & Internet
Settings.WifiSettingsActivity.class.getName(),
- Settings.DataPlanUsageSummaryActivity.class.getName(),
Settings.DataUsageSummaryActivity.class.getName(),
Settings.SimSettingsActivity.class.getName(),
// Home page > Connected devices
diff --git a/src/com/android/settings/dashboard/DashboardFeatureProviderImpl.java b/src/com/android/settings/dashboard/DashboardFeatureProviderImpl.java
index 086a131a9c8..3ed76d8dd52 100644
--- a/src/com/android/settings/dashboard/DashboardFeatureProviderImpl.java
+++ b/src/com/android/settings/dashboard/DashboardFeatureProviderImpl.java
@@ -33,21 +33,18 @@ import android.support.annotation.VisibleForTesting;
import android.support.v7.preference.Preference;
import android.text.TextUtils;
import android.util.ArrayMap;
-import android.util.FeatureFlagUtils;
import android.util.Log;
import android.util.Pair;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.R;
import com.android.settings.SettingsActivity;
-import com.android.settings.core.FeatureFlags;
import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import com.android.settingslib.core.instrumentation.VisibilityLoggerMixin;
import com.android.settingslib.drawer.CategoryManager;
import com.android.settingslib.drawer.DashboardCategory;
import com.android.settingslib.drawer.ProfileSelectDialog;
-import com.android.settingslib.drawer.SettingsDrawerActivity;
import com.android.settingslib.drawer.Tile;
import com.android.settingslib.drawer.TileUtils;
import com.android.settingslib.utils.ThreadUtils;
@@ -212,7 +209,6 @@ public class DashboardFeatureProviderImpl implements DashboardFeatureProvider {
final Intent intent = new Intent(tile.intent)
.putExtra(VisibilityLoggerMixin.EXTRA_SOURCE_METRICS_CATEGORY,
MetricsEvent.DASHBOARD_SUMMARY)
- .putExtra(SettingsDrawerActivity.EXTRA_SHOW_MENU, true)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
launchIntentOrSelectProfile(activity, tile, intent, MetricsEvent.DASHBOARD_SUMMARY);
}
diff --git a/src/com/android/settings/datausage/DataPlanFeatureProvider.java b/src/com/android/settings/datausage/DataPlanFeatureProvider.java
deleted file mode 100644
index eb5b48fc5a0..00000000000
--- a/src/com/android/settings/datausage/DataPlanFeatureProvider.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2017 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.datausage;
-
-/**
- * Feature provider for data plan feature.
- */
-public interface DataPlanFeatureProvider {
- /**
- * @return whether data plan feature is enabled.
- */
- boolean isEnabled();
-}
diff --git a/src/com/android/settings/datausage/DataPlanFeatureProviderImpl.java b/src/com/android/settings/datausage/DataPlanFeatureProviderImpl.java
deleted file mode 100644
index d5f435cce06..00000000000
--- a/src/com/android/settings/datausage/DataPlanFeatureProviderImpl.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2017 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.datausage;
-
-import android.os.SystemProperties;
-
-/**
- * Impl for data plan feature provider.
- */
-public final class DataPlanFeatureProviderImpl implements DataPlanFeatureProvider {
- private static final String ENABLE_SETTINGS_DATA_PLAN = "enable.settings.data.plan";
-
- @Override
- public boolean isEnabled() {
- return SystemProperties.getBoolean(ENABLE_SETTINGS_DATA_PLAN, false /* default */);
- }
-}
diff --git a/src/com/android/settings/datausage/DataPlanSummaryPreference.java b/src/com/android/settings/datausage/DataPlanSummaryPreference.java
deleted file mode 100644
index f48e04d704f..00000000000
--- a/src/com/android/settings/datausage/DataPlanSummaryPreference.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2017 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.datausage;
-
-import android.content.Context;
-import android.support.annotation.ColorRes;
-import android.support.v7.preference.Preference;
-import android.support.v7.preference.PreferenceViewHolder;
-import android.util.AttributeSet;
-import android.widget.TextView;
-import com.android.settings.R;
-import com.android.settings.widget.DonutView;
-
-/**
- * Provides a summary of data plans as preferences on settings page.
- */
-public final class DataPlanSummaryPreference extends Preference {
- private String mName;
- private String mDescription;
- private double mPercentageUsage;
- private int mUsageTextColor;
- private int mMeterBackgroundColor;
- private int mMeterConsumedColor;
-
- public DataPlanSummaryPreference(Context context) {
- super(context);
- setLayoutResource(R.layout.settings_data_plan_summary_preference);
- }
-
- public DataPlanSummaryPreference(Context context, AttributeSet attrs) {
- super(context, attrs);
- setLayoutResource(R.layout.settings_data_plan_summary_preference);
- }
-
- public void setName(String planName) {
- mName = planName;
- notifyChanged();
- }
-
- public void setDescription(String planDescription) {
- mDescription = planDescription;
- notifyChanged();
- }
-
- public void setPercentageUsage(double percentageUsage) {
- mPercentageUsage = percentageUsage;
- notifyChanged();
- }
-
- public void setUsageTextColor(@ColorRes int planUsageTextColor) {
- mUsageTextColor = planUsageTextColor;
- notifyChanged();
- }
-
- public void setMeterBackgroundColor(@ColorRes int meterBackgroundColor) {
- mMeterBackgroundColor = meterBackgroundColor;
- notifyChanged();
- }
-
- public void setMeterConsumedColor(@ColorRes int meterConsumedColor) {
- mMeterConsumedColor = meterConsumedColor;
- notifyChanged();
- }
-
- @Override
- public void onBindViewHolder(PreferenceViewHolder holder) {
- super.onBindViewHolder(holder);
- holder.setDividerAllowedAbove(false);
- TextView titleView = (TextView) holder.findViewById(android.R.id.title);
- titleView.setTextColor(mUsageTextColor);
- ((TextView) holder.findViewById(android.R.id.text1)).setText(mName);
- ((TextView) holder.findViewById(android.R.id.text2)).setText(mDescription);
- DonutView donutView = (DonutView) holder.findViewById(R.id.donut);
- donutView.setPercentage(mPercentageUsage);
- donutView.setMeterBackgroundColor(mMeterBackgroundColor);
- donutView.setMeterConsumedColor(mMeterConsumedColor);
- }
-}
diff --git a/src/com/android/settings/datausage/DataPlanUsageSummary.java b/src/com/android/settings/datausage/DataUsageSummaryLegacy.java
similarity index 51%
rename from src/com/android/settings/datausage/DataPlanUsageSummary.java
rename to src/com/android/settings/datausage/DataUsageSummaryLegacy.java
index 94893229bf9..6a241ebc506 100644
--- a/src/com/android/settings/datausage/DataPlanUsageSummary.java
+++ b/src/com/android/settings/datausage/DataUsageSummaryLegacy.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2016 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
@@ -14,68 +14,75 @@
package com.android.settings.datausage;
-import static android.net.NetworkPolicy.LIMIT_DISABLED;
-
-import android.annotation.IdRes;
import android.app.Activity;
+import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
-import android.net.NetworkPolicy;
import android.net.NetworkPolicyManager;
import android.net.NetworkTemplate;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.UserManager;
-import android.provider.Settings;
+import android.provider.SearchIndexableResource;
import android.support.annotation.VisibleForTesting;
import android.support.v7.preference.Preference;
-import android.support.v7.preference.PreferenceCategory;
import android.support.v7.preference.PreferenceScreen;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
+import android.text.BidiFormatter;
+import android.text.Spannable;
+import android.text.SpannableString;
import android.text.TextUtils;
import android.text.format.Formatter;
+import android.text.style.RelativeSizeSpan;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
+
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.R;
+import com.android.settings.SummaryPreference;
import com.android.settings.Utils;
import com.android.settings.dashboard.SummaryLoader;
+import com.android.settings.search.BaseSearchIndexProvider;
+import com.android.settings.search.Indexable;
import com.android.settingslib.NetworkPolicyEditor;
+import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.net.DataUsageController;
+
import java.util.ArrayList;
import java.util.List;
/**
- * @deprecated This fragment was supposed to be new version of {@link DataUsageSummary} however
- * unfinished and used nowhere. Keep it in case we may bring it back someday.
+ * Legacy {@link DataUsageSummary} fragment.
*/
-@Deprecated
-public class DataPlanUsageSummary extends DataUsageBase {
+public class DataUsageSummaryLegacy extends DataUsageBaseFragment implements Indexable,
+ DataUsageEditController {
- public static final String KEY_DATA_PLAN_USAGE = "data_plan_usage";
+ private static final String TAG = "DataUsageSummaryLegacy";
- public static final String KEY_STATUS_HEADER = "status_header";
- public static final String KEY_LIMIT_SUMMARY = "plan_summary";
+ static final boolean LOGD = false;
+
+ public static final String KEY_RESTRICT_BACKGROUND = "restrict_background";
+
+ private static final String KEY_STATUS_HEADER = "status_header";
+ private static final String KEY_LIMIT_SUMMARY = "limit_summary";
// Mobile data keys
- public static final String KEY_MOBILE_USAGE_TITLE = "data_usage_mobile_category";
+ public static final String KEY_MOBILE_USAGE_TITLE = "mobile_category";
public static final String KEY_MOBILE_DATA_USAGE_TOGGLE = "data_usage_enable";
+ public static final String KEY_MOBILE_DATA_USAGE = "cellular_data_usage";
+ public static final String KEY_MOBILE_BILLING_CYCLE = "billing_preference";
// Wifi keys
public static final String KEY_WIFI_USAGE_TITLE = "wifi_category";
public static final String KEY_WIFI_DATA_USAGE = "wifi_data_usage";
- public static final String KEY_NETWORK_RESTRICTIONS = "network_restrictions";
private DataUsageController mDataUsageController;
private DataUsageInfoController mDataInfoController;
- private List mDataPlanSummaryPreferenceList;
+ private SummaryPreference mSummaryPreference;
private Preference mLimitPreference;
private NetworkTemplate mDefaultTemplate;
- private NetworkRestrictionsPreference mNetworkRestrictionPreference;
- private WifiManager mWifiManager;
+ private int mDataUsageTemplate;
private NetworkPolicyEditor mPolicyEditor;
@Override
@@ -84,34 +91,58 @@ public class DataPlanUsageSummary extends DataUsageBase {
}
@Override
- public void onCreate(Bundle bundle) {
- super.onCreate(bundle);
+ public void onCreate(Bundle icicle) {
+ super.onCreate(icicle);
final Context context = getContext();
NetworkPolicyManager policyManager = NetworkPolicyManager.from(context);
- mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
mPolicyEditor = new NetworkPolicyEditor(policyManager);
+
+ boolean hasMobileData = DataUsageUtils.hasMobileData(context);
mDataUsageController = new DataUsageController(context);
mDataInfoController = new DataUsageInfoController();
int defaultSubId = DataUsageUtils.getDefaultSubscriptionId(context);
- boolean hasMobileData = DataUsageUtils.hasMobileData(context);
if (defaultSubId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
hasMobileData = false;
}
mDefaultTemplate = DataUsageUtils.getDefaultTemplate(context, defaultSubId);
+ mSummaryPreference = (SummaryPreference) findPreference(KEY_STATUS_HEADER);
- if (hasMobileData) {
- addDataPlanSection(defaultSubId);
+ if (!hasMobileData || !isAdmin()) {
+ removePreference(KEY_RESTRICT_BACKGROUND);
}
-
- if (DataUsageUtils.hasWifiRadio(context)) {
+ if (hasMobileData) {
+ mLimitPreference = findPreference(KEY_LIMIT_SUMMARY);
+ List subscriptions =
+ services.mSubscriptionManager.getActiveSubscriptionInfoList();
+ if (subscriptions == null || subscriptions.size() == 0) {
+ addMobileSection(defaultSubId);
+ }
+ for (int i = 0; subscriptions != null && i < subscriptions.size(); i++) {
+ SubscriptionInfo subInfo = subscriptions.get(i);
+ if (subscriptions.size() > 1) {
+ addMobileSection(subInfo.getSubscriptionId(), subInfo);
+ } else {
+ addMobileSection(subInfo.getSubscriptionId());
+ }
+ }
+ mSummaryPreference.setSelectable(true);
+ } else {
+ removePreference(KEY_LIMIT_SUMMARY);
+ mSummaryPreference.setSelectable(false);
+ }
+ boolean hasWifiRadio = DataUsageUtils.hasWifiRadio(context);
+ if (hasWifiRadio) {
addWifiSection();
}
-
if (hasEthernet(context)) {
addEthernetSection();
}
+ mDataUsageTemplate = hasMobileData ? R.string.cell_data_template
+ : hasWifiRadio ? R.string.wifi_data_template
+ : R.string.ethernet_data_template;
+
setHasOptionsMenu(true);
}
@@ -127,7 +158,9 @@ public class DataPlanUsageSummary extends DataUsageBase {
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.data_usage_menu_cellular_networks: {
- final Intent intent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
+ final Intent intent = new Intent(Intent.ACTION_MAIN);
+ intent.setComponent(new ComponentName("com.android.phone",
+ "com.android.phone.MobileNetworkSettings"));
startActivity(intent);
return true;
}
@@ -135,52 +168,28 @@ public class DataPlanUsageSummary extends DataUsageBase {
return false;
}
- private void addDataPlanSection(int defaultSubId) {
- Context context = getPrefContext();
- addPreferencesFromResource(R.xml.data_plan_usage);
- PreferenceScreen screen = getPreferenceScreen();
- screen.setTitle(context.getString(R.string.data_usage_summary_title));
-
- PreferenceCategory preferenceCategory =
- (PreferenceCategory) findPreference(KEY_DATA_PLAN_USAGE);
- screen.addPreference(preferenceCategory);
-
- Preference dataPlansSyncTimePreference = new Preference(context);
- dataPlansSyncTimePreference.setLayoutResource(R.layout.data_plans_sync_time_preference);
- dataPlansSyncTimePreference.setTitle(MockDataPlanUsage.SYNC_TIME);
- preferenceCategory.addPreference(dataPlansSyncTimePreference);
-
- mDataPlanSummaryPreferenceList = new ArrayList<>(MockDataPlanUsage.DATA_PLAN_USAGES.length);
- for (int i = 0; i < MockDataPlanUsage.DATA_PLAN_USAGES.length; i++) {
- DataPlanSummaryPreference dataPlanSummaryPreference =
- new DataPlanSummaryPreference(context);
- dataPlanSummaryPreference.setKey(KEY_STATUS_HEADER + (i + 1));
- mDataPlanSummaryPreferenceList.add(dataPlanSummaryPreference);
- preferenceCategory.addPreference(dataPlanSummaryPreference);
+ @Override
+ public boolean onPreferenceTreeClick(Preference preference) {
+ if (preference == findPreference(KEY_STATUS_HEADER)) {
+ BillingCycleSettings.BytesEditorFragment.show(this, false);
+ return false;
}
+ return super.onPreferenceTreeClick(preference);
+ }
- Preference preference = new Preference(context);
- preference.setLayoutResource(R.layout.manage_data_plans_preference);
- preferenceCategory.addPreference(preference);
- setPreferenceScreen(screen);
+ @Override
+ protected int getPreferenceScreenResId() {
+ return R.xml.data_usage_legacy;
+ }
- mLimitPreference = findPreference(KEY_LIMIT_SUMMARY);
- List subscriptions =
- services.mSubscriptionManager.getActiveSubscriptionInfoList();
+ @Override
+ protected String getLogTag() {
+ return TAG;
+ }
- if (subscriptions == null || subscriptions.isEmpty()) {
- addMobileSection(defaultSubId);
- }
-
- for (int i = 0, subscriptionsSize = subscriptions != null ? subscriptions.size() : 0;
- i < subscriptionsSize; i++) {
- SubscriptionInfo subInfo = subscriptions.get(i);
- if (subscriptionsSize > 1) {
- addMobileSection(subInfo.getSubscriptionId(), subInfo);
- } else {
- addMobileSection(subInfo.getSubscriptionId());
- }
- }
+ @Override
+ protected List getPreferenceControllers(Context context) {
+ return null;
}
private void addMobileSection(int subId) {
@@ -189,11 +198,11 @@ public class DataPlanUsageSummary extends DataUsageBase {
private void addMobileSection(int subId, SubscriptionInfo subInfo) {
TemplatePreferenceCategory category = (TemplatePreferenceCategory)
- inflatePreferences(R.xml.data_plan_usage_cell_data_preference_screen);
+ inflatePreferences(R.xml.data_usage_cellular);
category.setTemplate(getNetworkTemplate(subId), subId, services);
category.pushTemplates(services);
if (subInfo != null && !TextUtils.isEmpty(subInfo.getDisplayName())) {
- Preference title = category.findPreference(KEY_MOBILE_USAGE_TITLE);
+ Preference title = category.findPreference(KEY_MOBILE_USAGE_TITLE);
title.setTitle(subInfo.getDisplayName());
}
}
@@ -201,18 +210,16 @@ public class DataPlanUsageSummary extends DataUsageBase {
private void addWifiSection() {
TemplatePreferenceCategory category = (TemplatePreferenceCategory)
inflatePreferences(R.xml.data_usage_wifi);
- category.setTemplate(NetworkTemplate.buildTemplateWifiWildcard(), 0 /* subId */, services);
- mNetworkRestrictionPreference =
- (NetworkRestrictionsPreference) category.findPreference(KEY_NETWORK_RESTRICTIONS);
+ category.setTemplate(NetworkTemplate.buildTemplateWifiWildcard(), 0, services);
}
private void addEthernetSection() {
TemplatePreferenceCategory category = (TemplatePreferenceCategory)
inflatePreferences(R.xml.data_usage_ethernet);
- category.setTemplate(NetworkTemplate.buildTemplateEthernet(), 0 /* subId */, services);
+ category.setTemplate(NetworkTemplate.buildTemplateEthernet(), 0, services);
}
- private Preference inflatePreferences(@IdRes int resId) {
+ private Preference inflatePreferences(int resId) {
PreferenceScreen rootPreferences = getPreferenceManager().inflateFromResource(
getPrefContext(), resId, null);
Preference pref = rootPreferences.getPreference(0);
@@ -238,32 +245,51 @@ public class DataPlanUsageSummary extends DataUsageBase {
updateState();
}
+ @VisibleForTesting
+ static CharSequence formatUsage(Context context, String template, long usageLevel) {
+ final float LARGER_SIZE = 1.25f * 1.25f; // (1/0.8)^2
+ final float SMALLER_SIZE = 1.0f / LARGER_SIZE; // 0.8^2
+ final int FLAGS = Spannable.SPAN_INCLUSIVE_INCLUSIVE;
+
+ final Formatter.BytesResult usedResult = Formatter.formatBytes(context.getResources(),
+ usageLevel, Formatter.FLAG_CALCULATE_ROUNDED);
+ final SpannableString enlargedValue = new SpannableString(usedResult.value);
+ enlargedValue.setSpan(new RelativeSizeSpan(LARGER_SIZE), 0, enlargedValue.length(), FLAGS);
+
+ final SpannableString amountTemplate = new SpannableString(
+ context.getString(com.android.internal.R.string.fileSizeSuffix)
+ .replace("%1$s", "^1").replace("%2$s", "^2"));
+ final CharSequence formattedUsage = TextUtils.expandTemplate(amountTemplate,
+ enlargedValue, usedResult.units);
+
+ final SpannableString fullTemplate = new SpannableString(template);
+ fullTemplate.setSpan(new RelativeSizeSpan(SMALLER_SIZE), 0, fullTemplate.length(), FLAGS);
+ return TextUtils.expandTemplate(fullTemplate,
+ BidiFormatter.getInstance().unicodeWrap(formattedUsage.toString()));
+ }
+
private void updateState() {
DataUsageController.DataUsageInfo info = mDataUsageController.getDataUsageInfo(
mDefaultTemplate);
-
Context context = getContext();
mDataInfoController.updateDataLimit(info,
services.mPolicyEditor.getPolicy(mDefaultTemplate));
- // TODO(b/63391323): Get rid of MockDataPlanUsage once we integrate with data plan APIs
- if (mDataPlanSummaryPreferenceList != null && !mDataPlanSummaryPreferenceList.isEmpty()) {
- MockDataPlanUsage[] dataPlanUsages = MockDataPlanUsage.getDataPlanUsage();
- for (int i = 0; i < dataPlanUsages.length; i++) {
- DataPlanSummaryPreference dataPlanSummaryPreference =
- mDataPlanSummaryPreferenceList.get(i);
- MockDataPlanUsage dataPlanUsage = dataPlanUsages[i];
- dataPlanSummaryPreference.setTitle(dataPlanUsage.mUsage);
- dataPlanSummaryPreference.setUsageTextColor(dataPlanUsage.mUsageTextColor);
- dataPlanSummaryPreference.setName(dataPlanUsage.mName);
- dataPlanSummaryPreference.setPercentageUsage(dataPlanUsage.mPercentageUsage);
- dataPlanSummaryPreference
- .setMeterBackgroundColor(dataPlanUsage.mMeterBackgroundColor);
- dataPlanSummaryPreference.setMeterConsumedColor(dataPlanUsage.mMeterConsumedColor);
- dataPlanSummaryPreference.setDescription(dataPlanUsage.mDescription);
+ if (mSummaryPreference != null) {
+ mSummaryPreference.setTitle(
+ formatUsage(context, getString(mDataUsageTemplate), info.usageLevel));
+ final long limit = mDataInfoController.getSummaryLimit(info);
+ mSummaryPreference.setSummary(info.period);
+ if (limit <= 0) {
+ mSummaryPreference.setChartEnabled(false);
+ } else {
+ mSummaryPreference.setChartEnabled(true);
+ mSummaryPreference.setLabels(Formatter.formatFileSize(context, 0),
+ Formatter.formatFileSize(context, limit));
+ mSummaryPreference.setRatios(info.usageLevel / (float) limit, 0,
+ (limit - info.usageLevel) / (float) limit);
}
}
-
if (mLimitPreference != null && (info.warningLevel > 0 || info.limitLevel > 0)) {
String warning = Formatter.formatFileSize(context, info.warningLevel);
String limit = Formatter.formatFileSize(context, info.limitLevel);
@@ -273,10 +299,8 @@ public class DataPlanUsageSummary extends DataUsageBase {
mLimitPreference.setSummary(null);
}
- updateNetworkRestrictionSummary(mNetworkRestrictionPreference);
-
PreferenceScreen screen = getPreferenceScreen();
- for (int i = 1, preferenceCount = screen.getPreferenceCount(); i < preferenceCount; i++) {
+ for (int i = 1; i < screen.getPreferenceCount(); i++) {
((TemplatePreferenceCategory) screen.getPreference(i)).pushTemplates(services);
}
}
@@ -286,40 +310,19 @@ public class DataPlanUsageSummary extends DataUsageBase {
return MetricsEvent.DATA_USAGE_SUMMARY;
}
- @VisibleForTesting
- void updateNetworkRestrictionSummary(NetworkRestrictionsPreference preference) {
- if (preference == null) {
- return;
- }
- mPolicyEditor.read();
- int count = 0;
- List configuredNetworks = mWifiManager.getConfiguredNetworks();
- for (int i = 0, configuredNetworksSize = configuredNetworks.size();
- i < configuredNetworksSize; i++) {
- WifiConfiguration config = configuredNetworks.get(i);
- if (isMetered(config)) {
- count++;
- }
- }
- preference.setSummary(getResources().getQuantityString(
- R.plurals.network_restrictions_summary, count, count));
+ @Override
+ public NetworkPolicyEditor getNetworkPolicyEditor() {
+ return services.mPolicyEditor;
}
- @VisibleForTesting
- boolean isMetered(WifiConfiguration config) {
- if (config.SSID == null) {
- return false;
- }
- final String networkId = config.isPasspoint() ? config.providerFriendlyName : config.SSID;
- final NetworkPolicy policy =
- mPolicyEditor.getPolicyMaybeUnquoted(NetworkTemplate.buildTemplateWifi(networkId));
- if (policy == null) {
- return false;
- }
- if (policy.limitBytes != LIMIT_DISABLED) {
- return true;
- }
- return policy.metered;
+ @Override
+ public NetworkTemplate getNetworkTemplate() {
+ return mDefaultTemplate;
+ }
+
+ @Override
+ public void updateDataUsage() {
+ updateState();
}
private static class SummaryProvider
@@ -354,6 +357,52 @@ public class DataPlanUsageSummary extends DataUsageBase {
}
public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY
- = SummaryProvider::new;
-}
+ = SummaryProvider::new;
+ /**
+ * For search
+ */
+ public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+ new BaseSearchIndexProvider() {
+
+ @Override
+ public List getXmlResourcesToIndex(Context context,
+ boolean enabled) {
+ List resources = new ArrayList<>();
+ SearchIndexableResource resource = new SearchIndexableResource(context);
+ resource.xmlResId = R.xml.data_usage;
+ resources.add(resource);
+
+ resource = new SearchIndexableResource(context);
+ resource.xmlResId = R.xml.data_usage_cellular;
+ resources.add(resource);
+
+ resource = new SearchIndexableResource(context);
+ resource.xmlResId = R.xml.data_usage_wifi;
+ resources.add(resource);
+
+ return resources;
+ }
+
+ @Override
+ public List getNonIndexableKeys(Context context) {
+ List keys = super.getNonIndexableKeys(context);
+
+ if (!DataUsageUtils.hasMobileData(context)) {
+ keys.add(KEY_MOBILE_USAGE_TITLE);
+ keys.add(KEY_MOBILE_DATA_USAGE_TOGGLE);
+ keys.add(KEY_MOBILE_DATA_USAGE);
+ keys.add(KEY_MOBILE_BILLING_CYCLE);
+ }
+
+ if (!DataUsageUtils.hasWifiRadio(context)) {
+ keys.add(KEY_WIFI_DATA_USAGE);
+ }
+
+ // This title is named Wifi, and will confuse users.
+ keys.add(KEY_WIFI_USAGE_TITLE);
+
+ return keys;
+ }
+ };
+}
diff --git a/src/com/android/settings/datausage/MockDataPlanUsage.java b/src/com/android/settings/datausage/MockDataPlanUsage.java
deleted file mode 100644
index e3aa97af080..00000000000
--- a/src/com/android/settings/datausage/MockDataPlanUsage.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2017 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.datausage;
-
-import android.graphics.Color;
-
-/**
- * Mock data plan usage data.
- */
-@Deprecated // This class is only needed because we don't have working API yet.
-final class MockDataPlanUsage {
- static final MockDataPlanUsage[] DATA_PLAN_USAGES = new MockDataPlanUsage[3];
- static final String SYNC_TIME = "Today 12:24pm";
- final String mUsage;
- final int mUsageTextColor;
- final String mName;
- final double mPercentageUsage;
- final int mMeterBackgroundColor;
- final int mMeterConsumedColor;
- final String mDescription;
-
- private MockDataPlanUsage(String usage, int usageTextColor, String name,
- double percentageUsage, int meterBackgroundColor, int meterConsumedColor,
- String description) {
- mUsage = usage;
- mUsageTextColor = usageTextColor;
- mName = name;
- mPercentageUsage = percentageUsage;
- mMeterBackgroundColor = meterBackgroundColor;
- mMeterConsumedColor = meterConsumedColor;
- mDescription = description;
- }
-
- static MockDataPlanUsage[] getDataPlanUsage() {
- DATA_PLAN_USAGES[0] = new MockDataPlanUsage("100 MB and 14 days left",
- Color.parseColor("#FF5C94F1"), "GigaMaxLite / 1GB", 0.27D,
- Color.parseColor("#FFDBDCDC"), Color.parseColor("#FF5C94F1"),
- "Premium plan from Telekomsel");
-
- DATA_PLAN_USAGES[1] = new MockDataPlanUsage("1.25 GB and 14 days left",
- Color.parseColor("#FF673AB7"), "GigaMaxLite 4G / 5GB", 0.47D,
- Color.parseColor("#FFDBDCDC"), Color.parseColor("#FF673AB7"),
- "Plenty of 4G data");
-
- DATA_PLAN_USAGES[2] = new MockDataPlanUsage("700 MB and 14 days left",
- Color.parseColor("#FF4CAF50"), "GigaMaxLite Video / 7GB", 0.67D,
- Color.parseColor("#FFDBDCDC"), Color.parseColor("#FF4CAF50"),
- "Use certain video apps for free");
- return DATA_PLAN_USAGES;
- }
-}
diff --git a/src/com/android/settings/deviceinfo/StorageSettings.java b/src/com/android/settings/deviceinfo/StorageSettings.java
index efcf03db02d..209346913bb 100644
--- a/src/com/android/settings/deviceinfo/StorageSettings.java
+++ b/src/com/android/settings/deviceinfo/StorageSettings.java
@@ -236,7 +236,6 @@ public class StorageSettings extends SettingsPreferenceFragment implements Index
Intent intent = Utils.onBuildStartFragmentIntent(getActivity(),
StorageDashboardFragment.class.getName(), args, null,
R.string.storage_settings, null, false, getMetricsCategory());
- intent.putExtra(SettingsDrawerActivity.EXTRA_SHOW_MENU, true);
getActivity().startActivity(intent);
finish();
}
diff --git a/src/com/android/settings/deviceinfo/storage/UserProfileController.java b/src/com/android/settings/deviceinfo/storage/UserProfileController.java
index 4870e7e3fa3..c9fe54e74fe 100644
--- a/src/com/android/settings/deviceinfo/storage/UserProfileController.java
+++ b/src/com/android/settings/deviceinfo/storage/UserProfileController.java
@@ -85,7 +85,6 @@ public class UserProfileController extends AbstractPreferenceController implemen
Intent intent = Utils.onBuildStartFragmentIntent(mContext,
StorageProfileFragment.class.getName(), args, null, 0,
mUser.name, false, MetricsProto.MetricsEvent.DEVICEINFO_STORAGE);
- intent.putExtra(SettingsDrawerActivity.EXTRA_SHOW_MENU, true);
mContext.startActivity(intent);
return true;
}
diff --git a/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java b/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java
index e073456db82..981b0dc1129 100644
--- a/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java
+++ b/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java
@@ -58,6 +58,7 @@ import com.android.settingslib.applications.AppUtils;
import com.android.settingslib.applications.ApplicationsState;
import com.android.settingslib.core.AbstractPreferenceController;
+import com.android.settingslib.utils.StringUtil;
import java.util.ArrayList;
import java.util.List;
@@ -284,10 +285,10 @@ public class AdvancedPowerUsageDetail extends DashboardFragment implements
final int powerMah = bundle.getInt(EXTRA_POWER_USAGE_AMOUNT);
mForegroundPreference.setSummary(
TextUtils.expandTemplate(getText(R.string.battery_used_for),
- Utils.formatElapsedTime(context, foregroundTimeMs, false)));
+ StringUtil.formatElapsedTime(context, foregroundTimeMs, false)));
mBackgroundPreference.setSummary(
TextUtils.expandTemplate(getText(R.string.battery_active_for),
- Utils.formatElapsedTime(context, backgroundTimeMs, false)));
+ StringUtil.formatElapsedTime(context, backgroundTimeMs, false)));
mPowerUsagePreference.setSummary(
getString(R.string.battery_detail_power_percentage, usagePercent, powerMah));
}
diff --git a/src/com/android/settings/fuelgauge/BatteryAppListPreferenceController.java b/src/com/android/settings/fuelgauge/BatteryAppListPreferenceController.java
index 91f35e2533a..2095f25e679 100644
--- a/src/com/android/settings/fuelgauge/BatteryAppListPreferenceController.java
+++ b/src/com/android/settings/fuelgauge/BatteryAppListPreferenceController.java
@@ -18,7 +18,6 @@
package com.android.settings.fuelgauge;
import android.app.Activity;
-import android.app.Fragment;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.BatteryStats;
@@ -31,7 +30,6 @@ import android.support.annotation.VisibleForTesting;
import android.support.v14.preference.PreferenceFragment;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceGroup;
-import android.support.v7.preference.PreferenceManager;
import android.support.v7.preference.PreferenceScreen;
import android.text.TextUtils;
import android.text.format.DateUtils;
@@ -48,16 +46,14 @@ import com.android.settings.R;
import com.android.settings.SettingsActivity;
import com.android.settings.core.FeatureFlags;
import com.android.settings.core.PreferenceControllerMixin;
-import com.android.settings.Utils;
import com.android.settings.fuelgauge.anomaly.Anomaly;
-import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.core.AbstractPreferenceController;
-import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.core.lifecycle.LifecycleObserver;
import com.android.settingslib.core.lifecycle.events.OnDestroy;
import com.android.settingslib.core.lifecycle.events.OnPause;
+import com.android.settingslib.utils.StringUtil;
import java.util.ArrayList;
import java.util.List;
@@ -362,8 +358,8 @@ public class BatteryAppListPreferenceController extends AbstractPreferenceContro
// Only show summary when usage time is longer than one minute
final long usageTimeMs = sipper.usageTimeMs;
if (usageTimeMs >= DateUtils.MINUTE_IN_MILLIS) {
- final CharSequence timeSequence = Utils.formatElapsedTime(mContext, usageTimeMs,
- false);
+ final CharSequence timeSequence =
+ StringUtil.formatElapsedTime(mContext, usageTimeMs, false);
preference.setSummary(
(sipper.drainType != DrainType.APP || mBatteryUtils.shouldHideSipper(sipper))
? timeSequence
diff --git a/src/com/android/settings/fuelgauge/BatteryInfo.java b/src/com/android/settings/fuelgauge/BatteryInfo.java
index 63841307ed8..43465ab3c57 100644
--- a/src/com/android/settings/fuelgauge/BatteryInfo.java
+++ b/src/com/android/settings/fuelgauge/BatteryInfo.java
@@ -25,7 +25,6 @@ import android.os.BatteryStats.HistoryItem;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.WorkerThread;
-import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.SparseIntArray;
@@ -34,8 +33,14 @@ import com.android.settings.Utils;
import com.android.settings.graph.UsageView;
import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.R;
+import com.android.settingslib.utils.PowerUtil;
+import com.android.settingslib.utils.StringUtil;
+import java.util.concurrent.TimeUnit;
public class BatteryInfo {
+ private static final long SEVEN_MINUTES_MICROS = TimeUnit.MINUTES.toMicros(7);
+ private static final long FIFTEEN_MINUTES_MICROS = TimeUnit.MINUTES.toMicros(15);
+ private static final long ONE_DAY_MICROS = TimeUnit.DAYS.toMicros(1);
public CharSequence chargeLabel;
public CharSequence remainingLabel;
@@ -100,7 +105,7 @@ public class BatteryInfo {
if (lastTime >= 0) {
points.put(lastTime, lastLevel);
points.put((int) (timePeriod +
- BatteryUtils.convertUsToMs(remainingTimeUs)),
+ PowerUtil.convertUsToMs(remainingTimeUs)),
mCharging ? 100 : 0);
}
}
@@ -160,7 +165,7 @@ public class BatteryInfo {
PowerUsageFeatureProvider provider =
FeatureFactory.getFactory(context).getPowerUsageFeatureProvider(context);
final long elapsedRealtimeUs =
- BatteryUtils.convertMsToUs(SystemClock.elapsedRealtime());
+ PowerUtil.convertMsToUs(SystemClock.elapsedRealtime());
Intent batteryBroadcast = context.registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
@@ -176,7 +181,7 @@ public class BatteryInfo {
.logRuntime(LOG_TAG, "time for enhanced BatteryInfo", startTime);
return BatteryInfo.getBatteryInfo(context, batteryBroadcast, stats,
elapsedRealtimeUs, shortString,
- BatteryUtils.convertMsToUs(estimate.estimateMillis),
+ PowerUtil.convertMsToUs(estimate.estimateMillis),
estimate.isBasedOnUsage);
}
}
@@ -217,53 +222,61 @@ public class BatteryInfo {
info.statusLabel = Utils.getBatteryStatus(resources, batteryBroadcast);
if (!info.mCharging) {
- if (drainTimeUs > 0) {
- info.remainingTimeUs = drainTimeUs;
- CharSequence timeString = Utils.formatElapsedTime(context,
- BatteryUtils.convertUsToMs(drainTimeUs), false /* withSeconds */);
- info.remainingLabel = TextUtils.expandTemplate(context.getText(shortString ?
- R.string.power_remaining_duration_only_short :
- (basedOnUsage ?
- R.string.power_remaining_duration_only_enhanced :
- R.string.power_remaining_duration_only)), timeString);
- info.chargeLabel = TextUtils.expandTemplate(context.getText(
- shortString ?
- R.string.power_discharging_duration_short :
- basedOnUsage ?
- R.string.power_discharging_duration_enhanced :
- R.string.power_discharging_duration),
- info.batteryPercentString, timeString);
- } else {
- info.remainingLabel = null;
- info.chargeLabel = info.batteryPercentString;
- }
+ updateBatteryInfoDischarging(context, shortString, drainTimeUs, basedOnUsage, info);
} else {
- final long chargeTime = stats.computeChargeTimeRemaining(elapsedRealtimeUs);
- final int status = batteryBroadcast.getIntExtra(BatteryManager.EXTRA_STATUS,
- BatteryManager.BATTERY_STATUS_UNKNOWN);
- info.discharging = false;
- if (chargeTime > 0 && status != BatteryManager.BATTERY_STATUS_FULL) {
- info.remainingTimeUs = chargeTime;
- CharSequence timeString = Utils.formatElapsedTime(context,
- BatteryUtils.convertUsToMs(chargeTime), false /* withSeconds */);
- int resId = R.string.power_charging_duration;
- info.remainingLabel = TextUtils.expandTemplate(context.getText(
- R.string.power_remaining_charging_duration_only), timeString);
- info.chargeLabel = TextUtils.expandTemplate(context.getText(resId),
- info.batteryPercentString, timeString);
- } else {
- final String chargeStatusLabel = resources.getString(
- R.string.battery_info_status_charging_lower);
- info.remainingLabel = null;
- info.chargeLabel = info.batteryLevel == 100 ? info.batteryPercentString :
- resources.getString(R.string.power_charging, info.batteryPercentString,
- chargeStatusLabel);
- }
+ updateBatteryInfoCharging(context, batteryBroadcast, stats, elapsedRealtimeUs, info);
}
BatteryUtils.logRuntime(LOG_TAG, "time for getBatteryInfo", startTime);
return info;
}
+ private static void updateBatteryInfoCharging(Context context, Intent batteryBroadcast,
+ BatteryStats stats, long elapsedRealtimeUs, BatteryInfo info) {
+ final Resources resources = context.getResources();
+ final long chargeTime = stats.computeChargeTimeRemaining(elapsedRealtimeUs);
+ final int status = batteryBroadcast.getIntExtra(BatteryManager.EXTRA_STATUS,
+ BatteryManager.BATTERY_STATUS_UNKNOWN);
+ info.discharging = false;
+ if (chargeTime > 0 && status != BatteryManager.BATTERY_STATUS_FULL) {
+ info.remainingTimeUs = chargeTime;
+ CharSequence timeString = StringUtil.formatElapsedTime(context,
+ PowerUtil.convertUsToMs(info.remainingTimeUs), false /* withSeconds */);
+ int resId = R.string.power_charging_duration;
+ info.remainingLabel = context.getString(
+ R.string.power_remaining_charging_duration_only, timeString);
+ info.chargeLabel = context.getString(resId, info.batteryPercentString, timeString);
+ } else {
+ final String chargeStatusLabel = resources.getString(
+ R.string.battery_info_status_charging_lower);
+ info.remainingLabel = null;
+ info.chargeLabel = info.batteryLevel == 100 ? info.batteryPercentString :
+ resources.getString(R.string.power_charging, info.batteryPercentString,
+ chargeStatusLabel);
+ }
+ }
+
+ private static void updateBatteryInfoDischarging(Context context, boolean shortString,
+ long drainTimeUs, boolean basedOnUsage, BatteryInfo info) {
+ if (drainTimeUs > 0) {
+ info.remainingTimeUs = drainTimeUs;
+ info.remainingLabel = PowerUtil.getBatteryRemainingStringFormatted(
+ context,
+ PowerUtil.convertUsToMs(drainTimeUs),
+ null /* percentageString */,
+ basedOnUsage && !shortString
+ );
+ info.chargeLabel = PowerUtil.getBatteryRemainingStringFormatted(
+ context,
+ PowerUtil.convertUsToMs(drainTimeUs),
+ info.batteryPercentString,
+ basedOnUsage && !shortString
+ );
+ } else {
+ info.remainingLabel = null;
+ info.chargeLabel = info.batteryPercentString;
+ }
+ }
+
public interface BatteryDataParser {
void onParsingStarted(long startTime, long endTime);
diff --git a/src/com/android/settings/fuelgauge/BatteryUtils.java b/src/com/android/settings/fuelgauge/BatteryUtils.java
index 5738c290eb3..da9b7059908 100644
--- a/src/com/android/settings/fuelgauge/BatteryUtils.java
+++ b/src/com/android/settings/fuelgauge/BatteryUtils.java
@@ -43,6 +43,7 @@ import com.android.settings.R;
import com.android.settings.fuelgauge.anomaly.Anomaly;
import com.android.settings.overlay.FeatureFactory;
+import com.android.settingslib.utils.PowerUtil;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
@@ -68,19 +69,18 @@ public class BatteryUtils {
int BACKGROUND = 2;
int ALL = 3;
}
-
private static final String TAG = "BatteryUtils";
private static final int MIN_POWER_THRESHOLD_MILLI_AMP = 5;
+
private static final int SECONDS_IN_HOUR = 60 * 60;
private static BatteryUtils sInstance;
-
private PackageManager mPackageManager;
+
private AppOpsManager mAppOpsManager;
private Context mContext;
@VisibleForTesting
PowerUsageFeatureProvider mPowerUsageFeatureProvider;
-
public static BatteryUtils getInstance(Context context) {
if (sInstance == null || sInstance.isDataCorrupted()) {
sInstance = new BatteryUtils(context);
@@ -131,29 +131,30 @@ public class BatteryUtils {
// Return the min value of STATE_TOP time and foreground activity time, since both of these
// time have some errors
- return convertUsToMs(
+ return PowerUtil.convertUsToMs(
Math.min(timeUs, getForegroundActivityTotalTimeUs(uid, rawRealTimeUs)));
}
private long getScreenUsageTimeMs(BatteryStats.Uid uid, int which) {
- final long rawRealTimeUs = convertMsToUs(SystemClock.elapsedRealtime());
+ final long rawRealTimeUs = PowerUtil.convertMsToUs(SystemClock.elapsedRealtime());
return getScreenUsageTimeMs(uid, which, rawRealTimeUs);
}
private long getProcessBackgroundTimeMs(BatteryStats.Uid uid, int which) {
- final long rawRealTimeUs = convertMsToUs(SystemClock.elapsedRealtime());
+ final long rawRealTimeUs = PowerUtil.convertMsToUs(SystemClock.elapsedRealtime());
final long timeUs = uid.getProcessStateTime(
BatteryStats.Uid.PROCESS_STATE_BACKGROUND, rawRealTimeUs, which);
Log.v(TAG, "package: " + mPackageManager.getNameForUid(uid.getUid()));
Log.v(TAG, "background time(us): " + timeUs);
- return convertUsToMs(timeUs);
+ return PowerUtil.convertUsToMs(timeUs);
}
private long getProcessForegroundTimeMs(BatteryStats.Uid uid, int which) {
- final long rawRealTimeUs = convertMsToUs(SystemClock.elapsedRealtime());
+ final long rawRealTimeUs = PowerUtil.convertMsToUs(SystemClock.elapsedRealtime());
return getScreenUsageTimeMs(uid, which, rawRealTimeUs)
- + convertUsToMs(getForegroundServiceTotalTimeUs(uid, rawRealTimeUs));
+ + PowerUtil.convertUsToMs(
+ getForegroundServiceTotalTimeUs(uid, rawRealTimeUs));
}
/**
@@ -267,9 +268,10 @@ public class BatteryUtils {
*/
public long calculateRunningTimeBasedOnStatsType(BatteryStatsHelper batteryStatsHelper,
int statsType) {
- final long elapsedRealtimeUs = convertMsToUs(SystemClock.elapsedRealtime());
+ final long elapsedRealtimeUs = PowerUtil.convertMsToUs(
+ SystemClock.elapsedRealtime());
// Return the battery time (millisecond) on status mStatsType
- return convertUsToMs(
+ return PowerUtil.convertUsToMs(
batteryStatsHelper.getStats().computeBatteryRealtime(elapsedRealtimeUs, statsType));
}
@@ -390,25 +392,15 @@ public class BatteryUtils {
}
}
- public static long convertUsToMs(long timeUs) {
- return timeUs / 1000;
- }
-
- public static long convertMsToUs(long timeMs) {
- return timeMs * 1000;
- }
-
public void setForceAppStandby(int uid, String packageName,
int mode) {
final boolean isPreOApp = isLegacyApp(packageName);
if (isPreOApp) {
// Control whether app could run in the background if it is pre O app
- mAppOpsManager.setMode(AppOpsManager.OP_RUN_IN_BACKGROUND, uid, packageName,
- mode);
+ mAppOpsManager.setMode(AppOpsManager.OP_RUN_IN_BACKGROUND, uid, packageName, mode);
}
// Control whether app could run jobs in the background
- mAppOpsManager.setMode(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName,
- mode);
+ mAppOpsManager.setMode(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName, mode);
}
public void initBatteryStatsHelper(BatteryStatsHelper statsHelper, Bundle bundle,
@@ -425,7 +417,8 @@ public class BatteryUtils {
// Stuff we always need to get BatteryInfo
final Intent batteryBroadcast = mContext.registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
- final long elapsedRealtimeUs = BatteryUtils.convertMsToUs(SystemClock.elapsedRealtime());
+ final long elapsedRealtimeUs = PowerUtil.convertMsToUs(
+ SystemClock.elapsedRealtime());
BatteryInfo batteryInfo;
// 0 means we are discharging, anything else means charging
@@ -443,7 +436,7 @@ public class BatteryUtils {
if (estimate != null) {
batteryInfo = BatteryInfo.getBatteryInfo(mContext, batteryBroadcast, stats,
elapsedRealtimeUs, false /* shortString */,
- BatteryUtils.convertMsToUs(estimate.estimateMillis),
+ PowerUtil.convertMsToUs(estimate.estimateMillis),
estimate.isBasedOnUsage);
} else {
batteryInfo = BatteryInfo.getBatteryInfo(mContext, batteryBroadcast, stats,
diff --git a/src/com/android/settings/fuelgauge/DebugEstimatesLoader.java b/src/com/android/settings/fuelgauge/DebugEstimatesLoader.java
index e58ccd339a0..509f96758d2 100644
--- a/src/com/android/settings/fuelgauge/DebugEstimatesLoader.java
+++ b/src/com/android/settings/fuelgauge/DebugEstimatesLoader.java
@@ -22,6 +22,7 @@ import android.os.BatteryStats;
import android.os.SystemClock;
import com.android.internal.os.BatteryStatsHelper;
import com.android.settings.overlay.FeatureFactory;
+import com.android.settingslib.utils.PowerUtil;
import com.android.settingslib.utils.AsyncLoader;
import java.util.ArrayList;
import java.util.List;
@@ -46,7 +47,8 @@ public class DebugEstimatesLoader extends AsyncLoader> {
FeatureFactory.getFactory(context).getPowerUsageFeatureProvider(context);
// get stuff we'll need for both BatteryInfo
- final long elapsedRealtimeUs = BatteryUtils.convertMsToUs(SystemClock.elapsedRealtime());
+ final long elapsedRealtimeUs = PowerUtil.convertMsToUs(
+ SystemClock.elapsedRealtime());
Intent batteryBroadcast = getContext().registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
BatteryStats stats = mStatsHelper.getStats();
@@ -60,7 +62,7 @@ public class DebugEstimatesLoader extends AsyncLoader> {
}
BatteryInfo newInfo = BatteryInfo.getBatteryInfo(getContext(), batteryBroadcast, stats,
elapsedRealtimeUs, false,
- BatteryUtils.convertMsToUs(estimate.estimateMillis),
+ PowerUtil.convertMsToUs(estimate.estimateMillis),
estimate.isBasedOnUsage);
List infos = new ArrayList<>();
diff --git a/src/com/android/settings/fuelgauge/PowerUsageAdvanced.java b/src/com/android/settings/fuelgauge/PowerUsageAdvanced.java
index 6ed92a7cb42..25351d33db5 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageAdvanced.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageAdvanced.java
@@ -47,6 +47,7 @@ import com.android.settings.overlay.FeatureFactory;
import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settingslib.core.AbstractPreferenceController;
+import com.android.settingslib.utils.StringUtil;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
@@ -318,7 +319,7 @@ public class PowerUsageAdvanced extends PowerUsageBase {
return;
}
if (usageData.usageList.size() <= 1) {
- CharSequence timeSequence = Utils.formatElapsedTime(getContext(),
+ CharSequence timeSequence = StringUtil.formatElapsedTime(getContext(),
usageData.totalUsageTimeMs, false);
usageData.summary = usageData.usageType == UsageType.IDLE ? timeSequence
: TextUtils.expandTemplate(getText(R.string.battery_used_for), timeSequence);
diff --git a/src/com/android/settings/fuelgauge/PowerUsageSummary.java b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
index 74dc986b574..3583b142b69 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageSummary.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
@@ -37,10 +37,7 @@ import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.TextView;
-import com.android.internal.hardware.AmbientDisplayConfiguration;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.internal.os.BatterySipper;
-import com.android.internal.os.BatterySipper.DrainType;
import com.android.settings.R;
import com.android.settings.Settings.HighPowerApplicationsActivity;
import com.android.settings.SettingsActivity;
@@ -48,10 +45,7 @@ import com.android.settings.Utils;
import com.android.settings.applications.LayoutPreference;
import com.android.settings.applications.manageapplications.ManageApplications;
import com.android.settings.dashboard.SummaryLoader;
-import com.android.settings.display.AmbientDisplayPreferenceController;
-import com.android.settings.display.AutoBrightnessPreferenceController;
import com.android.settings.display.BatteryPercentagePreferenceController;
-import com.android.settings.display.TimeoutPreferenceController;
import com.android.settings.fuelgauge.anomaly.Anomaly;
import com.android.settings.fuelgauge.anomaly.AnomalyDetectionPolicy;
import com.android.settings.fuelgauge.batterytip.BatteryTipLoader;
@@ -63,6 +57,8 @@ import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import com.android.settingslib.core.lifecycle.Lifecycle;
+import com.android.settingslib.utils.PowerUtil;
+import com.android.settingslib.utils.StringUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -164,12 +160,12 @@ public class PowerUsageSummary extends PowerUsageBase implements OnLongClickList
// be unplugged for a period of time before being willing ot make an estimate.
summary1.setText(mPowerFeatureProvider.getOldEstimateDebugString(
Formatter.formatShortElapsedTime(getContext(),
- BatteryUtils.convertUsToMs(oldInfo.remainingTimeUs))));
+ PowerUtil.convertUsToMs(oldInfo.remainingTimeUs))));
// for this one we can just set the string directly
summary2.setText(mPowerFeatureProvider.getEnhancedEstimateDebugString(
Formatter.formatShortElapsedTime(getContext(),
- BatteryUtils.convertUsToMs(newInfo.remainingTimeUs))));
+ PowerUtil.convertUsToMs(newInfo.remainingTimeUs))));
batteryView.setBatteryLevel(oldInfo.batteryLevel);
batteryView.setCharging(!oldInfo.discharging);
@@ -314,10 +310,10 @@ public class PowerUsageSummary extends PowerUsageBase implements OnLongClickList
final long lastFullChargeTime = mBatteryUtils.calculateLastFullChargeTime(mStatsHelper,
System.currentTimeMillis());
updateLastFullChargePreference(lastFullChargeTime);
- mScreenUsagePref.setSubtitle(Utils.formatElapsedTime(getContext(),
+ mScreenUsagePref.setSubtitle(StringUtil.formatElapsedTime(getContext(),
mBatteryUtils.calculateScreenUsageTime(mStatsHelper), false));
- final CharSequence timeSequence = Utils.formatRelativeTime(context, lastFullChargeTime,
+ final CharSequence timeSequence = StringUtil.formatRelativeTime(context, lastFullChargeTime,
false);
mBatteryAppListPreferenceController.refreshAppListGroup(mStatsHelper,
false /* showAllApps */, timeSequence);
@@ -340,7 +336,7 @@ public class PowerUsageSummary extends PowerUsageBase implements OnLongClickList
@VisibleForTesting
void updateLastFullChargePreference(long timeMs) {
- final CharSequence timeSequence = Utils.formatRelativeTime(getContext(), timeMs, false);
+ final CharSequence timeSequence = StringUtil.formatRelativeTime(getContext(), timeMs, false);
mLastFullChargePref.setSubtitle(timeSequence);
}
diff --git a/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacy.java b/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacy.java
index 605591dda15..e6c49237218 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacy.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacy.java
@@ -69,6 +69,8 @@ import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import com.android.settingslib.core.AbstractPreferenceController;
+import com.android.settingslib.utils.PowerUtil;
+import com.android.settingslib.utils.StringUtil;
import java.util.ArrayList;
import java.util.List;
@@ -210,12 +212,12 @@ public class PowerUsageSummaryLegacy extends PowerUsageBase implements
// be unplugged for a period of time before being willing ot make an estimate.
summary1.setText(mPowerFeatureProvider.getOldEstimateDebugString(
Formatter.formatShortElapsedTime(getContext(),
- BatteryUtils.convertUsToMs(oldInfo.remainingTimeUs))));
+ PowerUtil.convertUsToMs(oldInfo.remainingTimeUs))));
// for this one we can just set the string directly
summary2.setText(mPowerFeatureProvider.getEnhancedEstimateDebugString(
Formatter.formatShortElapsedTime(getContext(),
- BatteryUtils.convertUsToMs(newInfo.remainingTimeUs))));
+ PowerUtil.convertUsToMs(newInfo.remainingTimeUs))));
batteryView.setBatteryLevel(oldInfo.batteryLevel);
batteryView.setCharging(!oldInfo.discharging);
@@ -524,7 +526,7 @@ public class PowerUsageSummaryLegacy extends PowerUsageBase implements
updateScreenPreference();
updateLastFullChargePreference(lastFullChargeTime);
- final CharSequence timeSequence = Utils.formatRelativeTime(context, lastFullChargeTime,
+ final CharSequence timeSequence = StringUtil.formatRelativeTime(context, lastFullChargeTime,
false);
final int resId = mShowAllApps ? R.string.power_usage_list_summary_device
: R.string.power_usage_list_summary;
@@ -653,12 +655,13 @@ public class PowerUsageSummaryLegacy extends PowerUsageBase implements
mStatsHelper.getUsageList(), DrainType.SCREEN);
final long usageTimeMs = sipper != null ? sipper.usageTimeMs : 0;
- mScreenUsagePref.setSubtitle(Utils.formatElapsedTime(getContext(), usageTimeMs, false));
+ mScreenUsagePref.setSubtitle(
+ StringUtil.formatElapsedTime(getContext(), usageTimeMs, false));
}
@VisibleForTesting
void updateLastFullChargePreference(long timeMs) {
- final CharSequence timeSequence = Utils.formatRelativeTime(getContext(), timeMs, false);
+ final CharSequence timeSequence = StringUtil.formatRelativeTime(getContext(), timeMs, false);
mLastFullChargePref.setSubtitle(timeSequence);
}
@@ -685,8 +688,8 @@ public class PowerUsageSummaryLegacy extends PowerUsageBase implements
// Only show summary when usage time is longer than one minute
final long usageTimeMs = sipper.usageTimeMs;
if (usageTimeMs >= DateUtils.MINUTE_IN_MILLIS) {
- final CharSequence timeSequence = Utils.formatElapsedTime(getContext(), usageTimeMs,
- false);
+ final CharSequence timeSequence =
+ StringUtil.formatElapsedTime(getContext(), usageTimeMs, false);
preference.setSummary(
(sipper.drainType != DrainType.APP || mBatteryUtils.shouldHideSipper(sipper))
? timeSequence
diff --git a/src/com/android/settings/fuelgauge/batterytip/BatteryTipDialogFragment.java b/src/com/android/settings/fuelgauge/batterytip/BatteryTipDialogFragment.java
index 66ce3caad01..d93b58909d4 100644
--- a/src/com/android/settings/fuelgauge/batterytip/BatteryTipDialogFragment.java
+++ b/src/com/android/settings/fuelgauge/batterytip/BatteryTipDialogFragment.java
@@ -36,6 +36,7 @@ import com.android.settings.fuelgauge.batterytip.tips.BatteryTip;
import com.android.settings.fuelgauge.batterytip.tips.HighUsageTip;
import com.android.settings.fuelgauge.batterytip.tips.RestrictAppTip;
import com.android.settings.fuelgauge.batterytip.tips.UnrestrictAppTip;
+import com.android.settingslib.utils.StringUtil;
import java.util.List;
@@ -83,7 +84,8 @@ public class BatteryTipDialogFragment extends InstrumentedDialogFragment impleme
return new AlertDialog.Builder(context)
.setMessage(getString(R.string.battery_tip_dialog_message,
- Utils.formatElapsedTime(context, highUsageTip.getScreenTimeMs(),
+ StringUtil.formatElapsedTime(
+ context, highUsageTip.getScreenTimeMs(),
false /* withSeconds */)))
.setView(view)
.setPositiveButton(android.R.string.ok, null)
diff --git a/src/com/android/settings/fuelgauge/batterytip/HighUsageAdapter.java b/src/com/android/settings/fuelgauge/batterytip/HighUsageAdapter.java
index 6c129d8a9be..d982280a4eb 100644
--- a/src/com/android/settings/fuelgauge/batterytip/HighUsageAdapter.java
+++ b/src/com/android/settings/fuelgauge/batterytip/HighUsageAdapter.java
@@ -30,6 +30,7 @@ import android.widget.TextView;
import com.android.settings.R;
import com.android.settings.Utils;
+import com.android.settingslib.utils.StringUtil;
import java.util.List;
/**
@@ -78,7 +79,7 @@ public class HighUsageAdapter extends RecyclerView.Adapter prioritySettings = new HashSet(Arrays.asList(whiteList));
-
-
- public CursorToSearchResultConverter(Context context) {
- mContext = context;
- }
-
- public Set convertCursor(Cursor cursorResults, int baseRank) {
- if (cursorResults == null) {
- return null;
- }
- final Map contextMap = new HashMap<>();
- final Set results = new HashSet<>();
-
- while (cursorResults.moveToNext()) {
- SearchResult result = buildSingleSearchResultFromCursor(contextMap, cursorResults,
- baseRank);
- if (result != null) {
- results.add(result);
- }
- }
- return results;
- }
-
- public static ResultPayload getUnmarshalledPayload(byte[] marshalledPayload,
- int payloadType) {
- try {
- switch (payloadType) {
- case ResultPayload.PayloadType.INTENT:
- return ResultPayloadUtils.unmarshall(marshalledPayload,
- ResultPayload.CREATOR);
- case ResultPayload.PayloadType.INLINE_SWITCH:
- return ResultPayloadUtils.unmarshall(marshalledPayload,
- InlineSwitchPayload.CREATOR);
- case ResultPayload.PayloadType.INLINE_LIST:
- return ResultPayloadUtils.unmarshall(marshalledPayload,
- InlineListPayload.CREATOR);
- }
- } catch (BadParcelableException e) {
- Log.w(TAG, "Error creating parcelable: " + e);
- }
- return null;
- }
-
- private SearchResult buildSingleSearchResultFromCursor(Map contextMap,
- Cursor cursor, int baseRank) {
- final int docId = cursor.getInt(COLUMN_INDEX_ID);
- final String pkgName = cursor.getString(COLUMN_INDEX_INTENT_ACTION_TARGET_PACKAGE);
- final String title = cursor.getString(COLUMN_INDEX_TITLE);
- final String summaryOn = cursor.getString(COLUMN_INDEX_SUMMARY_ON);
- final String className = cursor.getString(COLUMN_INDEX_CLASS_NAME);
- final String key = cursor.getString(COLUMN_INDEX_KEY);
- final String iconResStr = cursor.getString(COLUMN_INDEX_ICON);
- final int payloadType = cursor.getInt(COLUMN_INDEX_PAYLOAD_TYPE);
- final byte[] marshalledPayload = cursor.getBlob(COLUMN_INDEX_PAYLOAD);
- final ResultPayload payload = getUnmarshalledPayload(marshalledPayload, payloadType);
-
- final int rank = getRank(title, baseRank, key);
-
- final SearchResult.Builder builder = new SearchResult.Builder()
- .setStableId(docId)
- .setTitle(title)
- .setSummary(summaryOn)
- .setRank(rank)
- .setIcon(getIconForPackage(contextMap, pkgName, className, iconResStr))
- .setPayload(payload);
- return builder.build();
- }
-
- private Drawable getIconForPackage(Map contextMap, String pkgName,
- String className, String iconResStr) {
- final int iconId = TextUtils.isEmpty(iconResStr)
- ? 0 : Integer.parseInt(iconResStr);
- Drawable icon;
- Context packageContext;
- if (iconId == 0) {
- icon = null;
- } else {
- if (TextUtils.isEmpty(className) && !TextUtils.isEmpty(pkgName)) {
- packageContext = contextMap.get(pkgName);
- if (packageContext == null) {
- try {
- packageContext = mContext.createPackageContext(pkgName, 0);
- } catch (PackageManager.NameNotFoundException e) {
- Log.e(TAG, "Cannot create Context for package: " + pkgName);
- return null;
- }
- contextMap.put(pkgName, packageContext);
- }
- } else {
- packageContext = mContext;
- }
- try {
- icon = packageContext.getDrawable(iconId);
- } catch (Resources.NotFoundException nfe) {
- icon = null;
- }
- }
- return icon;
- }
-
-
- /** Uses the breadcrumbs to determine the offset to the base rank.
- * There are three checks
- * A) If the result is prioritized and the highest base level
- * B) If the query matches the highest level menu title
- * C) If the query is longer than 20
- *
- * If the query matches A, set it to TOP_RANK
- * If the query matches B, the offset is 0.
- * If the query matches C, the offset is 1
-
- * @param title of the result.
- * @param baseRank of the result. Lower if it's a better result.
- * @return
- */
- private int getRank(String title, int baseRank, String key) {
- // The result can only be prioritized if it is a top ranked result.
- if (prioritySettings.contains(key) && baseRank < BASE_RANKS[1]) {
- return TOP_RANK;
- }
- if (title.length() > LONG_TITLE_LENGTH) {
- return baseRank + 1;
- }
- return baseRank;
- }
-}
\ No newline at end of file
diff --git a/src/com/android/settings/search/DatabaseIndexingManager.java b/src/com/android/settings/search/DatabaseIndexingManager.java
index 7b9a6356612..0c02b6757bb 100644
--- a/src/com/android/settings/search/DatabaseIndexingManager.java
+++ b/src/com/android/settings/search/DatabaseIndexingManager.java
@@ -18,10 +18,10 @@
package com.android.settings.search;
-import static com.android.settings.search.CursorToSearchResultConverter.COLUMN_INDEX_ID;
-import static com.android.settings.search.CursorToSearchResultConverter
+import static com.android.settings.search.DatabaseResultLoader.COLUMN_INDEX_ID;
+import static com.android.settings.search.DatabaseResultLoader
.COLUMN_INDEX_INTENT_ACTION_TARGET_PACKAGE;
-import static com.android.settings.search.CursorToSearchResultConverter.COLUMN_INDEX_KEY;
+import static com.android.settings.search.DatabaseResultLoader.COLUMN_INDEX_KEY;
import static com.android.settings.search.DatabaseResultLoader.SELECT_COLUMNS;
import static com.android.settings.search.IndexDatabaseHelper.IndexColumns.CLASS_NAME;
import static com.android.settings.search.IndexDatabaseHelper.IndexColumns.DATA_ENTRIES;
diff --git a/src/com/android/settings/search/DatabaseResultLoader.java b/src/com/android/settings/search/DatabaseResultLoader.java
index 3b5cc476c2e..7902eef2399 100644
--- a/src/com/android/settings/search/DatabaseResultLoader.java
+++ b/src/com/android/settings/search/DatabaseResultLoader.java
@@ -43,14 +43,11 @@ public class DatabaseResultLoader {
};
/**
- * Base ranks defines the best possible rank based on what the query matches.
- * If the query matches the prefix of the first word in the title, the best rank it can be
- * is 1
- * If the query matches the prefix of the other words in the title, the best rank it can be
- * is 3
- * If the query only matches the summary, the best rank it can be is 7
- * If the query only matches keywords or entries, the best rank it can be is 9
+ * These indices are used to match the columns of the this loader's SELECT statement.
+ * These are not necessarily the same order nor similar coverage as the schema defined in
+ * IndexDatabaseHelper
*/
- public static final int[] BASE_RANKS = {1, 3, 7, 9};
-
+ public static final int COLUMN_INDEX_ID = 0;
+ public static final int COLUMN_INDEX_INTENT_ACTION_TARGET_PACKAGE = 8;
+ public static final int COLUMN_INDEX_KEY = 10;
}
\ No newline at end of file
diff --git a/src/com/android/settings/search/SearchIndexableResourcesImpl.java b/src/com/android/settings/search/SearchIndexableResourcesImpl.java
index 2b2551250c3..55235a48595 100644
--- a/src/com/android/settings/search/SearchIndexableResourcesImpl.java
+++ b/src/com/android/settings/search/SearchIndexableResourcesImpl.java
@@ -22,6 +22,7 @@ import com.android.settings.DateTimeSettings;
import com.android.settings.DisplaySettings;
import com.android.settings.LegalSettings;
import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragmentOld;
+import com.android.settings.datausage.DataUsageSummaryLegacy;
import com.android.settings.deviceinfo.aboutphone.MyDeviceInfoFragment;
import com.android.settings.accessibility.AccessibilitySettings;
import com.android.settings.accessibility.AccessibilityShortcutPreferenceFragment;
@@ -112,6 +113,7 @@ public class SearchIndexableResourcesImpl implements SearchIndexableResources {
addIndex(BluetoothSettings.class);
addIndex(SimSettings.class);
addIndex(DataUsageSummary.class);
+ addIndex(DataUsageSummaryLegacy.class);
addIndex(ScreenZoomSettings.class);
addIndex(DisplaySettings.class);
addIndex(AmbientDisplaySettings.class);
diff --git a/src/com/android/settings/search/SearchResult.java b/src/com/android/settings/search/SearchResult.java
deleted file mode 100644
index d96661a38c9..00000000000
--- a/src/com/android/settings/search/SearchResult.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (C) 2017 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.search;
-
-import android.graphics.drawable.Drawable;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.util.List;
-
-/**
- * Data class as an interface for all Search Results.
- */
-public class SearchResult implements Comparable {
-
- private static final String TAG = "SearchResult";
-
- /**
- * Defines the lowest rank for a search result to be considered as ranked. Results with ranks
- * higher than this have no guarantee for sorting order.
- */
- public static final int BOTTOM_RANK = 10;
-
- /**
- * Defines the highest rank for a search result. Used for special search results only.
- */
- public static final int TOP_RANK = 0;
-
- /**
- * The title of the result and main text displayed.
- * Intent Results: Displays as the primary
- */
- public final CharSequence title;
-
- /**
- * Summary / subtitle text
- * Intent Results: Displays the text underneath the title
- */
- final public CharSequence summary;
-
- /**
- * An ordered list of the information hierarchy.
- * Intent Results: Displayed a hierarchy of selections to reach the setting from the home screen
- */
- public final List breadcrumbs;
-
- /**
- * A suggestion for the ranking of the result.
- * Based on Settings Rank:
- * 1 is a near perfect match
- * 9 is the weakest match
- * TODO subject to change
- */
- public final int rank;
-
- /**
- * Identifier for the recycler view adapter.
- */
- @ResultPayload.PayloadType
- public final int viewType;
-
- /**
- * Metadata for the specific result types.
- */
- public final ResultPayload payload;
-
- /**
- * Result's icon.
- */
- public final Drawable icon;
-
- /**
- * Stable id for this object.
- */
- public final int stableId;
-
- protected SearchResult(Builder builder) {
- stableId = builder.mStableId;
- title = builder.mTitle;
- summary = builder.mSummary;
- breadcrumbs = builder.mBreadcrumbs;
- rank = builder.mRank;
- icon = builder.mIcon;
- payload = builder.mResultPayload;
- viewType = payload.getType();
- }
-
- @Override
- public int compareTo(SearchResult searchResult) {
- if (searchResult == null) {
- return -1;
- }
- return this.rank - searchResult.rank;
- }
-
- @Override
- public boolean equals(Object that) {
- if (this == that) {
- return true;
- }
- if (!(that instanceof SearchResult)) {
- return false;
- }
- return this.stableId == ((SearchResult) that).stableId;
- }
-
- @Override
- public int hashCode() {
- return stableId;
- }
-
- public static class Builder {
- protected CharSequence mTitle;
- protected CharSequence mSummary;
- protected List mBreadcrumbs;
- protected int mRank = 42;
- protected ResultPayload mResultPayload;
- protected Drawable mIcon;
- protected int mStableId;
-
- public Builder setTitle(CharSequence title) {
- mTitle = title;
- return this;
- }
-
- public Builder setSummary(CharSequence summary) {
- mSummary = summary;
- return this;
- }
-
- public Builder addBreadcrumbs(List breadcrumbs) {
- mBreadcrumbs = breadcrumbs;
- return this;
- }
-
- public Builder setRank(int rank) {
- if (rank >= 0 && rank <= 9) {
- mRank = rank;
- }
- return this;
- }
-
- public Builder setIcon(Drawable icon) {
- mIcon = icon;
- return this;
- }
-
- public Builder setPayload(ResultPayload payload) {
- mResultPayload = payload;
- return this;
- }
-
- public Builder setStableId(int stableId) {
- mStableId = stableId;
- return this;
- }
-
- public SearchResult build() {
- // Check that all of the mandatory fields are set.
- if (TextUtils.isEmpty(mTitle)) {
- throw new IllegalStateException("SearchResult missing title argument");
- } else if (mStableId == 0) {
- Log.v(TAG, "No stable ID on SearchResult with title: " + mTitle);
- throw new IllegalStateException("SearchResult missing stableId argument");
- } else if (mResultPayload == null) {
- throw new IllegalStateException("SearchResult missing Payload argument");
- }
- return new SearchResult(this);
- }
- }
-}
\ No newline at end of file
diff --git a/src/com/android/settings/users/AutoSyncWorkDataPreferenceController.java b/src/com/android/settings/users/AutoSyncWorkDataPreferenceController.java
index 19701954708..5e8ad2cf9d8 100644
--- a/src/com/android/settings/users/AutoSyncWorkDataPreferenceController.java
+++ b/src/com/android/settings/users/AutoSyncWorkDataPreferenceController.java
@@ -17,6 +17,7 @@ package com.android.settings.users;
import android.app.Fragment;
import android.content.Context;
+import android.os.UserHandle;
import com.android.settings.Utils;
@@ -34,4 +35,10 @@ public class AutoSyncWorkDataPreferenceController extends AutoSyncPersonalDataPr
public String getPreferenceKey() {
return KEY_AUTO_SYNC_WORK_ACCOUNT;
}
+
+ @Override
+ public boolean isAvailable() {
+ return mUserHandle != null && !mUserManager.isManagedProfile() && !mUserManager.isLinkedUser()
+ && mUserManager.getProfiles(UserHandle.myUserId()).size() > 1;
+ }
}
diff --git a/src/com/android/settings/wifi/ConfigureWifiSettings.java b/src/com/android/settings/wifi/ConfigureWifiSettings.java
index b359bf35f0d..1607b74d464 100644
--- a/src/com/android/settings/wifi/ConfigureWifiSettings.java
+++ b/src/com/android/settings/wifi/ConfigureWifiSettings.java
@@ -92,8 +92,6 @@ public class ConfigureWifiSettings extends DashboardFragment {
controllers.add(new WifiInfoPreferenceController(context, getLifecycle(), wifiManager));
controllers.add(new CellularFallbackPreferenceController(context));
controllers.add(new WifiP2pPreferenceController(context, getLifecycle(), wifiManager));
- controllers.add(new WpsPreferenceController(
- context, getLifecycle(), wifiManager, getFragmentManager()));
return controllers;
}
diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java
index ce0ff80c086..69dc1304659 100644
--- a/src/com/android/settings/wifi/WifiSettings.java
+++ b/src/com/android/settings/wifi/WifiSettings.java
@@ -85,16 +85,12 @@ public class WifiSettings extends RestrictedSettingsFragment
private static final String TAG = "WifiSettings";
- /* package */ static final int MENU_ID_WPS_PBC = Menu.FIRST;
- private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1;
private static final int MENU_ID_CONNECT = Menu.FIRST + 6;
private static final int MENU_ID_FORGET = Menu.FIRST + 7;
private static final int MENU_ID_MODIFY = Menu.FIRST + 8;
private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9;
public static final int WIFI_DIALOG_ID = 1;
- /* package */ static final int WPS_PBC_DIALOG_ID = 2;
- private static final int WPS_PIN_DIALOG_ID = 3;
private static final int WRITE_NFC_DIALOG_ID = 6;
// Instance state keys
@@ -109,6 +105,10 @@ public class WifiSettings extends RestrictedSettingsFragment
private static final String PREF_KEY_CONFIGURE_WIFI_SETTINGS = "configure_settings";
private static final String PREF_KEY_SAVED_NETWORKS = "saved_networks";
+ private static boolean isVerboseLoggingEnabled() {
+ return WifiTracker.sVerboseLogging || Log.isLoggable(TAG, Log.VERBOSE);
+ }
+
private final Runnable mUpdateAccessPointsRunnable = () -> {
updateAccessPointPreferences();
};
@@ -371,7 +371,7 @@ public class WifiSettings extends RestrictedSettingsFragment
}
setProgressBarVisible(true);
mWifiTracker.forceUpdate();
- if (WifiTracker.sVerboseLogging) {
+ if (isVerboseLoggingEnabled()) {
Log.i(TAG, "WifiSettings force update APs: " + mWifiTracker.getAccessPoints());
}
getView().removeCallbacks(mUpdateAccessPointsRunnable);
@@ -459,24 +459,6 @@ public class WifiSettings extends RestrictedSettingsFragment
}
}
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // If the user is not allowed to configure wifi, do not handle menu selections.
- if (mIsRestricted) {
- return false;
- }
-
- switch (item.getItemId()) {
- case MENU_ID_WPS_PBC:
- showDialog(WPS_PBC_DIALOG_ID);
- return true;
- case MENU_ID_WPS_PIN:
- showDialog(WPS_PIN_DIALOG_ID);
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
-
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
Preference preference = (Preference) view.getTag();
@@ -635,10 +617,6 @@ public class WifiSettings extends RestrictedSettingsFragment
mSelectedAccessPoint = mDlgAccessPoint;
return mDialog;
- case WPS_PBC_DIALOG_ID:
- return new WpsDialog(getActivity(), WpsInfo.PBC);
- case WPS_PIN_DIALOG_ID:
- return new WpsDialog(getActivity(), WpsInfo.DISPLAY);
case WRITE_NFC_DIALOG_ID:
if (mSelectedAccessPoint != null) {
mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(
@@ -660,10 +638,6 @@ public class WifiSettings extends RestrictedSettingsFragment
switch (dialogId) {
case WIFI_DIALOG_ID:
return MetricsEvent.DIALOG_WIFI_AP_EDIT;
- case WPS_PBC_DIALOG_ID:
- return MetricsEvent.DIALOG_WIFI_PBC;
- case WPS_PIN_DIALOG_ID:
- return MetricsEvent.DIALOG_WIFI_PIN;
case WRITE_NFC_DIALOG_ID:
return MetricsEvent.DIALOG_WIFI_WRITE_NFC;
default:
@@ -762,7 +736,7 @@ public class WifiSettings extends RestrictedSettingsFragment
}
// AccessPoints are sorted by the WifiTracker
final List accessPoints = mWifiTracker.getAccessPoints();
- if (WifiTracker.sVerboseLogging) {
+ if (isVerboseLoggingEnabled()) {
Log.i(TAG, "updateAccessPoints called for: " + accessPoints);
}
diff --git a/src/com/android/settings/wifi/WpsDialog.java b/src/com/android/settings/wifi/WpsDialog.java
deleted file mode 100644
index 440b72d9e05..00000000000
--- a/src/com/android/settings/wifi/WpsDialog.java
+++ /dev/null
@@ -1,297 +0,0 @@
-/*
- * Copyright (C) 2012 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.wifi;
-
-import android.app.AlertDialog;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.net.NetworkInfo;
-import android.net.NetworkInfo.DetailedState;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiManager;
-import android.net.wifi.WpsInfo;
-import android.os.Bundle;
-import android.os.Handler;
-import android.view.View;
-import android.widget.Button;
-import android.widget.ProgressBar;
-import android.widget.TextView;
-
-import com.android.settings.R;
-
-import java.util.Timer;
-import java.util.TimerTask;
-
-
-/**
- * Dialog to show WPS progress.
- */
-public class WpsDialog extends AlertDialog {
-
- private final static String TAG = "WpsDialog";
- private static final String DIALOG_STATE = "android:dialogState";
- private static final String DIALOG_MSG_STRING = "android:dialogMsg";
-
- private View mView;
- private TextView mTextView;
- private ProgressBar mTimeoutBar;
- private ProgressBar mProgressBar;
- private Button mButton;
- private Timer mTimer;
-
- private static final int WPS_TIMEOUT_S = 120;
-
- private WifiManager mWifiManager;
- private WifiManager.WpsCallback mWpsListener;
- private int mWpsSetup;
-
- private final IntentFilter mFilter;
- private BroadcastReceiver mReceiver;
-
- private Context mContext;
- private Handler mHandler = new Handler();
- private String mMsgString = "";
-
- private enum DialogState {
- WPS_INIT,
- WPS_START,
- WPS_COMPLETE,
- CONNECTED, //WPS + IP config is done
- WPS_FAILED
- }
- DialogState mDialogState = DialogState.WPS_INIT;
-
- public WpsDialog(Context context, int wpsSetup) {
- super(context);
- mContext = context;
- mWpsSetup = wpsSetup;
-
- class WpsListener extends WifiManager.WpsCallback {
-
- public void onStarted(String pin) {
- if (pin != null) {
- updateDialog(DialogState.WPS_START, String.format(
- mContext.getString(R.string.wifi_wps_onstart_pin), pin));
- } else {
- updateDialog(DialogState.WPS_START, mContext.getString(
- R.string.wifi_wps_onstart_pbc));
- }
- }
-
- public void onSucceeded() {
- updateDialog(DialogState.WPS_COMPLETE,
- mContext.getString(R.string.wifi_wps_complete));
- }
-
- public void onFailed(int reason) {
- String msg;
- switch (reason) {
- case WifiManager.WPS_OVERLAP_ERROR:
- msg = mContext.getString(R.string.wifi_wps_failed_overlap);
- break;
- case WifiManager.WPS_WEP_PROHIBITED:
- msg = mContext.getString(R.string.wifi_wps_failed_wep);
- break;
- case WifiManager.WPS_TKIP_ONLY_PROHIBITED:
- msg = mContext.getString(R.string.wifi_wps_failed_tkip);
- break;
- case WifiManager.IN_PROGRESS:
- msg = mContext.getString(R.string.wifi_wps_in_progress);
- break;
- default:
- msg = mContext.getString(R.string.wifi_wps_failed_generic);
- break;
- }
- updateDialog(DialogState.WPS_FAILED, msg);
- }
- }
-
- mWpsListener = new WpsListener();
-
-
- mFilter = new IntentFilter();
- mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
- mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
- mReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- handleEvent(context, intent);
- }
- };
- setCanceledOnTouchOutside(false);
- }
-
- @Override
- public Bundle onSaveInstanceState () {
- Bundle bundle = super.onSaveInstanceState();
- bundle.putString(DIALOG_STATE, mDialogState.toString());
- bundle.putString(DIALOG_MSG_STRING, mMsgString.toString());
- return bundle;
- }
-
- @Override
- public void onRestoreInstanceState(Bundle savedInstanceState) {
- if (savedInstanceState != null) {
- super.onRestoreInstanceState(savedInstanceState);
- DialogState dialogState = mDialogState.valueOf(savedInstanceState.getString(DIALOG_STATE));
- String msg = savedInstanceState.getString(DIALOG_MSG_STRING);
- updateDialog(dialogState, msg);
- if (dialogState == DialogState.WPS_START) {
- startWps();
- }
- }
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- mView = getLayoutInflater().inflate(R.layout.wifi_wps_dialog, null);
-
- mTextView = (TextView) mView.findViewById(R.id.wps_dialog_txt);
- mTextView.setText(R.string.wifi_wps_setup_msg);
-
- mTimeoutBar = ((ProgressBar) mView.findViewById(R.id.wps_timeout_bar));
- mTimeoutBar.setMax(WPS_TIMEOUT_S);
- mTimeoutBar.setProgress(0);
-
- mProgressBar = ((ProgressBar) mView.findViewById(R.id.wps_progress_bar));
- mProgressBar.setVisibility(View.GONE);
-
- mButton = ((Button) mView.findViewById(R.id.wps_dialog_btn));
- mButton.setText(R.string.wifi_cancel);
- mButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- dismiss();
- }
- });
-
- mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
-
- setView(mView);
- if (savedInstanceState == null) {
- startWps();
- }
- super.onCreate(savedInstanceState);
- }
-
- @Override
- protected void onStart() {
- /*
- * increment timeout bar per second.
- */
- mTimer = new Timer(false);
- mTimer.schedule(new TimerTask() {
- @Override
- public void run() {
- mHandler.post(new Runnable() {
-
- @Override
- public void run() {
- mTimeoutBar.incrementProgressBy(1);
- }
- });
- }
- }, 1000, 1000);
-
- mContext.registerReceiver(mReceiver, mFilter);
-
- }
-
- @Override
- protected void onStop() {
- if (mDialogState != DialogState.WPS_COMPLETE) {
- mWifiManager.cancelWps(null);
- }
-
- if (mReceiver != null) {
- mContext.unregisterReceiver(mReceiver);
- mReceiver = null;
- }
-
- if (mTimer != null) {
- mTimer.cancel();
- }
- }
-
- private void updateDialog(final DialogState state, final String msg) {
- if (mDialogState.ordinal() >= state.ordinal()) {
- //ignore.
- return;
- }
- mDialogState = state;
- mMsgString = msg;
-
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- switch(state) {
- case WPS_COMPLETE:
- mTimeoutBar.setVisibility(View.GONE);
- mProgressBar.setVisibility(View.VISIBLE);
- break;
- case CONNECTED:
- case WPS_FAILED:
- mButton.setText(mContext.getString(R.string.dlg_ok));
- mTimeoutBar.setVisibility(View.GONE);
- mProgressBar.setVisibility(View.GONE);
- if (mReceiver != null) {
- mContext.unregisterReceiver(mReceiver);
- mReceiver = null;
- }
- break;
- }
- mTextView.setText(msg);
- }
- });
- }
-
- private void handleEvent(Context context, Intent intent) {
- String action = intent.getAction();
- if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
- final int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
- WifiManager.WIFI_STATE_UNKNOWN);
- if (state == WifiManager.WIFI_STATE_DISABLED) {
- if (mTimer != null) {
- mTimer.cancel();
- mTimer = null;
- }
- String msg = mContext.getString(R.string.wifi_wps_failed_wifi_disconnected);
- updateDialog(DialogState.WPS_FAILED, msg);
- }
- } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
- NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
- WifiManager.EXTRA_NETWORK_INFO);
- final NetworkInfo.DetailedState state = info.getDetailedState();
- if (state == DetailedState.CONNECTED &&
- mDialogState == DialogState.WPS_COMPLETE) {
- WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
- if (wifiInfo != null) {
- String msg = String.format(mContext.getString(
- R.string.wifi_wps_connected), wifiInfo.getSSID());
- updateDialog(DialogState.CONNECTED, msg);
- }
- }
- }
- }
-
- private void startWps() {
- WpsInfo wpsConfig = new WpsInfo();
- wpsConfig.setup = mWpsSetup;
- mWifiManager.startWps(wpsConfig, mWpsListener);
- }
-}
diff --git a/src/com/android/settings/wifi/WpsPreferenceController.java b/src/com/android/settings/wifi/WpsPreferenceController.java
deleted file mode 100644
index f6365936707..00000000000
--- a/src/com/android/settings/wifi/WpsPreferenceController.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2017 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.wifi;
-
-import android.app.Dialog;
-import android.app.FragmentManager;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.net.wifi.WifiManager;
-import android.net.wifi.WpsInfo;
-import android.os.Bundle;
-import android.support.annotation.VisibleForTesting;
-import android.support.v7.preference.Preference;
-import android.support.v7.preference.PreferenceScreen;
-
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settings.core.PreferenceControllerMixin;
-import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
-import com.android.settingslib.core.AbstractPreferenceController;
-import com.android.settingslib.core.lifecycle.Lifecycle;
-import com.android.settingslib.core.lifecycle.LifecycleObserver;
-import com.android.settingslib.core.lifecycle.events.OnPause;
-import com.android.settingslib.core.lifecycle.events.OnResume;
-
-/**
- * {@link PreferenceControllerMixin} that shows Dialog for WPS progress. Disabled when Wi-Fi is off.
- */
-public class WpsPreferenceController extends AbstractPreferenceController
- implements PreferenceControllerMixin, LifecycleObserver, OnPause, OnResume {
-
- private static final String KEY_WPS_PUSH = "wps_push_button";
- private static final String KEY_WPS_PIN = "wps_pin_entry";
-
- private final WifiManager mWifiManager;
- private final FragmentManager mFragmentManager;
- @VisibleForTesting
- final BroadcastReceiver mReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- togglePreferences();
- }
- };
- private final IntentFilter mFilter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
-
- private Preference mWpsPushPref;
- private Preference mWpsPinPref;
-
- public WpsPreferenceController(
- Context context,
- Lifecycle lifecycle,
- WifiManager wifiManager,
- FragmentManager fragmentManager) {
- super(context);
- mWifiManager = wifiManager;
- mFragmentManager = fragmentManager;
- lifecycle.addObserver(this);
- }
-
- @Override
- public boolean isAvailable() {
- // Always show preference.
- return true;
- }
-
- @Override
- public String getPreferenceKey() {
- // Returns null because this controller contains more than 1 preference.
- return null;
- }
-
- @Override
- public void displayPreference(PreferenceScreen screen) {
- super.displayPreference(screen);
- mWpsPushPref = screen.findPreference(KEY_WPS_PUSH);
- mWpsPinPref = screen.findPreference(KEY_WPS_PIN);
- if (mWpsPushPref == null || mWpsPinPref == null) {
- return;
- }
- // WpsDialog: Create the dialog like WifiSettings does.
- mWpsPushPref.setOnPreferenceClickListener((arg) -> {
- WpsFragment wpsFragment = new WpsFragment(WpsInfo.PBC);
- wpsFragment.show(mFragmentManager, KEY_WPS_PUSH);
- return true;
- }
- );
-
- // WpsDialog: Create the dialog like WifiSettings does.
- mWpsPinPref.setOnPreferenceClickListener((arg) -> {
- WpsFragment wpsFragment = new WpsFragment(WpsInfo.DISPLAY);
- wpsFragment.show(mFragmentManager, KEY_WPS_PIN);
- return true;
- });
- togglePreferences();
- }
-
- @Override
- public void onResume() {
- mContext.registerReceiver(mReceiver, mFilter);
- }
-
- @Override
- public void onPause() {
- mContext.unregisterReceiver(mReceiver);
- }
-
- private void togglePreferences() {
- if (mWpsPushPref != null && mWpsPinPref != null) {
- boolean enabled = mWifiManager.isWifiEnabled();
- mWpsPushPref.setEnabled(enabled);
- mWpsPinPref.setEnabled(enabled);
- }
- }
-
- /**
- * Fragment for Dialog to show WPS progress.
- */
- public static class WpsFragment extends InstrumentedDialogFragment {
- private static int mWpsSetup;
-
- // Public default constructor is required for rotation.
- public WpsFragment() {
- super();
- }
-
- public WpsFragment(int wpsSetup) {
- super();
- mWpsSetup = wpsSetup;
- }
-
- @Override
- public int getMetricsCategory() {
- return MetricsEvent.DIALOG_WPS_SETUP;
- }
-
- @Override
- public Dialog onCreateDialog(Bundle savedInstanceState) {
- return new WpsDialog(getActivity(), mWpsSetup);
- }
- }
-}
diff --git a/tests/robotests/assets/grandfather_not_implementing_indexable b/tests/robotests/assets/grandfather_not_implementing_indexable
index ece35fb37ab..5a3c0446bb6 100644
--- a/tests/robotests/assets/grandfather_not_implementing_indexable
+++ b/tests/robotests/assets/grandfather_not_implementing_indexable
@@ -15,7 +15,6 @@ com.android.settings.applications.VrListenerSettings
com.android.settings.inputmethod.UserDictionaryList
com.android.settings.datausage.DataSaverSummary
com.android.settings.datausage.AppDataUsage
-com.android.settings.datausage.DataPlanUsageSummary
com.android.settings.accessibility.FontSizePreferenceFragmentForSetupWizard
com.android.settings.applications.ManageDomainUrls
com.android.settings.applications.appinfo.WriteSettingsDetails
@@ -72,4 +71,4 @@ com.android.settings.TetherSettings
com.android.settings.ApnEditor
com.android.settings.UserCredentialsSettings
com.android.settings.TestingSettings
-com.android.settings.applications.DirectoryAccessDetails
\ No newline at end of file
+com.android.settings.applications.DirectoryAccessDetails
diff --git a/tests/robotests/src/com/android/settings/SettingsActivityTest.java b/tests/robotests/src/com/android/settings/SettingsActivityTest.java
index 509ecdad1a9..25abd4d84ea 100644
--- a/tests/robotests/src/com/android/settings/SettingsActivityTest.java
+++ b/tests/robotests/src/com/android/settings/SettingsActivityTest.java
@@ -16,7 +16,6 @@
package com.android.settings;
-import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doReturn;
@@ -28,17 +27,14 @@ import static org.mockito.Mockito.when;
import android.app.ActivityManager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
-import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
-import android.os.Bundle;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
@@ -48,9 +44,6 @@ import org.robolectric.annotation.Config;
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class SettingsActivityTest {
- @Mock(answer = Answers.RETURNS_DEEP_STUBS)
- private Context mContext;
-
@Mock
private FragmentManager mFragmentManager;
@Mock
@@ -84,13 +77,4 @@ public class SettingsActivityTest {
verify(mTaskDescription).setIcon(nullable(Bitmap.class));
}
-
- @Test
- public void testSaveState_EnabledHomeSaved() {
- mActivity.mDisplayHomeAsUpEnabled = true;
- Bundle bundle = new Bundle();
- mActivity.saveState(bundle);
-
- assertThat((boolean) bundle.get(SettingsActivity.SAVE_KEY_SHOW_HOME_AS_UP)).isTrue();
- }
}
diff --git a/tests/robotests/src/com/android/settings/UtilsTest.java b/tests/robotests/src/com/android/settings/UtilsTest.java
index fb571bb5cf3..d1c4a55c631 100644
--- a/tests/robotests/src/com/android/settings/UtilsTest.java
+++ b/tests/robotests/src/com/android/settings/UtilsTest.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2018 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 com.google.common.truth.Truth.assertThat;
@@ -25,9 +41,7 @@ import android.os.UserManager;
import android.os.storage.DiskInfo;
import android.os.storage.StorageManager;
import android.os.storage.VolumeInfo;
-import android.text.SpannableStringBuilder;
import android.text.format.DateUtils;
-import android.text.style.TtsSpan;
import android.util.IconDrawableFactory;
import android.widget.EditText;
import android.widget.TextView;
@@ -35,6 +49,7 @@ import android.widget.TextView;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.wrapper.DevicePolicyManagerWrapper;
+import com.android.settingslib.utils.StringUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -109,175 +124,6 @@ public class UtilsTest {
assertThat(Utils.getWifiIpAddresses(mContext)).isNull();
}
- @Test
- public void testFormatElapsedTime_WithSeconds_ShowSeconds() {
- final double testMillis = 5 * DateUtils.MINUTE_IN_MILLIS + 30 * DateUtils.SECOND_IN_MILLIS;
- final String expectedTime = "5m 30s";
-
- assertThat(Utils.formatElapsedTime(mContext, testMillis, true).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatElapsedTime_NoSeconds_DoNotShowSeconds() {
- final double testMillis = 5 * DateUtils.MINUTE_IN_MILLIS + 30 * DateUtils.SECOND_IN_MILLIS;
- final String expectedTime = "6m";
-
- assertThat(Utils.formatElapsedTime(mContext, testMillis, false).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatElapsedTime_TimeMoreThanOneDay_ShowCorrectly() {
- final double testMillis = 2 * DateUtils.DAY_IN_MILLIS
- + 4 * DateUtils.HOUR_IN_MILLIS + 15 * DateUtils.MINUTE_IN_MILLIS;
- final String expectedTime = "2d 4h 15m";
-
- assertThat(Utils.formatElapsedTime(mContext, testMillis, false).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatElapsedTime_ZeroFieldsInTheMiddleDontShow() {
- final double testMillis = 2 * DateUtils.DAY_IN_MILLIS + 15 * DateUtils.MINUTE_IN_MILLIS;
- final String expectedTime = "2d 15m";
-
- assertThat(Utils.formatElapsedTime(mContext, testMillis, false).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatElapsedTime_FormatZero_WithSeconds() {
- final double testMillis = 0;
- final String expectedTime = "0s";
-
- assertThat(Utils.formatElapsedTime(mContext, testMillis, true).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatElapsedTime_FormatZero_NoSeconds() {
- final double testMillis = 0;
- final String expectedTime = "0m";
-
- assertThat(Utils.formatElapsedTime(mContext, testMillis, false).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatElapsedTime_onlyContainsMinute_hasTtsSpan() {
- final double testMillis = 15 * DateUtils.MINUTE_IN_MILLIS;
-
- final CharSequence charSequence = Utils.formatElapsedTime(mContext, testMillis, false);
- assertThat(charSequence).isInstanceOf(SpannableStringBuilder.class);
-
- final SpannableStringBuilder expectedString = (SpannableStringBuilder) charSequence;
- final TtsSpan[] ttsSpans = expectedString.getSpans(0, expectedString.length(),
- TtsSpan.class);
-
- assertThat(ttsSpans).asList().hasSize(1);
- assertThat(ttsSpans[0].getType()).isEqualTo(TtsSpan.TYPE_MEASURE);
- }
-
- @Test
- public void testFormatRelativeTime_WithSeconds_ShowSeconds() {
- final double testMillis = 40 * DateUtils.SECOND_IN_MILLIS;
- final String expectedTime = "40 sec. ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, true).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatRelativeTime_NoSeconds_DoNotShowSeconds() {
- final double testMillis = 40 * DateUtils.SECOND_IN_MILLIS;
- final String expectedTime = "1 min. ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, false).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatRelativeTime_LessThanTwoMinutes_withSeconds() {
- final double testMillis = 119 * DateUtils.SECOND_IN_MILLIS;
- final String expectedTime = "119 sec. ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, true).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatRelativeTime_LessThanTwoMinutes_NoSeconds() {
- final double testMillis = 119 * DateUtils.SECOND_IN_MILLIS;
- final String expectedTime = "2 min. ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, false).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatRelativeTime_TwoMinutes_withSeconds() {
- final double testMillis = 2 * DateUtils.MINUTE_IN_MILLIS;
- final String expectedTime = "2 min. ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, true).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatRelativeTime_LessThanTwoHours_withSeconds() {
- final double testMillis = 119 * DateUtils.MINUTE_IN_MILLIS;
- final String expectedTime = "119 min. ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, true).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatRelativeTime_TwoHours_withSeconds() {
- final double testMillis = 2 * DateUtils.HOUR_IN_MILLIS;
- final String expectedTime = "2 hr. ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, true).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatRelativeTime_LessThanTwoDays_withSeconds() {
- final double testMillis = 47 * DateUtils.HOUR_IN_MILLIS;
- final String expectedTime = "47 hr. ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, true).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatRelativeTime_TwoDays_withSeconds() {
- final double testMillis = 2 * DateUtils.DAY_IN_MILLIS;
- final String expectedTime = "2 days ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, true).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatRelativeTime_FormatZero_WithSeconds() {
- final double testMillis = 0;
- final String expectedTime = "0 sec. ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, true).toString()).isEqualTo(
- expectedTime);
- }
-
- @Test
- public void testFormatRelativeTime_FormatZero_NoSeconds() {
- final double testMillis = 0;
- final String expectedTime = "0 min. ago";
-
- assertThat(Utils.formatRelativeTime(mContext, testMillis, false).toString()).isEqualTo(
- expectedTime);
- }
-
@Test
public void testInitializeVolumeDoesntBreakOnNullVolume() {
VolumeInfo info = new VolumeInfo("id", 0, new DiskInfo("id", 0), "");
diff --git a/tests/robotests/src/com/android/settings/backup/BackupSettingsHelperTest.java b/tests/robotests/src/com/android/settings/backup/BackupSettingsHelperTest.java
index 9de0c6a3c2e..4e5428cc6f8 100644
--- a/tests/robotests/src/com/android/settings/backup/BackupSettingsHelperTest.java
+++ b/tests/robotests/src/com/android/settings/backup/BackupSettingsHelperTest.java
@@ -16,6 +16,14 @@
package com.android.settings.backup;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
import android.app.backup.BackupManager;
import android.app.backup.IBackupManager;
import android.content.ComponentName;
@@ -26,6 +34,10 @@ import android.content.res.Resources;
import android.os.IBinder;
import android.os.RemoteException;
+import com.android.settings.R;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -36,19 +48,6 @@ import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import com.android.settings.R;
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settings.TestConfig;
-import com.android.settingslib.drawer.SettingsDrawerActivity;
-
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION,
shadows = {BackupSettingsHelperTest.ShadowBackupManagerStub.class})
@@ -263,8 +262,6 @@ public class BackupSettingsHelperTest {
assertThat(backupIntent.getComponent().getClassName()).isEqualTo(
DEFAULT_SETTINGS_CLASSNAME);
- assertThat(backupIntent.getExtras().getBoolean(
- SettingsDrawerActivity.EXTRA_SHOW_MENU)).isTrue();
}
@Test
diff --git a/tests/robotests/src/com/android/settings/datausage/DataPlanSummaryPreferenceTest.java b/tests/robotests/src/com/android/settings/datausage/DataPlanSummaryPreferenceTest.java
deleted file mode 100644
index 9ddce537032..00000000000
--- a/tests/robotests/src/com/android/settings/datausage/DataPlanSummaryPreferenceTest.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2017 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.datausage;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.content.Context;
-import android.graphics.Color;
-import android.support.v7.preference.PreferenceViewHolder;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-import com.android.settings.R;
-import com.android.settings.TestConfig;
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settings.testutils.shadow.SettingsShadowResources;
-import com.android.settings.widget.DonutView;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.robolectric.RuntimeEnvironment;
-import org.robolectric.annotation.Config;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION,
- shadows = {
- SettingsShadowResources.class,
- SettingsShadowResources.SettingsShadowTheme.class
- }
-)
-public final class DataPlanSummaryPreferenceTest {
-
- private static final String TEST_PLAN_USAGE = "Test plan usage";
- private static final String TEST_PLAN_NAME = "Test plan name";
- private static final String TEST_PLAN_DESCRIPTION = "Test plan description";
- private static int sPlanUsageTextColor;
- private static int sMeterBackgroundColor;
- private static int sMeterConsumedColor;
-
- @BeforeClass
- public static void beforeClass() {
- sPlanUsageTextColor = Color.parseColor("#FF5C94F1");
- sMeterBackgroundColor = Color.parseColor("#FFDBDCDC");
- sMeterConsumedColor = Color.parseColor("#FF5C94F1");
- }
-
- private DataPlanSummaryPreference mPreference;
- private PreferenceViewHolder mHolder;
-
- @Before
- public void setUp() {
- SettingsShadowResources.overrideResource(
- com.android.internal.R.string.config_headlineFontFamily, "");
- Context context = RuntimeEnvironment.application;
- mPreference = new DataPlanSummaryPreference(context);
- LayoutInflater inflater = LayoutInflater.from(context);
- View view = inflater.inflate(mPreference.getLayoutResource(),
- new LinearLayout(context), false);
- mHolder = PreferenceViewHolder.createInstanceForTests(view);
- }
-
- @After
- public void tearDown() {
- SettingsShadowResources.reset();
- }
-
- @Test
- public void shouldRender_withoutData() {
- mPreference.onBindViewHolder(mHolder);
-
- TextView planUsageTextView = (TextView) mHolder.findViewById(android.R.id.title);
- assertThat(planUsageTextView.getText().toString()).isEmpty();
- TextView planNameTextView = (TextView) mHolder.findViewById(android.R.id.text1);
- assertThat(planNameTextView.getText().toString()).isEmpty();
- TextView planDescriptionTextView = (TextView) mHolder.findViewById(android.R.id.text2);
- assertThat(planDescriptionTextView.getText().toString()).isEmpty();
- }
-
- @Test
- public void shouldRender_withData() {
- mPreference.setTitle(TEST_PLAN_USAGE);
- mPreference.setUsageTextColor(sPlanUsageTextColor);
- mPreference.setName(TEST_PLAN_NAME);
- mPreference.setDescription(TEST_PLAN_DESCRIPTION);
- mPreference.setPercentageUsage(0.25D);
- mPreference.setMeterBackgroundColor(sMeterBackgroundColor);
- mPreference.setMeterConsumedColor(sMeterConsumedColor);
-
- mPreference.onBindViewHolder(mHolder);
-
- TextView planUsageTextView = (TextView) mHolder.findViewById(android.R.id.title);
- assertThat(planUsageTextView.getTextColors().getDefaultColor())
- .isEqualTo(sPlanUsageTextColor);
- assertThat(planUsageTextView.getText()).isEqualTo(TEST_PLAN_USAGE);
-
- TextView planNameTextView = (TextView) mHolder.findViewById(android.R.id.text1);
- assertThat(planNameTextView.getText()).isEqualTo(TEST_PLAN_NAME);
-
- TextView planDescriptionTextView = (TextView) mHolder.findViewById(android.R.id.text2);
- assertThat(planDescriptionTextView.getText()).isEqualTo(TEST_PLAN_DESCRIPTION);
-
- DonutView donutView = (DonutView) mHolder.findViewById(R.id.donut);
- assertThat(donutView.getMeterBackgroundColor()).isEqualTo(sMeterBackgroundColor);
- assertThat(donutView.getMeterConsumedColor()).isEqualTo(sMeterConsumedColor);
- }
-}
diff --git a/tests/robotests/src/com/android/settings/datausage/DataPlanUsageSummaryTest.java b/tests/robotests/src/com/android/settings/datausage/DataPlanUsageSummaryTest.java
deleted file mode 100644
index 748c3173793..00000000000
--- a/tests/robotests/src/com/android/settings/datausage/DataPlanUsageSummaryTest.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2017 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.datausage;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.content.Context;
-import android.net.ConnectivityManager;
-import android.net.NetworkPolicy;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiManager;
-import com.android.settings.R;
-import com.android.settings.TestConfig;
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settingslib.NetworkPolicyEditor;
-import java.util.ArrayList;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.robolectric.annotation.Config;
-import org.robolectric.shadows.ShadowApplication;
-import org.robolectric.util.ReflectionHelpers;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public class DataPlanUsageSummaryTest {
- @Mock
- private ConnectivityManager mManager;
-
- private Context mContext;
- private DataPlanUsageSummary mDataUsageSummary;
- private NetworkPolicyEditor mPolicyEditor;
- private WifiConfiguration mWifiConfiguration;
- private NetworkPolicy mNetworkPolicy;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- ShadowApplication shadowContext = ShadowApplication.getInstance();
- shadowContext.setSystemService(Context.CONNECTIVITY_SERVICE, mManager);
- mContext = shadowContext.getApplicationContext();
- when(mManager.isNetworkSupported(anyInt())).thenReturn(true);
- }
-
- @Test
- public void testUpdateNetworkRestrictionSummary_shouldSetSummary() {
- mDataUsageSummary = spy(new DataPlanUsageSummary());
- NetworkRestrictionsPreference preference = mock(NetworkRestrictionsPreference.class);
- mPolicyEditor = mock(NetworkPolicyEditor.class);
- WifiManager wifiManager = mock(WifiManager.class);
- ReflectionHelpers.setField(mDataUsageSummary, "mPolicyEditor", mPolicyEditor);
- ReflectionHelpers.setField(mDataUsageSummary, "mWifiManager", wifiManager);
- when(wifiManager.getConfiguredNetworks()).thenReturn(new ArrayList<>());
- doReturn(mContext.getResources()).when(mDataUsageSummary).getResources();
-
- mDataUsageSummary.updateNetworkRestrictionSummary(preference);
-
- verify(preference).setSummary(mContext.getResources().getQuantityString(
- R.plurals.network_restrictions_summary, 0, 0));
- }
-
- @Test
- public void testIsMetered_noSsid_shouldReturnFalse() {
- initTest();
-
- assertThat(mDataUsageSummary.isMetered(mWifiConfiguration)).isFalse();
- }
-
- @Test
- public void testIsMetered_noNetworkPolicy_shouldReturnFalse() {
- initTest();
- mWifiConfiguration.SSID = "network1";
- doReturn(null).when(mPolicyEditor).getPolicyMaybeUnquoted(any());
-
- assertThat(mDataUsageSummary.isMetered(mWifiConfiguration)).isFalse();
- }
-
- @Test
- public void testIsMetered_policyHasLimit_shouldReturnTrue() {
- initTest();
- mWifiConfiguration.SSID = "network1";
- mNetworkPolicy = mock(NetworkPolicy.class);
- mNetworkPolicy.limitBytes = 100;
- doReturn(mNetworkPolicy).when(mPolicyEditor).getPolicyMaybeUnquoted(any());
-
- assertThat(mDataUsageSummary.isMetered(mWifiConfiguration)).isTrue();
- }
-
- @Test
- public void testIsMetered_noPolicyLimit_shouldReturnMeteredValue() {
- initTest();
- mWifiConfiguration.SSID = "network1";
- mNetworkPolicy = mock(NetworkPolicy.class);
- mNetworkPolicy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
- doReturn(mNetworkPolicy).when(mPolicyEditor).getPolicyMaybeUnquoted(any());
-
- mNetworkPolicy.metered = true;
- assertThat(mDataUsageSummary.isMetered(mWifiConfiguration)).isTrue();
-
- mNetworkPolicy.metered = false;
- assertThat(mDataUsageSummary.isMetered(mWifiConfiguration)).isFalse();
- }
-
- private void initTest() {
- mDataUsageSummary = new DataPlanUsageSummary();
- mPolicyEditor = mock(NetworkPolicyEditor.class);
- ReflectionHelpers.setField(mDataUsageSummary, "mPolicyEditor", mPolicyEditor);
- mWifiConfiguration = mock(WifiConfiguration.class);
- }
-}
diff --git a/tests/robotests/src/com/android/settings/datausage/DataPlansSyncTimePreferenceTest.java b/tests/robotests/src/com/android/settings/datausage/DataPlansSyncTimePreferenceTest.java
deleted file mode 100644
index ba2d5f15ba5..00000000000
--- a/tests/robotests/src/com/android/settings/datausage/DataPlansSyncTimePreferenceTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2017 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.datausage;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.content.Context;
-import android.support.v7.preference.Preference;
-import android.support.v7.preference.PreferenceViewHolder;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-import com.android.settings.R;
-import com.android.settings.TestConfig;
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.robolectric.RuntimeEnvironment;
-import org.robolectric.annotation.Config;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public final class DataPlansSyncTimePreferenceTest {
- private static final String SYNC_TIME = "Today 12:24pm";
-
- private Preference mPreference;
- private PreferenceViewHolder mHolder;
-
- @Before
- public void setUp() {
- Context context = RuntimeEnvironment.application;
- mPreference = new Preference(context);
- mPreference.setLayoutResource(R.layout.data_plans_sync_time_preference);
-
- LayoutInflater inflater = LayoutInflater.from(context);
- View view = inflater.inflate(mPreference.getLayoutResource(),
- new LinearLayout(context), false);
- mHolder = PreferenceViewHolder.createInstanceForTests(view);
- }
-
- @Test
- public void shouldRender_withData() {
- mPreference.setTitle(SYNC_TIME);
-
- mPreference.onBindViewHolder(mHolder);
-
- TextView syncTimeTextView = (TextView) mHolder.findViewById(android.R.id.title);
- assertThat(syncTimeTextView.getText()).isEqualTo(SYNC_TIME);
- }
-}
diff --git a/tests/robotests/src/com/android/settings/datausage/DataUsageSummaryLegacyTest.java b/tests/robotests/src/com/android/settings/datausage/DataUsageSummaryLegacyTest.java
new file mode 100644
index 00000000000..ad1defb003a
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/datausage/DataUsageSummaryLegacyTest.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2016 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.datausage;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiManager;
+import android.text.format.Formatter;
+
+import com.android.settings.R;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settings.testutils.shadow.SettingsShadowResources;
+import com.android.settingslib.NetworkPolicyEditor;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowApplication;
+import org.robolectric.util.ReflectionHelpers;
+
+import java.util.ArrayList;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class DataUsageSummaryLegacyTest {
+ @Mock
+ private ConnectivityManager mManager;
+ private Context mContext;
+
+ /**
+ * This set up is contrived to get a passing test so that the build doesn't block without tests.
+ * These tests should be updated as code gets refactored to improve testability.
+ */
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ ShadowApplication shadowContext = ShadowApplication.getInstance();
+ shadowContext.setSystemService(Context.CONNECTIVITY_SERVICE, mManager);
+ mContext = shadowContext.getApplicationContext();
+ when(mManager.isNetworkSupported(anyInt())).thenReturn(true);
+ }
+
+ @Test
+ @Config(shadows = {
+ SettingsShadowResources.class,
+ SettingsShadowResources.SettingsShadowTheme.class
+ })
+ public void formatUsage_shouldLookLikeFormatFileSize() {
+ SettingsShadowResources.overrideResource(com.android.internal.R.string.fileSizeSuffix,
+ "%1$s %2$s");
+ final long usage = 2147483648L; // 2GB
+ final String formattedUsage =
+ DataUsageSummaryLegacy.formatUsage(mContext, "^1", usage).toString();
+ final String formattedAsFileSize = Formatter.formatFileSize(mContext, usage);
+ assertThat(formattedUsage).isEqualTo(formattedAsFileSize);
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/datausage/ManageDataPlansPreferenceTest.java b/tests/robotests/src/com/android/settings/datausage/ManageDataPlansPreferenceTest.java
deleted file mode 100644
index 6eff393cd0e..00000000000
--- a/tests/robotests/src/com/android/settings/datausage/ManageDataPlansPreferenceTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2017 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.datausage;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.content.Context;
-import android.support.v7.preference.Preference;
-import android.support.v7.preference.PreferenceViewHolder;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.widget.Button;
-import android.widget.LinearLayout;
-import com.android.settings.R;
-import com.android.settings.TestConfig;
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.robolectric.RuntimeEnvironment;
-import org.robolectric.annotation.Config;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public final class ManageDataPlansPreferenceTest {
- private Preference mPreference;
- private PreferenceViewHolder mHolder;
- private Context mContext;
-
- @Before
- public void setUp() {
- mContext = RuntimeEnvironment.application;
- mPreference = new Preference(mContext);
- mPreference.setLayoutResource(R.layout.manage_data_plans_preference);
- LayoutInflater inflater = LayoutInflater.from(mContext);
- View view = inflater.inflate(mPreference.getLayoutResource(),
- new LinearLayout(mContext), false);
- mHolder = PreferenceViewHolder.createInstanceForTests(view);
- }
-
- @Test
- public void shouldRender_withData() {
- mPreference.onBindViewHolder(mHolder);
- Button managePlanButton = (Button) mHolder.findViewById(R.id.manage_data_plans);
- assertThat(managePlanButton.getText())
- .isEqualTo(mContext.getString(R.string.data_plan_usage_manage_plans_button_text));
- }
-}
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatteryInfoTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatteryInfoTest.java
index 70958a9b4ca..45edb472e1a 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/BatteryInfoTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BatteryInfoTest.java
@@ -43,6 +43,9 @@ import com.android.settings.testutils.BatteryTestUtils;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settingslib.R;
+import com.android.settingslib.utils.PowerUtil;
+import java.time.Duration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -72,6 +75,8 @@ public class BatteryInfoTest {
public static final long TEST_CHARGE_TIME_REMAINING = TimeUnit.MINUTES.toMicros(1);
public static final String TEST_CHARGE_TIME_REMAINING_STRINGIFIED =
"1m left until fully charged";
+ public static final String TEST_BATTERY_LEVEL_10 = "10%";
+ public static final String FIFTEEN_MIN_FORMATTED = "15m";
private Intent mDisChargingBatteryBroadcast;
private Intent mChargingBatteryBroadcast;
private Context mContext;
@@ -134,13 +139,15 @@ public class BatteryInfoTest {
}
@Test
- public void testGetBatteryInfo_basedOnUsageTrue_usesCorrectString() {
+ public void testGetBatteryInfo_basedOnUsageTrueMoreThanFifteenMinutes_usesCorrectString() {
BatteryInfo info = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
mBatteryStats, SystemClock.elapsedRealtime() * 1000, false /* shortString */,
- 1000, true /* basedOnUsage */);
+ PowerUtil.convertMsToUs(Duration.ofHours(4).toMillis()),
+ true /* basedOnUsage */);
BatteryInfo info2 = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
mBatteryStats, SystemClock.elapsedRealtime() * 1000, true /* shortString */,
- 1000, true /* basedOnUsage */);
+ PowerUtil.convertMsToUs(Duration.ofHours(4).toMillis()),
+ true /* basedOnUsage */);
// We only add special mention for the long string
assertThat(info.remainingLabel.toString()).contains(ENHANCED_STRING_SUFFIX);
@@ -148,6 +155,41 @@ public class BatteryInfoTest {
assertThat(info2.remainingLabel.toString()).doesNotContain(ENHANCED_STRING_SUFFIX);
}
+ @Test
+ public void testGetBatteryInfo_basedOnUsageTrueLessThanSevenMinutes_usesCorrectString() {
+ BatteryInfo info = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
+ mBatteryStats, SystemClock.elapsedRealtime() * 1000, false /* shortString */,
+ PowerUtil.convertMsToUs(Duration.ofMinutes(7).toMillis()),
+ true /* basedOnUsage */);
+ BatteryInfo info2 = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
+ mBatteryStats, SystemClock.elapsedRealtime() * 1000, true /* shortString */,
+ PowerUtil.convertMsToUs(Duration.ofMinutes(7).toMillis()),
+ true /* basedOnUsage */);
+
+ // These should be identical in either case
+ assertThat(info.remainingLabel.toString()).isEqualTo(
+ mContext.getString(R.string.power_remaining_duration_only_shutdown_imminent));
+ assertThat(info2.remainingLabel.toString()).isEqualTo(
+ mContext.getString(R.string.power_remaining_duration_only_shutdown_imminent));
+ }
+
+ @Test
+ public void testGetBatteryInfo_basedOnUsageTrueBetweenSevenAndFifteenMinutes_usesCorrectString() {
+ BatteryInfo info = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
+ mBatteryStats, SystemClock.elapsedRealtime() * 1000, false /* shortString */,
+ PowerUtil.convertMsToUs(Duration.ofMinutes(10).toMillis()),
+ true /* basedOnUsage */);
+
+ // Check that strings are showing less than 15 minutes remaining regardless of exact time.
+ assertThat(info.chargeLabel.toString()).isEqualTo(
+ mContext.getString(R.string.power_remaining_less_than_duration,
+ TEST_BATTERY_LEVEL_10, FIFTEEN_MIN_FORMATTED));
+ assertThat(info.remainingLabel.toString()).isEqualTo(
+ mContext.getString(R.string.power_remaining_less_than_duration_only,
+ FIFTEEN_MIN_FORMATTED));
+ }
+
+
@Test
public void testGetBatteryInfo_basedOnUsageFalse_usesDefaultString() {
BatteryInfo info = BatteryInfo.getBatteryInfo(mContext, mDisChargingBatteryBroadcast,
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacyTest.java b/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacyTest.java
index e707ede3f7d..a3786c2b40c 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacyTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacyTest.java
@@ -55,7 +55,6 @@ import com.android.internal.os.BatteryStatsImpl;
import com.android.settings.R;
import com.android.settings.SettingsActivity;
import com.android.settings.TestConfig;
-import com.android.settings.Utils;
import com.android.settings.applications.LayoutPreference;
import com.android.settings.fuelgauge.anomaly.Anomaly;
import com.android.settings.fuelgauge.anomaly.AnomalyDetectionPolicy;
@@ -65,6 +64,7 @@ import com.android.settings.testutils.XmlTestUtils;
import com.android.settings.testutils.shadow.SettingsShadowResources;
import com.android.settingslib.core.AbstractPreferenceController;
+import com.android.settingslib.utils.StringUtil;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -367,8 +367,8 @@ public class PowerUsageSummaryLegacyTest {
public void testUpdateScreenPreference_showCorrectSummary() {
doReturn(mScreenBatterySipper).when(mFragment).findBatterySipperByType(any(), any());
doReturn(mRealContext).when(mFragment).getContext();
- final CharSequence expectedSummary = Utils.formatElapsedTime(mRealContext, USAGE_TIME_MS,
- false);
+ final CharSequence expectedSummary =
+ StringUtil.formatElapsedTime(mRealContext, USAGE_TIME_MS, false);
mFragment.updateScreenPreference();
diff --git a/tests/robotests/src/com/android/settings/notification/VisibilityPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/notification/VisibilityPreferenceControllerTest.java
index 25dba80ef1c..d3863db4653 100644
--- a/tests/robotests/src/com/android/settings/notification/VisibilityPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/notification/VisibilityPreferenceControllerTest.java
@@ -16,6 +16,7 @@
package com.android.settings.notification;
+import static android.app.Notification.VISIBILITY_PRIVATE;
import static android.app.NotificationChannel.DEFAULT_CHANNEL_ID;
import static android.app.NotificationManager.IMPORTANCE_DEFAULT;
import static android.app.NotificationManager.IMPORTANCE_MIN;
@@ -114,14 +115,14 @@ public class VisibilityPreferenceControllerTest {
}
@Test
- public void testNoCrashIfNoOnResume() throws Exception {
+ public void testNoCrashIfNoOnResume() {
mController.isAvailable();
mController.updateState(mock(RestrictedListPreference.class));
mController.onPreferenceChange(mock(RestrictedListPreference.class), true);
}
@Test
- public void testIsAvailable_notSecure() throws Exception {
+ public void testIsAvailable_notSecure() {
when(mLockUtils.isSecure(anyInt())).thenReturn(false);
NotificationBackend.AppRow appRow = new NotificationBackend.AppRow();
NotificationChannel channel = new NotificationChannel("", "", IMPORTANCE_DEFAULT);
@@ -130,7 +131,7 @@ public class VisibilityPreferenceControllerTest {
}
@Test
- public void testIsAvailable_notIfNotImportant() throws Exception {
+ public void testIsAvailable_notIfNotImportant() {
NotificationBackend.AppRow appRow = new NotificationBackend.AppRow();
NotificationChannel channel = new NotificationChannel("", "", IMPORTANCE_MIN);
mController.onResume(appRow, channel, null, null);
@@ -138,7 +139,7 @@ public class VisibilityPreferenceControllerTest {
}
@Test
- public void testIsAvailable() throws Exception {
+ public void testIsAvailable() {
NotificationBackend.AppRow appRow = new NotificationBackend.AppRow();
NotificationChannel channel =
new NotificationChannel(DEFAULT_CHANNEL_ID, "", IMPORTANCE_DEFAULT);
@@ -151,7 +152,7 @@ public class VisibilityPreferenceControllerTest {
}
@Test
- public void testUpdateState_disabledByAdmin_disableSecure() throws Exception {
+ public void testUpdateState_disabledByAdmin_disableSecure() {
ShadowRestrictionUtils.setRestricted(true);
UserInfo userInfo = new UserInfo(2, "user 2", UserInfo.FLAG_MANAGED_PROFILE);
when(mUm.getUserInfo(anyInt())).thenReturn(userInfo);
@@ -173,7 +174,7 @@ public class VisibilityPreferenceControllerTest {
}
@Test
- public void testUpdateState_disabledByAdmin_disableUnredacted() throws Exception {
+ public void testUpdateState_disabledByAdmin_disableUnredacted() {
ShadowRestrictionUtils.setRestricted(true);
UserInfo userInfo = new UserInfo(2, "user 2", UserInfo.FLAG_MANAGED_PROFILE);
when(mUm.getUserInfo(anyInt())).thenReturn(userInfo);
@@ -195,7 +196,7 @@ public class VisibilityPreferenceControllerTest {
}
@Test
- public void testUpdateState_noLockScreenNotificationsGlobally() throws Exception {
+ public void testUpdateState_noLockScreenNotificationsGlobally() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, 0);
@@ -211,10 +212,14 @@ public class VisibilityPreferenceControllerTest {
verify(pref, times(1)).setEntryValues(argumentCaptor.capture());
assertFalse(toStringList(argumentCaptor.getValue())
.contains(String.valueOf(VISIBILITY_NO_OVERRIDE)));
+ assertFalse(toStringList(argumentCaptor.getValue())
+ .contains(String.valueOf(VISIBILITY_PRIVATE)));
}
@Test
- public void testUpdateState_noPrivateLockScreenNotificationsGlobally() throws Exception {
+ public void testUpdateState_noPrivateLockScreenNotificationsGlobally() {
+ Settings.Secure.putInt(mContext.getContentResolver(),
+ Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, 1);
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, 0);
@@ -228,12 +233,13 @@ public class VisibilityPreferenceControllerTest {
ArgumentCaptor argumentCaptor =
ArgumentCaptor.forClass(CharSequence[].class);
verify(pref, times(1)).setEntryValues(argumentCaptor.capture());
+ assertEquals(2, toStringList(argumentCaptor.getValue()).size());
assertFalse(toStringList(argumentCaptor.getValue())
.contains(String.valueOf(VISIBILITY_NO_OVERRIDE)));
}
@Test
- public void testUpdateState_noGlobalRestriction() throws Exception {
+ public void testUpdateState_noGlobalRestriction() {
NotificationBackend.AppRow appRow = new NotificationBackend.AppRow();
NotificationChannel channel = mock(NotificationChannel.class);
mController.onResume(appRow, channel, null, null);
@@ -247,7 +253,7 @@ public class VisibilityPreferenceControllerTest {
List values = toStringList(argumentCaptor.getValue());
assertEquals(3, values.size());
assertTrue(values.contains(String.valueOf(VISIBILITY_NO_OVERRIDE)));
- assertTrue(values.contains(String.valueOf(Notification.VISIBILITY_PRIVATE)));
+ assertTrue(values.contains(String.valueOf(VISIBILITY_PRIVATE)));
assertTrue(values.contains(String.valueOf(Notification.VISIBILITY_SECRET)));
}
@@ -260,7 +266,7 @@ public class VisibilityPreferenceControllerTest {
}
@Test
- public void testUpdateState_noChannelOverride() throws Exception {
+ public void testUpdateState_noChannelOverride() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, 0);
@@ -275,11 +281,11 @@ public class VisibilityPreferenceControllerTest {
ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class);
verify(pref, times(1)).setValue(argumentCaptor.capture());
- assertEquals(String.valueOf(Notification.VISIBILITY_PRIVATE), argumentCaptor.getValue());
+ assertEquals(String.valueOf(VISIBILITY_PRIVATE), argumentCaptor.getValue());
}
@Test
- public void testUpdateState_channelOverride() throws Exception {
+ public void testUpdateState_channelOverride() {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, 0);
@@ -310,7 +316,7 @@ public class VisibilityPreferenceControllerTest {
RestrictedListPreference pref = mock(RestrictedListPreference.class);
mController.updateState(pref);
- mController.onPreferenceChange(pref, String.valueOf(Notification.VISIBILITY_PRIVATE));
+ mController.onPreferenceChange(pref, String.valueOf(VISIBILITY_PRIVATE));
assertEquals(VISIBILITY_NO_OVERRIDE, channel.getLockscreenVisibility());
verify(mBackend, times(1)).updateChannel(any(), anyInt(), any());
diff --git a/tests/robotests/src/com/android/settings/search/CursorToSearchResultConverterTest.java b/tests/robotests/src/com/android/settings/search/CursorToSearchResultConverterTest.java
deleted file mode 100644
index a1cafc5db43..00000000000
--- a/tests/robotests/src/com/android/settings/search/CursorToSearchResultConverterTest.java
+++ /dev/null
@@ -1,347 +0,0 @@
-/*
- * Copyright (C) 2017 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.search;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.app.Activity;
-import android.content.Context;
-import android.content.Intent;
-import android.database.Cursor;
-import android.database.MatrixCursor;
-import android.graphics.drawable.Drawable;
-
-import com.android.settings.DisplaySettings;
-import com.android.settings.R;
-import com.android.settings.TestConfig;
-import com.android.settings.gestures.SwipeToNotificationSettings;
-import com.android.settings.search.ResultPayload.Availability;
-import com.android.settings.search.ResultPayload.PayloadType;
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settings.wifi.WifiSettings;
-
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.MockitoAnnotations;
-import org.robolectric.Robolectric;
-import org.robolectric.annotation.Config;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public class CursorToSearchResultConverterTest {
-
- private static final List TITLES = Arrays.asList("title1", "title2", "title3");
- private static final String SUMMARY = "summary";
- private static final String TARGET_PACKAGE = "a.b.c";
- private static final String TARGET_CLASS = "a.b.c.class";
- private static final String KEY = "key";
- private static final int ICON = R.drawable.ic_search_24dp;
- private static final int BASE_RANK = 1;
- private static Intent sIntent;
-
- @BeforeClass
- public static void beforeClass() {
- sIntent = new Intent("com.android.settings");
- }
-
- private Drawable mDrawable;
- private CursorToSearchResultConverter mConverter;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- Context context = Robolectric.buildActivity(Activity.class).get();
- mDrawable = context.getDrawable(ICON);
- mConverter = new CursorToSearchResultConverter(context);
- }
-
- @Test
- public void testParseCursor_MatchesIcon() {
- final MatrixCursor cursor = new MatrixCursor(DatabaseResultLoader.SELECT_COLUMNS);
- final byte[] payload = ResultPayloadUtils.marshall(new ResultPayload(sIntent));
- final String BLANK = "";
- cursor.addRow(new Object[] {
- KEY.hashCode(), // Doc ID
- "Longer than 20 characters", // Title
- SUMMARY, // Summary on
- SUMMARY, // summary off
- DisplaySettings.class.getName(),
- BLANK, // screen title
- ICON, // icon
- BLANK, // action
- null, // target package
- BLANK, // target class
- KEY, // Key
- PayloadType.INTENT, // Payload Type
- payload // Payload
- });
-
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
-
- for (SearchResult result : results) {
- Drawable resultDrawable = result.icon;
- assertThat(resultDrawable).isNotNull();
- assertThat(resultDrawable.toString()).isEqualTo(mDrawable.toString());
- }
- }
-
- @Test
- public void testParseCursor_NoIcon() {
- final Set results = mConverter.convertCursor(
- getDummyCursor("noIcon" /* key */, "" /* className */), BASE_RANK);
- for (SearchResult result : results) {
- assertThat(result.icon).isNull();
- }
- }
-
- @Test
- public void testParseCursor_MatchesPayloadType() {
- final Set results = mConverter.convertCursor(getDummyCursor(), BASE_RANK);
- ResultPayload payload;
- for (SearchResult result : results) {
- payload = result.payload;
- assertThat(payload.getType()).isEqualTo(PayloadType.INTENT);
- }
- }
-
- @Test
- public void testLongTitle_PenalizedInRank() {
- final MatrixCursor cursor = new MatrixCursor(DatabaseResultLoader.SELECT_COLUMNS);
- final byte[] payload = ResultPayloadUtils.marshall(new ResultPayload(sIntent));
- final String BLANK = "";
- cursor.addRow(new Object[] {
- KEY.hashCode(), // Doc ID
- "Longer than 20 characters", // Title
- SUMMARY, // Summary on
- SUMMARY, // summary off
- DisplaySettings.class.getName(),
- BLANK, // screen title
- null, // icon
- BLANK, // action
- null, // target package
- BLANK, // target class
- KEY, // Key
- PayloadType.INTENT, // Payload Type
- payload // Payload
- });
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
- for (SearchResult result : results) {
- assertThat(result.rank).isEqualTo(BASE_RANK + 1);
- }
- }
-
- @Test
- public void testParseCursor_MatchesResultPayload() {
- final Set results = mConverter.convertCursor(getDummyCursor(), BASE_RANK);
- ResultPayload payload;
- for (SearchResult result : results) {
- payload = result.payload;
- Intent intent = payload.getIntent();
- assertThat(intent.getAction()).isEqualTo(sIntent.getAction());
- }
- }
-
-
- @Test
- public void testParseCursor_MatchesInlineSwitchPayload() {
- MatrixCursor cursor = new MatrixCursor(DatabaseResultLoader.SELECT_COLUMNS);
- final String BLANK = "";
- final String uri = "test.com";
- final int type = ResultPayload.PayloadType.INLINE_SWITCH;
- final int source = ResultPayload.SettingsSource.SECURE;
- final String intentKey = "key";
- final String intentVal = "value";
- final Intent intent = new Intent();
- intent.putExtra(intentKey, intentVal);
- final InlineSwitchPayload payload = new InlineSwitchPayload(uri, source, 1 /* onValue */,
- intent, true /* isDeviceSupported */, 0 /* defautValue */);
-
- cursor.addRow(new Object[] {
- KEY.hashCode(), // Doc ID
- TITLES.get(0), // Title
- SUMMARY, // Summary on
- SUMMARY, // summary off
- SwipeToNotificationSettings.class.getName(),
- BLANK, // screen title
- null, // icon
- BLANK, // action
- null, // target package
- BLANK, // target class
- KEY, // Key
- type, // Payload Type
- ResultPayloadUtils.marshall(payload) // Payload
- });
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
-
- for (SearchResult result : results) {
- final InlineSwitchPayload newPayload = (InlineSwitchPayload) result.payload;
- final Intent rebuiltIntent = newPayload.getIntent();
- assertThat(newPayload.getKey()).isEqualTo(uri);
- assertThat(newPayload.getType()).isEqualTo(type);
- assertThat(newPayload.mSettingSource).isEqualTo(source);
- assertThat(newPayload.isStandard()).isTrue();
- assertThat(newPayload.getAvailability()).isEqualTo(Availability.AVAILABLE);
- assertThat(rebuiltIntent.getStringExtra(intentKey)).isEqualTo(intentVal);
- }
- }
-
- // The following tests are temporary, and should be removed when we replace the Search
- // White-list solution for elevating ranking.
-
- @Test
- public void testWifiKey_PrioritizedResult() {
- final String key = "main_toggle_wifi";
- final Cursor cursor = getDummyCursor(key, WifiSettings.class.getName());
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
-
- for (SearchResult result : results) {
- assertThat(result.rank).isEqualTo(SearchResult.TOP_RANK);
- }
- }
-
- @Test
- public void testBluetoothKey_PrioritizedResult() {
- final String key = "main_toggle_bluetooth";
- final Cursor cursor = getDummyCursor(key, WifiSettings.class.getName());
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
-
- for (SearchResult result : results) {
- assertThat(result.rank).isEqualTo(SearchResult.TOP_RANK);
- }
- }
-
- @Test
- public void testAirplaneKey_PrioritizedResult() {
- final String key = "toggle_airplane";
- final Cursor cursor = getDummyCursor(key, WifiSettings.class.getName());
- Set results = mConverter.convertCursor(cursor, BASE_RANK);
- for (SearchResult result : results) {
- assertThat(result.rank).isEqualTo(SearchResult.TOP_RANK);
- }
- }
-
- @Test
- public void testHotspotKey_PrioritizedResult() {
- final String key = "tether_settings";
- final Cursor cursor = getDummyCursor(key, WifiSettings.class.getName());
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
-
- for (SearchResult result : results) {
- assertThat(result.rank).isEqualTo(SearchResult.TOP_RANK);
- }
- }
-
- @Test
- public void testBatterySaverKey_PrioritizedResult() {
- final String key = "battery_saver";
- final Cursor cursor = getDummyCursor(key, WifiSettings.class.getName());
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
-
- for (SearchResult result : results) {
- assertThat(result.rank).isEqualTo(SearchResult.TOP_RANK);
- }
- }
-
- @Test
- public void testNFCKey_PrioritizedResult() {
- final String key = "toggle_nfc";
- final Cursor cursor = getDummyCursor(key, WifiSettings.class.getName());
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
-
- for (SearchResult result : results) {
- assertThat(result.rank).isEqualTo(SearchResult.TOP_RANK);
- }
- }
-
- @Test
- public void testDataSaverKey_PrioritizedResult() {
- final String key = "restrict_background";
- final Cursor cursor = getDummyCursor(key, WifiSettings.class.getName());
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
-
- for (SearchResult result : results) {
- assertThat(result.rank).isEqualTo(SearchResult.TOP_RANK);
- }
- }
-
- @Test
- public void testDataUsageKey_PrioritizedResult() {
- final String key = "data_usage_enable";
- final Cursor cursor = getDummyCursor(key, WifiSettings.class.getName());
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
- for (SearchResult result : results) {
- assertThat(result.rank).isEqualTo(SearchResult.TOP_RANK);
- }
- }
-
- @Test
- public void testRoamingKey_PrioritizedResult() {
- final String key = "button_roaming_key";
- final Cursor cursor = getDummyCursor(key, WifiSettings.class.getName());
- final Set results = mConverter.convertCursor(cursor, BASE_RANK);
-
- for (SearchResult result : results) {
- assertThat(result.rank).isEqualTo(SearchResult.TOP_RANK);
- }
- }
-
- // End of temporary tests
-
- private MatrixCursor getDummyCursor() {
- String[] keys = new String[] {KEY + "1", KEY + "2", KEY + "3"};
- return getDummyCursor(keys, "" /* className */);
- }
-
- private MatrixCursor getDummyCursor(String key, String className) {
- String[] keys = new String[] {key};
- return getDummyCursor(keys, className);
- }
-
- private MatrixCursor getDummyCursor(String[] keys, String className) {
- MatrixCursor cursor = new MatrixCursor(DatabaseResultLoader.SELECT_COLUMNS);
- final String BLANK = "";
- final byte[] payload = ResultPayloadUtils.marshall(new ResultPayload(sIntent));
-
- for (int i = 0; i < keys.length; i++) {
- ArrayList