Merge "Fix NPE when building suggestion identifier."
diff --git a/res/layout/search_panel.xml b/res/layout/search_panel.xml
deleted file mode 100644
index d466874..0000000
--- a/res/layout/search_panel.xml
+++ /dev/null
@@ -1,74 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.
--->
-
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/search_panel"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
-
- <LinearLayout android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_gravity="center"
- android:orientation="vertical">
-
- <LinearLayout android:id="@+id/layout_suggestions"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:orientation="vertical">
-
- <!-- Padding is included in the background -->
- <ListView android:id="@+id/list_suggestions"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingStart="@dimen/dashboard_padding_start"
- android:paddingEnd="@dimen/dashboard_padding_end"
- android:paddingTop="@dimen/dashboard_padding_top"
- android:paddingBottom="@dimen/dashboard_padding_bottom"
- android:scrollbarStyle="outsideOverlay"
- android:headerDividersEnabled="false"
- android:background="@drawable/search_panel_list_background"
- android:elevation="@dimen/search_panel_elevation"
- />
-
- </LinearLayout>
-
- <LinearLayout android:id="@+id/layout_results"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_gravity="center"
- android:orientation="vertical"
- android:layout_weight="1">
-
- <!-- Padding is included in the background -->
- <ListView android:id="@+id/list_results"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingStart="@dimen/dashboard_padding_start"
- android:paddingEnd="@dimen/dashboard_padding_end"
- android:paddingTop="@dimen/dashboard_padding_top"
- android:paddingBottom="@dimen/dashboard_padding_bottom"
- android:scrollbarStyle="outsideOverlay"
- android:headerDividersEnabled="false"
- android:background="@drawable/search_panel_list_background"
- android:elevation="@dimen/search_panel_elevation"
- />
-
- </LinearLayout>
-
- </LinearLayout>
-
-</FrameLayout>
diff --git a/res/layout/search_panel_results_header.xml b/res/layout/search_panel_results_header.xml
deleted file mode 100644
index 2deb273..0000000
--- a/res/layout/search_panel_results_header.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.
--->
-
-<TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="@dimen/dashboard_category_height"
- android:paddingStart="@dimen/search_title_padding_start"
- android:singleLine="true"
- android:ellipsize="marquee"
- android:gravity="center_vertical"
- android:textAppearance="@style/TextAppearance.ResultTitle"
- android:textAlignment="viewStart"
- android:text="@string/search_results_label"
- />
diff --git a/res/layout/search_panel_suggestions_header.xml b/res/layout/search_panel_suggestions_header.xml
deleted file mode 100644
index 98957e4..0000000
--- a/res/layout/search_panel_suggestions_header.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.
--->
-
-<TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="@dimen/dashboard_category_height"
- android:paddingStart="@dimen/search_title_padding_start"
- android:singleLine="true"
- android:ellipsize="marquee"
- android:gravity="center_vertical"
- android:textAppearance="@style/TextAppearance.RecentsTitle"
- android:textAlignment="viewStart"
- android:text="@string/search_recents_queries_label"
- />
diff --git a/res/layout/search_result_item.xml b/res/layout/search_result_item.xml
deleted file mode 100644
index b659387..0000000
--- a/res/layout/search_result_item.xml
+++ /dev/null
@@ -1,57 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.
--->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:minHeight="?android:attr/listPreferredItemHeight"
- android:gravity="center_vertical"
- android:paddingEnd="?android:attr/scrollbarSize">
-
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="match_parent"
- android:gravity="center"
- android:minWidth="@*android:dimen/preference_icon_minWidth"
- android:orientation="horizontal">
-
- <ImageView
- android:id="@+id/icon"
- android:layout_width="@dimen/search_result_item_image_size"
- android:layout_height="@dimen/search_result_item_image_size"
- android:scaleType="centerInside"
- android:layout_marginStart="@dimen/search_result_item_image_margin_start"
- android:layout_marginEnd="@dimen/search_result_item_image_margin_end"
- />
-
- </LinearLayout>
-
- <RelativeLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1">
-
- <TextView android:id="@+id/title"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:singleLine="true"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:ellipsize="marquee"
- android:fadingEdge="horizontal" />
-
- </RelativeLayout>
-
-</LinearLayout>
diff --git a/res/menu/options_menu.xml b/res/menu/options_menu.xml
deleted file mode 100644
index f73ce90..0000000
--- a/res/menu/options_menu.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.
--->
-
-<menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item
- android:id="@+id/search"
- android:title="@string/search_menu"
- android:icon="@*android:drawable/ic_search_api_material"
- android:showAsAction="collapseActionView|ifRoom"
- android:actionViewClass="android.widget.SearchView" />
-</menu>
\ No newline at end of file
diff --git a/res/values/strings.xml b/res/values/strings.xml
index bff3170..fc484b0 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1595,18 +1595,21 @@
<!-- Checkbox title for option to notify user when open networks are nearby -->
<string name="wifi_notify_open_networks">Open network notification</string>
<!-- Checkbox summary for option to notify user when open networks are nearby-->
- <string name="wifi_notify_open_networks_summary">Notify whenever a high quality open network is available</string>
+ <string name="wifi_notify_open_networks_summary">Notify when a high\u2011quality open network is available that may require sign\u2011in</string>
<!-- Checkbox title for option to enable Wi-Fi when saved networks are nearby -->
<string name="wifi_wakeup">Turn Wi\u2011Fi back on</string>
- <!-- Checkbox summary for option to enable Wi-Fi when saved networks are nearby-->
- <string name="wifi_wakeup_summary">Automatically turn on Wi\u2011Fi near saved networks</string>
+ <!-- Checkbox summary for option to enable Wi-Fi when high quality saved networks are nearby-->
+ <string name="wifi_wakeup_summary">Automatically turn on Wi\u2011Fi near high\u2011quality saved networks</string>
<!-- Checkbox title for option to toggle poor network detection -->
<string name="wifi_poor_network_detection">Avoid poor connections</string>
<!-- Checkbox summary for option to toggle poor network detection -->
<string name="wifi_poor_network_detection_summary">Don\u2019t use a Wi\u2011Fi network unless it has a good Internet connection</string>
<!-- Checkbox summary for option to toggle poor network detection [CHAR LIMIT=60] -->
<string name="wifi_avoid_poor_network_detection_summary">Only use networks that have a good Internet connection</string>
-
+ <!-- Checkbox title for option to connect to open Wi-Fi automatically [CHAR LIMIT=40] -->
+ <string name="use_open_wifi_automatically_title">Connect to open networks</string>
+ <!-- Checkbox summary for option to connect to open Wi-Fi automatically [CHAR LIMIT=100] -->
+ <string name="use_open_wifi_automatically_summary">Automatically connect to high\u2011quality open networks </string>
<!-- Preference title for option to install certificates -->
<string name="wifi_install_credentials">Install certificates</string>
<!-- Message to describe "Wi-Fi scan always available feature" when Wi-Fi is off. The
@@ -3031,7 +3034,7 @@
<string name="sms_change_default_no_previous_dialog_text" translatable="true">Use <xliff:g id="new_app">%s</xliff:g> as your SMS app?</string>
<!-- Network Scorer Picker title [CHAR LIMIT=40]-->
- <string name="network_scorer_picker_title">Network Scorer</string>
+ <string name="network_scorer_picker_title">Network Rating Provider</string>
<string name="network_scorer_picker_none_preference">None</string>
<!-- Wifi Assistant change wi-fi assistant title. [CHAR LIMIT=40] -->
@@ -6062,11 +6065,6 @@
<xliff:g name="first_item">%1$s</xliff:g> > <xliff:g name="second_item">%2$s</xliff:g>
</string>
- <!-- Text used to identify the search query suggestions / recent searches -->
- <string name="search_recents_queries_label">Recent searches</string>
- <!-- Text used to identify the search results -->
- <string name="search_results_label">Results</string>
-
<!--Search Keywords [CHAR LIMIT=NONE]-->
<string name="keywords_wifi">wifi, wi-fi, network connection</string>
<string name="keywords_more_default_sms_app">text message, texting, messages, messaging</string>
diff --git a/res/xml/location_settings.xml b/res/xml/location_settings.xml
index adfff63..ea85d53 100644
--- a/res/xml/location_settings.xml
+++ b/res/xml/location_settings.xml
@@ -44,7 +44,7 @@
</intent>
</Preference>
- <com.android.settings.DividedCategory
+ <PreferenceCategory
android:key="recent_location_requests"
android:title="@string/location_category_recent_location_requests" />
diff --git a/res/xml/wifi_configure_settings.xml b/res/xml/wifi_configure_settings.xml
index 8e51009..fa5239d 100644
--- a/res/xml/wifi_configure_settings.xml
+++ b/res/xml/wifi_configure_settings.xml
@@ -26,15 +26,21 @@
android:summary="@string/wifi_wakeup_summary" />
<SwitchPreference
+ android:key="use_open_wifi_automatically"
+ android:icon="@drawable/ic_vpn_key"
+ android:title="@string/use_open_wifi_automatically_title"
+ android:summary="@string/use_open_wifi_automatically_summary" />
+
+ <SwitchPreference
android:key="notify_open_networks"
android:title="@string/wifi_notify_open_networks"
android:icon="@drawable/ic_settings_notifications"
android:summary="@string/wifi_notify_open_networks_summary" />
<SwitchPreference
- android:key="wifi_cellular_data_fallback"
- android:title="@string/wifi_cellular_data_fallback_title"
- android:summary="@string/wifi_cellular_data_fallback_summary"/>
+ android:key="wifi_cellular_data_fallback"
+ android:title="@string/wifi_cellular_data_fallback_title"
+ android:summary="@string/wifi_cellular_data_fallback_summary"/>
<ListPreference
android:key="sleep_policy"
diff --git a/src/com/android/settings/DividedCategory.java b/src/com/android/settings/DividedCategory.java
deleted file mode 100644
index d1c40c8..0000000
--- a/src/com/android/settings/DividedCategory.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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;
-
-import android.content.Context;
-import android.support.v7.preference.PreferenceCategory;
-import android.support.v7.preference.PreferenceViewHolder;
-import android.util.AttributeSet;
-
-/**
- * PreferenceCategory that allows a divider above it.
- */
-public class DividedCategory extends PreferenceCategory {
-
- public DividedCategory(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- @Override
- public void onBindViewHolder(PreferenceViewHolder holder) {
- super.onBindViewHolder(holder);
- holder.setDividerAllowedAbove(true);
- }
-}
diff --git a/src/com/android/settings/SettingsActivity.java b/src/com/android/settings/SettingsActivity.java
index 00a2c7d..2fa147e 100644
--- a/src/com/android/settings/SettingsActivity.java
+++ b/src/com/android/settings/SettingsActivity.java
@@ -47,13 +47,10 @@
import android.transition.TransitionManager;
import android.util.Log;
import android.view.Menu;
-import android.view.MenuInflater;
-import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
-import android.widget.SearchView;
import com.android.internal.util.ArrayUtils;
import com.android.settings.Settings.WifiSettingsActivity;
@@ -63,7 +60,6 @@
import com.android.settings.core.instrumentation.SharedPreferencesLogger;
import com.android.settings.dashboard.DashboardFeatureProvider;
import com.android.settings.dashboard.DashboardSummary;
-import com.android.settings.dashboard.SearchResultsSummary;
import com.android.settings.enterprise.EnterprisePrivacySettings;
import com.android.settings.overlay.FeatureFactory;
import com.android.settings.search.DynamicIndexableContentMonitor;
@@ -81,9 +77,7 @@
public class SettingsActivity extends SettingsDrawerActivity
implements PreferenceManager.OnPreferenceTreeClickListener,
PreferenceFragment.OnPreferenceStartFragmentCallback,
- ButtonBarHandler, FragmentManager.OnBackStackChangedListener,
- SearchView.OnQueryTextListener, SearchView.OnCloseListener,
- MenuItem.OnActionExpandListener {
+ ButtonBarHandler, FragmentManager.OnBackStackChangedListener {
private static final String LOG_TAG = "Settings";
@@ -91,8 +85,6 @@
// Constants for state save/restore
private static final String SAVE_KEY_CATEGORIES = ":settings:categories";
- private static final String SAVE_KEY_SEARCH_MENU_EXPANDED = ":settings:search_menu_expanded";
- private static final String SAVE_KEY_SEARCH_QUERY = ":settings:search_query";
private static final String SAVE_KEY_SHOW_HOME_AS_UP = ":settings:show_home_as_up";
private static final String SAVE_KEY_SHOW_SEARCH = ":settings:show_search";
@@ -166,8 +158,6 @@
private static final String EXTRA_UI_OPTIONS = "settings:ui_options";
- private static final String EMPTY_QUERY = "";
-
private static final int REQUEST_SUGGESTION = 42;
private String mFragmentClass;
@@ -226,25 +216,15 @@
private ViewGroup mContent;
- private SearchView mSearchView;
- private MenuItem mSearchMenuItem;
- private boolean mSearchMenuItemExpanded = false;
- private SearchResultsSummary mSearchResultsFragment;
private SearchFeatureProvider mSearchFeatureProvider;
private MetricsFeatureProvider mMetricsFeatureProvider;
// Categories
private ArrayList<DashboardCategory> mCategories = new ArrayList<>();
- private boolean mNeedToRevertToInitialFragment = false;
-
private DashboardFeatureProvider mDashboardFeatureProvider;
- private Intent mResultIntentData;
private ComponentName mCurrentSuggestion;
- @VisibleForTesting
- String mSearchQuery;
-
public SwitchBar getSwitchBar() {
return mSwitchBar;
}
@@ -270,51 +250,12 @@
}
@Override
- protected void onStart() {
- super.onStart();
-
- if (mNeedToRevertToInitialFragment) {
- revertToInitialFragment();
- }
- }
-
- @Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mDisplaySearch) {
return false;
}
- MenuInflater inflater = getMenuInflater();
- if (mSearchFeatureProvider.isEnabled(this)) {
- mSearchFeatureProvider.setUpSearchMenu(menu, this);
- return true;
- }
- inflater.inflate(R.menu.options_menu, menu);
-
-
- // Cache the search query (can be overridden by the OnQueryTextListener)
- final String query = mSearchQuery;
-
- mSearchMenuItem = menu.findItem(R.id.search);
- mSearchView = (SearchView) mSearchMenuItem.getActionView();
-
- if (mSearchMenuItem == null || mSearchView == null) {
- return false;
- }
-
- if (mSearchResultsFragment != null) {
- mSearchResultsFragment.setSearchView(mSearchView);
- }
-
- mSearchMenuItem.setOnActionExpandListener(this);
- mSearchView.setMaxWidth(Integer.MAX_VALUE);
- mSearchView.setOnQueryTextListener(this);
- mSearchView.setOnCloseListener(this);
-
- if (mSearchMenuItemExpanded) {
- mSearchMenuItem.expandActionView();
- }
- mSearchView.setQuery(query, true /* submit */);
+ mSearchFeatureProvider.setUpSearchMenu(menu, this);
return true;
}
@@ -417,8 +358,6 @@
if (savedState != null) {
// We are restarting from a previous saved state; used that to initialize, instead
// of starting fresh.
- mSearchMenuItemExpanded = savedState.getBoolean(SAVE_KEY_SEARCH_MENU_EXPANDED);
- mSearchQuery = savedState.getString(SAVE_KEY_SEARCH_QUERY);
setTitleFromIntent(intent);
ArrayList<DashboardCategory> categories =
@@ -430,7 +369,6 @@
}
mDisplayHomeAsUpEnabled = savedState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
- mDisplaySearch = savedState.getBoolean(SAVE_KEY_SHOW_SEARCH);
} else {
launchSettingFragment(initialFragmentName, isSubSettings, intent);
@@ -456,21 +394,21 @@
Button backButton = (Button)findViewById(R.id.back_button);
backButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
- setResult(RESULT_CANCELED, getResultIntentData());
+ setResult(RESULT_CANCELED, null);
finish();
}
});
Button skipButton = (Button)findViewById(R.id.skip_button);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
- setResult(RESULT_OK, getResultIntentData());
+ setResult(RESULT_OK, null);
finish();
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
- setResult(RESULT_OK, getResultIntentData());
+ setResult(RESULT_OK, null);
finish();
}
});
@@ -614,20 +552,6 @@
}
outState.putBoolean(SAVE_KEY_SHOW_HOME_AS_UP, mDisplayHomeAsUpEnabled);
- outState.putBoolean(SAVE_KEY_SHOW_SEARCH, mDisplaySearch);
-
- if (mDisplaySearch) {
- // The option menus are created if the ActionBar is visible and they are also created
- // asynchronously. If you launch Settings with an Intent action like
- // android.intent.action.POWER_USAGE_SUMMARY and at the same time your device is locked
- // thru a LockScreen, onCreateOptionsMenu() is not yet called and references to the search
- // menu item and search view are null.
- boolean isExpanded = (mSearchMenuItem != null) && mSearchMenuItem.isActionViewExpanded();
- outState.putBoolean(SAVE_KEY_SEARCH_MENU_EXPANDED, isExpanded);
-
- String query = (mSearchView != null) ? mSearchView.getQuery().toString() : EMPTY_QUERY;
- outState.putString(SAVE_KEY_SEARCH_QUERY, query);
- }
}
@Override
@@ -653,9 +577,6 @@
}
mDynamicIndexableContentMonitor.register(this, LOADER_ID_INDEXABLE_CONTENT_MONITOR);
- if(mDisplaySearch && !TextUtils.isEmpty(mSearchQuery)) {
- onQueryTextSubmit(mSearchQuery);
- }
updateTilesList();
}
@@ -1011,96 +932,6 @@
return super.shouldUpRecreateTask(new Intent(this, SettingsActivity.class));
}
- @Deprecated
- @Override
- public boolean onQueryTextSubmit(String query) {
- if (mSearchFeatureProvider.isEnabled(this)) {
- return false;
- }
- mSearchQuery = query;
- switchToSearchResultsFragmentIfNeeded();
- return mSearchResultsFragment.onQueryTextSubmit(query);
- }
-
- @Deprecated
- @Override
- public boolean onQueryTextChange(String newText) {
- mSearchQuery = newText;
- if (mSearchFeatureProvider.isEnabled(this) || mSearchResultsFragment == null) {
- return false;
- }
- return mSearchResultsFragment.onQueryTextChange(newText);
- }
-
- @Override
- public boolean onClose() {
- return false;
- }
-
- @Override
- public boolean onMenuItemActionExpand(MenuItem item) {
- if (item.getItemId() == mSearchMenuItem.getItemId()) {
- switchToSearchResultsFragmentIfNeeded();
- }
- return true;
- }
-
- @Override
- public boolean onMenuItemActionCollapse(MenuItem item) {
- if (item.getItemId() == mSearchMenuItem.getItemId()) {
- if (mSearchMenuItemExpanded) {
- revertToInitialFragment();
- }
- }
- return true;
- }
-
- @Override
- public void onProfileTileOpen() {
- if (!mIsShowingDashboard) {
- finish();
- }
- }
-
- @Deprecated
- private void switchToSearchResultsFragmentIfNeeded() {
- if (mSearchResultsFragment != null) {
- return;
- }
- Fragment current = getFragmentManager().findFragmentById(R.id.main_content);
- if (current != null && current instanceof SearchResultsSummary) {
- mSearchResultsFragment = (SearchResultsSummary) current;
- } else {
- setContentHeaderView(null);
- mSearchResultsFragment = (SearchResultsSummary) switchToFragment(
- SearchResultsSummary.class.getName(), null, false, true,
- R.string.search_results_title, null, true);
- }
- mSearchResultsFragment.setSearchView(mSearchView);
- mSearchMenuItemExpanded = true;
- }
-
- @Deprecated
- public void needToRevertToInitialFragment() {
- mNeedToRevertToInitialFragment = true;
- }
-
- @Deprecated
- private void revertToInitialFragment() {
- mNeedToRevertToInitialFragment = false;
- mSearchResultsFragment = null;
- mSearchMenuItemExpanded = false;
- getFragmentManager().popBackStackImmediate(SettingsActivity.BACK_STACK_PREFS,
- FragmentManager.POP_BACK_STACK_INCLUSIVE);
- if (mSearchMenuItem != null) {
- mSearchMenuItem.collapseActionView();
- }
- }
-
- public Intent getResultIntentData() {
- return mResultIntentData;
- }
-
public void startSuggestion(Intent intent) {
if (intent == null || ActivityManager.isUserAMonkey()) {
return;
@@ -1131,4 +962,4 @@
return bitmap;
}
-}
+}
\ No newline at end of file
diff --git a/src/com/android/settings/dashboard/SearchResultsSummary.java b/src/com/android/settings/dashboard/SearchResultsSummary.java
deleted file mode 100644
index 06b71d6..0000000
--- a/src/com/android/settings/dashboard/SearchResultsSummary.java
+++ /dev/null
@@ -1,642 +0,0 @@
-/*
- * Copyright (C) 2014 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.dashboard;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.res.Resources;
-import android.database.Cursor;
-import android.graphics.drawable.Drawable;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.text.TextUtils;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.BaseAdapter;
-import android.widget.ImageView;
-import android.widget.ListView;
-import android.widget.SearchView;
-import android.widget.TextView;
-
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settings.R;
-import com.android.settings.SettingsActivity;
-import com.android.settings.Utils;
-import com.android.settings.core.InstrumentedPreferenceFragment;
-import com.android.settings.search.Index;
-
-import java.util.HashMap;
-
-public class SearchResultsSummary extends InstrumentedPreferenceFragment {
-
- private static final String LOG_TAG = "SearchResultsSummary";
-
- private static final String EMPTY_QUERY = "";
- private static char ELLIPSIS = '\u2026';
-
- private static final String SAVE_KEY_SHOW_RESULTS = ":settings:show_results";
-
- private SearchView mSearchView;
-
- private ListView mResultsListView;
- private SearchResultsAdapter mResultsAdapter;
- private UpdateSearchResultsTask mUpdateSearchResultsTask;
-
- private ListView mSuggestionsListView;
- private SuggestionsAdapter mSuggestionsAdapter;
- private UpdateSuggestionsTask mUpdateSuggestionsTask;
-
- private ViewGroup mLayoutSuggestions;
- private ViewGroup mLayoutResults;
-
- private String mQuery;
-
- private boolean mShowResults;
-
- /**
- * A basic AsyncTask for updating the query results cursor
- */
- private class UpdateSearchResultsTask extends AsyncTask<String, Void, Cursor> {
- @Override
- protected Cursor doInBackground(String... params) {
- return Index.getInstance(getActivity()).search(params[0]);
- }
-
- @Override
- protected void onPostExecute(Cursor cursor) {
- if (!isCancelled()) {
- mMetricsFeatureProvider.action(getContext(),
- MetricsEvent.ACTION_SEARCH_RESULTS, cursor.getCount());
- setResultsCursor(cursor);
- setResultsVisibility(cursor.getCount() > 0);
- } else if (cursor != null) {
- cursor.close();
- }
- }
- }
-
- /**
- * A basic AsyncTask for updating the suggestions cursor
- */
- private class UpdateSuggestionsTask extends AsyncTask<String, Void, Cursor> {
- @Override
- protected Cursor doInBackground(String... params) {
- return Index.getInstance(getActivity()).getSuggestions(params[0]);
- }
-
- @Override
- protected void onPostExecute(Cursor cursor) {
- if (!isCancelled()) {
- setSuggestionsCursor(cursor);
- setSuggestionsVisibility(cursor.getCount() > 0);
- } else if (cursor != null) {
- cursor.close();
- }
- }
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- mResultsAdapter = new SearchResultsAdapter(getActivity());
- mSuggestionsAdapter = new SuggestionsAdapter(getActivity());
-
- if (savedInstanceState != null) {
- mShowResults = savedInstanceState.getBoolean(SAVE_KEY_SHOW_RESULTS);
- }
- }
-
- @Override
- public void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
-
- outState.putBoolean(SAVE_KEY_SHOW_RESULTS, mShowResults);
- }
-
- @Override
- public void onStop() {
- super.onStop();
-
- clearSuggestions();
- clearResults();
- }
-
- @Override
- public void onDestroy() {
- mResultsListView = null;
- mResultsAdapter = null;
- mUpdateSearchResultsTask = null;
-
- mSuggestionsListView = null;
- mSuggestionsAdapter = null;
- mUpdateSuggestionsTask = null;
-
- mSearchView = null;
-
- super.onDestroy();
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
-
- final View view = inflater.inflate(R.layout.search_panel, container, false);
-
- mLayoutSuggestions = (ViewGroup) view.findViewById(R.id.layout_suggestions);
- mLayoutResults = (ViewGroup) view.findViewById(R.id.layout_results);
-
- mResultsListView = (ListView) view.findViewById(R.id.list_results);
- mResultsListView.setAdapter(mResultsAdapter);
- mResultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- // We have a header, so we need to decrement the position by one
- position--;
-
- // Some Monkeys could create a case where they were probably clicking on the
- // List Header and thus the position passed was "0" and then by decrement was "-1"
- if (position < 0) {
- return;
- }
-
- final Cursor cursor = mResultsAdapter.mCursor;
- cursor.moveToPosition(position);
-
- final String className = cursor.getString(Index.COLUMN_INDEX_CLASS_NAME);
- final String screenTitle = cursor.getString(Index.COLUMN_INDEX_SCREEN_TITLE);
- final String action = cursor.getString(Index.COLUMN_INDEX_INTENT_ACTION);
- final String key = cursor.getString(Index.COLUMN_INDEX_KEY);
-
- final SettingsActivity sa = (SettingsActivity) getActivity();
- sa.needToRevertToInitialFragment();
-
- if (TextUtils.isEmpty(action)) {
- Bundle args = new Bundle();
- args.putString(SettingsActivity.EXTRA_FRAGMENT_ARG_KEY, key);
-
- Utils.startWithFragment(sa, className, args, null, 0, -1, screenTitle,
- getMetricsCategory());
- } else {
- final Intent intent = new Intent(action);
-
- final String targetPackage = cursor.getString(
- Index.COLUMN_INDEX_INTENT_ACTION_TARGET_PACKAGE);
- final String targetClass = cursor.getString(
- Index.COLUMN_INDEX_INTENT_ACTION_TARGET_CLASS);
- if (!TextUtils.isEmpty(targetPackage) && !TextUtils.isEmpty(targetClass)) {
- final ComponentName component =
- new ComponentName(targetPackage, targetClass);
- intent.setComponent(component);
- }
- intent.putExtra(SettingsActivity.EXTRA_FRAGMENT_ARG_KEY, key);
-
- sa.startActivity(intent);
- }
-
- saveQueryToDatabase();
- }
- });
- mResultsListView.addHeaderView(
- LayoutInflater.from(getActivity()).inflate(
- R.layout.search_panel_results_header, mResultsListView, false),
- null, false);
-
- mSuggestionsListView = (ListView) view.findViewById(R.id.list_suggestions);
- mSuggestionsListView.setAdapter(mSuggestionsAdapter);
- mSuggestionsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- // We have a header, so we need to decrement the position by one
- position--;
- // Some Monkeys could create a case where they were probably clicking on the
- // List Header and thus the position passed was "0" and then by decrement was "-1"
- if (position < 0) {
- return;
- }
- final Cursor cursor = mSuggestionsAdapter.mCursor;
- cursor.moveToPosition(position);
-
- mShowResults = true;
- mQuery = cursor.getString(0);
- mSearchView.setQuery(mQuery, false);
- }
- });
- mSuggestionsListView.addHeaderView(
- LayoutInflater.from(getActivity()).inflate(
- R.layout.search_panel_suggestions_header, mSuggestionsListView, false),
- null, false);
-
- return view;
- }
-
- @Override
- public int getMetricsCategory() {
- return MetricsEvent.DASHBOARD_SEARCH_RESULTS;
- }
-
- @Override
- public void onResume() {
- super.onResume();
-
- if (!mShowResults) {
- showSomeSuggestions();
- }
- }
-
- public void setSearchView(SearchView searchView) {
- mSearchView = searchView;
- }
-
- private void setSuggestionsVisibility(boolean visible) {
- if (mLayoutSuggestions != null) {
- mLayoutSuggestions.setVisibility(visible ? View.VISIBLE : View.GONE);
- }
- }
-
- private void setResultsVisibility(boolean visible) {
- if (mLayoutResults != null) {
- mLayoutResults.setVisibility(visible ? View.VISIBLE : View.GONE);
- }
- }
-
- private void saveQueryToDatabase() {
- Index.getInstance(getActivity()).addSavedQuery(mQuery);
- }
-
- public boolean onQueryTextSubmit(String query) {
- mQuery = getFilteredQueryString(query);
- mShowResults = true;
- setSuggestionsVisibility(false);
- updateSearchResults();
- saveQueryToDatabase();
-
- return false;
- }
-
- public boolean onQueryTextChange(String query) {
- final String newQuery = getFilteredQueryString(query);
-
- mQuery = newQuery;
-
- if (TextUtils.isEmpty(mQuery)) {
- mShowResults = false;
- setResultsVisibility(false);
- updateSuggestions();
- } else {
- mShowResults = true;
- setSuggestionsVisibility(false);
- updateSearchResults();
- }
-
- return true;
- }
-
- public void showSomeSuggestions() {
- setResultsVisibility(false);
- mQuery = EMPTY_QUERY;
- updateSuggestions();
- }
-
- private void clearSuggestions() {
- if (mUpdateSuggestionsTask != null) {
- mUpdateSuggestionsTask.cancel(false);
- mUpdateSuggestionsTask = null;
- }
- setSuggestionsCursor(null);
- setSuggestionsVisibility(false);
- }
-
- private void setSuggestionsCursor(Cursor cursor) {
- if (mSuggestionsAdapter == null) {
- return;
- }
- Cursor oldCursor = mSuggestionsAdapter.swapCursor(cursor);
- if (oldCursor != null) {
- oldCursor.close();
- }
- }
-
- private void clearResults() {
- if (mUpdateSearchResultsTask != null) {
- mUpdateSearchResultsTask.cancel(false);
- mUpdateSearchResultsTask = null;
- }
- setResultsCursor(null);
- setResultsVisibility(false);
- }
-
- private void setResultsCursor(Cursor cursor) {
- if (mResultsAdapter == null) {
- return;
- }
- Cursor oldCursor = mResultsAdapter.swapCursor(cursor);
- if (oldCursor != null) {
- oldCursor.close();
- }
- }
-
- private String getFilteredQueryString(CharSequence query) {
- if (query == null) {
- return null;
- }
- final StringBuilder filtered = new StringBuilder();
- for (int n = 0; n < query.length(); n++) {
- char c = query.charAt(n);
- if (!Character.isLetterOrDigit(c) && !Character.isSpaceChar(c)) {
- continue;
- }
- filtered.append(c);
- }
- return filtered.toString();
- }
-
- private void clearAllTasks() {
- if (mUpdateSearchResultsTask != null) {
- mUpdateSearchResultsTask.cancel(false);
- mUpdateSearchResultsTask = null;
- }
- if (mUpdateSuggestionsTask != null) {
- mUpdateSuggestionsTask.cancel(false);
- mUpdateSuggestionsTask = null;
- }
- }
-
- private void updateSuggestions() {
- clearAllTasks();
- if (mQuery == null) {
- setSuggestionsCursor(null);
- } else {
- mUpdateSuggestionsTask = new UpdateSuggestionsTask();
- mUpdateSuggestionsTask.execute(mQuery);
- }
- }
-
- private void updateSearchResults() {
- clearAllTasks();
- if (TextUtils.isEmpty(mQuery)) {
- setResultsVisibility(false);
- setResultsCursor(null);
- } else {
- mUpdateSearchResultsTask = new UpdateSearchResultsTask();
- mUpdateSearchResultsTask.execute(mQuery);
- }
- }
-
- private static class SuggestionItem {
- public String query;
-
- public SuggestionItem(String query) {
- this.query = query;
- }
- }
-
- private static class SuggestionsAdapter extends BaseAdapter {
-
- private static final int COLUMN_SUGGESTION_QUERY = 0;
- private static final int COLUMN_SUGGESTION_TIMESTAMP = 1;
-
- private Context mContext;
- private Cursor mCursor;
- private LayoutInflater mInflater;
- private boolean mDataValid = false;
-
- public SuggestionsAdapter(Context context) {
- mContext = context;
- mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- mDataValid = false;
- }
-
- public Cursor swapCursor(Cursor newCursor) {
- if (newCursor == mCursor) {
- return null;
- }
- Cursor oldCursor = mCursor;
- mCursor = newCursor;
- if (newCursor != null) {
- mDataValid = true;
- notifyDataSetChanged();
- } else {
- mDataValid = false;
- notifyDataSetInvalidated();
- }
- return oldCursor;
- }
-
- @Override
- public int getCount() {
- if (!mDataValid || mCursor == null || mCursor.isClosed()) return 0;
- return mCursor.getCount();
- }
-
- @Override
- public Object getItem(int position) {
- if (mDataValid && mCursor.moveToPosition(position)) {
- final String query = mCursor.getString(COLUMN_SUGGESTION_QUERY);
-
- return new SuggestionItem(query);
- }
- return null;
- }
-
- @Override
- public long getItemId(int position) {
- return 0;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- if (!mDataValid && convertView == null) {
- throw new IllegalStateException(
- "this should only be called when the cursor is valid");
- }
- if (!mCursor.moveToPosition(position)) {
- throw new IllegalStateException("couldn't move cursor to position " + position);
- }
-
- View view;
-
- if (convertView == null) {
- view = mInflater.inflate(R.layout.search_suggestion_item, parent, false);
- } else {
- view = convertView;
- }
-
- TextView query = (TextView) view.findViewById(R.id.title);
-
- SuggestionItem item = (SuggestionItem) getItem(position);
- query.setText(item.query);
-
- return view;
- }
- }
-
- private static class SearchResult {
- public Context context;
- public String title;
- public String summaryOn;
- public String summaryOff;
- public String entries;
- public int iconResId;
- public String key;
-
- public SearchResult(Context context, String title, String summaryOn, String summaryOff,
- String entries, int iconResId, String key) {
- this.context = context;
- this.title = title;
- this.summaryOn = summaryOn;
- this.summaryOff = summaryOff;
- this.entries = entries;
- this.iconResId = iconResId;
- this.key = key;
- }
- }
-
- private static class SearchResultsAdapter extends BaseAdapter {
-
- private Context mContext;
- private Cursor mCursor;
- private LayoutInflater mInflater;
- private boolean mDataValid;
- private HashMap<String, Context> mContextMap = new HashMap<String, Context>();
-
- private static final String PERCENT_RECLACE = "%s";
- private static final String DOLLAR_REPLACE = "$s";
-
- public SearchResultsAdapter(Context context) {
- mContext = context;
- mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- mDataValid = false;
- }
-
- public Cursor swapCursor(Cursor newCursor) {
- if (newCursor == mCursor) {
- return null;
- }
- Cursor oldCursor = mCursor;
- mCursor = newCursor;
- if (newCursor != null) {
- mDataValid = true;
- notifyDataSetChanged();
- } else {
- mDataValid = false;
- notifyDataSetInvalidated();
- }
- return oldCursor;
- }
-
- @Override
- public int getCount() {
- if (!mDataValid || mCursor == null || mCursor.isClosed()) return 0;
- return mCursor.getCount();
- }
-
- @Override
- public Object getItem(int position) {
- if (mDataValid && mCursor.moveToPosition(position)) {
- final String title = mCursor.getString(Index.COLUMN_INDEX_TITLE);
- final String summaryOn = mCursor.getString(Index.COLUMN_INDEX_SUMMARY_ON);
- final String summaryOff = mCursor.getString(Index.COLUMN_INDEX_SUMMARY_OFF);
- final String entries = mCursor.getString(Index.COLUMN_INDEX_ENTRIES);
- final String iconResStr = mCursor.getString(Index.COLUMN_INDEX_ICON);
- final String className = mCursor.getString(
- Index.COLUMN_INDEX_CLASS_NAME);
- final String packageName = mCursor.getString(
- Index.COLUMN_INDEX_INTENT_ACTION_TARGET_PACKAGE);
- final String key = mCursor.getString(
- Index.COLUMN_INDEX_KEY);
-
- Context packageContext;
- if (TextUtils.isEmpty(className) && !TextUtils.isEmpty(packageName)) {
- packageContext = mContextMap.get(packageName);
- if (packageContext == null) {
- try {
- packageContext = mContext.createPackageContext(packageName, 0);
- } catch (PackageManager.NameNotFoundException e) {
- Log.e(LOG_TAG, "Cannot create Context for package: " + packageName);
- return null;
- }
- mContextMap.put(packageName, packageContext);
- }
- } else {
- packageContext = mContext;
- }
-
- final int iconResId = TextUtils.isEmpty(iconResStr) ?
- R.drawable.empty_icon : Integer.parseInt(iconResStr);
-
- return new SearchResult(packageContext, title, summaryOn, summaryOff,
- entries, iconResId, key);
- }
- return null;
- }
-
- @Override
- public long getItemId(int position) {
- return 0;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- if (!mDataValid && convertView == null) {
- throw new IllegalStateException(
- "this should only be called when the cursor is valid");
- }
- if (!mCursor.moveToPosition(position)) {
- throw new IllegalStateException("couldn't move cursor to position " + position);
- }
-
- View view;
- TextView textTitle;
- ImageView imageView;
-
- if (convertView == null) {
- view = mInflater.inflate(R.layout.search_result_item, parent, false);
- } else {
- view = convertView;
- }
-
- textTitle = (TextView) view.findViewById(R.id.title);
- imageView = (ImageView) view.findViewById(R.id.icon);
-
- final SearchResult result = (SearchResult) getItem(position);
- textTitle.setText(result.title);
-
- if (result.iconResId != R.drawable.empty_icon) {
- final Context packageContext = result.context;
- final Drawable drawable;
- try {
- drawable = packageContext.getDrawable(result.iconResId);
- imageView.setImageDrawable(drawable);
- } catch (Resources.NotFoundException nfe) {
- // Not much we can do except logging
- Log.e(LOG_TAG, "Cannot load Drawable for " + result.title);
- }
- } else {
- imageView.setImageDrawable(null);
- imageView.setBackgroundResource(R.drawable.empty_icon);
- }
-
- return view;
- }
- }
-}
diff --git a/src/com/android/settings/datausage/BillingCyclePreference.java b/src/com/android/settings/datausage/BillingCyclePreference.java
index 8e450df..beb0ba1 100644
--- a/src/com/android/settings/datausage/BillingCyclePreference.java
+++ b/src/com/android/settings/datausage/BillingCyclePreference.java
@@ -58,8 +58,9 @@
mSubId = subId;
mServices = services;
mPolicy = services.mPolicyEditor.getPolicy(mTemplate);
- setSummary(getContext().getString(R.string.billing_cycle_fragment_summary,
- mPolicy != null ? mPolicy.cycleDay : 1));
+ setSummary(getContext().getString(R.string.billing_cycle_fragment_summary, mPolicy != null
+ ? mPolicy.cycleDay
+ : "1"));
setIntent(getIntent());
}
diff --git a/src/com/android/settings/datausage/DataUsageList.java b/src/com/android/settings/datausage/DataUsageList.java
index a817479..e12f89e 100644
--- a/src/com/android/settings/datausage/DataUsageList.java
+++ b/src/com/android/settings/datausage/DataUsageList.java
@@ -46,8 +46,10 @@
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
+
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.R;
+import com.android.settings.datausage.CycleAdapter.SpinnerInterface;
import com.android.settingslib.AppItem;
import com.android.settingslib.net.ChartData;
import com.android.settingslib.net.ChartDataLoader;
@@ -56,9 +58,7 @@
import java.util.ArrayList;
import java.util.Collections;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import static android.net.ConnectivityManager.TYPE_MOBILE;
import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
@@ -73,6 +73,10 @@
* to inspect based on usage cycle and control through {@link NetworkPolicy}.
*/
public class DataUsageList extends DataUsageBase {
+
+ public static final String EXTRA_SUB_ID = "sub_id";
+ public static final String EXTRA_NETWORK_TEMPLATE = "network_template";
+
private static final String TAG = "DataUsage";
private static final boolean LOGD = false;
@@ -82,8 +86,14 @@
private static final int LOADER_CHART_DATA = 2;
private static final int LOADER_SUMMARY = 3;
- public static final String EXTRA_SUB_ID = "sub_id";
- public static final String EXTRA_NETWORK_TEMPLATE = "network_template";
+
+ private final CellDataPreference.DataStateListener mDataStateListener =
+ new CellDataPreference.DataStateListener() {
+ @Override
+ public void onChange(boolean selfChange) {
+ updatePolicy();
+ }
+ };
private INetworkStatsSession mStatsSession;
@@ -93,15 +103,7 @@
private int mSubId;
private ChartData mChartData;
- /** Flag used to ignore listeners during binding. */
- private boolean mBinding;
-
private UidDetailProvider mUidDetailProvider;
-
- /**
- * Local cache of data enabled for subId, used to work around delays.
- */
- private final Map<String, Boolean> mMobileDataEnabled = new HashMap<String, Boolean>();
private CycleAdapter mCycleAdapter;
private Spinner mCycleSpinner;
private Preference mUsageAmount;
@@ -146,9 +148,14 @@
super.onViewCreated(v, savedInstanceState);
mHeader = setPinnedHeaderView(R.layout.apps_filter_spinner);
- mCycleSpinner = (Spinner) mHeader.findViewById(R.id.filter_spinner);
- mCycleAdapter = new CycleAdapter(mCycleSpinner.getContext(),
- new CycleAdapter.SpinnerInterface() {
+ mHeader.findViewById(R.id.filter_settings).setOnClickListener(btn -> {
+ final Bundle args = new Bundle();
+ args.putParcelable(DataUsageList.EXTRA_NETWORK_TEMPLATE, mTemplate);
+ startFragment(DataUsageList.this, BillingCycleSettings.class.getName(),
+ R.string.billing_cycle, 0, args);
+ });
+ mCycleSpinner = mHeader.findViewById(R.id.filter_spinner);
+ mCycleAdapter = new CycleAdapter(mCycleSpinner.getContext(), new SpinnerInterface() {
@Override
public void setAdapter(CycleAdapter cycleAdapter) {
mCycleSpinner.setAdapter(cycleAdapter);
@@ -175,7 +182,7 @@
@Override
public void onResume() {
super.onResume();
-
+ mDataStateListener.setListener(true, mSubId, getContext());
updateBody();
// kick off background task to update stats
@@ -202,6 +209,12 @@
}
@Override
+ public void onPause() {
+ super.onPause();
+ mDataStateListener.setListener(false, mSubId, getContext());
+ }
+
+ @Override
public void onDestroy() {
mUidDetailProvider.clearCache();
mUidDetailProvider = null;
@@ -217,7 +230,6 @@
* binds them to visible controls.
*/
private void updateBody() {
- mBinding = true;
if (!isAdded()) return;
final Context context = getActivity();
@@ -231,10 +243,8 @@
// detail mode can change visible menus, invalidate
getActivity().invalidateOptionsMenu();
- mBinding = false;
-
int seriesColor = context.getColor(R.color.sim_noitification);
- if (mSubId != SubscriptionManager.INVALID_SUBSCRIPTION_ID){
+ if (mSubId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
final SubscriptionInfo sir = services.mSubscriptionManager
.getActiveSubscriptionInfo(mSubId);
@@ -252,33 +262,22 @@
* Update chart sweeps and cycle list to reflect {@link NetworkPolicy} for
* current {@link #mTemplate}.
*/
- private void updatePolicy(boolean refreshCycle) {
+ private void updatePolicy() {
final NetworkPolicy policy = services.mPolicyEditor.getPolicy(mTemplate);
+ final View configureButton = mHeader.findViewById(R.id.filter_settings);
//SUB SELECT
if (isNetworkPolicyModifiable(policy, mSubId) && isMobileDataAvailable(mSubId)) {
mChart.setNetworkPolicy(policy);
- mHeader.findViewById(R.id.filter_settings).setVisibility(View.VISIBLE);
- mHeader.findViewById(R.id.filter_settings).setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Bundle args = new Bundle();
- args.putParcelable(DataUsageList.EXTRA_NETWORK_TEMPLATE, mTemplate);
- startFragment(DataUsageList.this, BillingCycleSettings.class.getName(),
- R.string.billing_cycle, 0, args);
- }
- });
+ configureButton.setVisibility(View.VISIBLE);
} else {
// controls are disabled; don't bind warning/limit sweeps
mChart.setNetworkPolicy(null);
- mHeader.findViewById(R.id.filter_settings).setVisibility(View.GONE);
+ configureButton.setVisibility(View.GONE);
}
- if (refreshCycle) {
- // generate cycle list based on policy and available history
- if (mCycleAdapter.updateCycleList(policy, mChartData)) {
- updateDetailData();
- }
+ // generate cycle list based on policy and available history
+ if (mCycleAdapter.updateCycleList(policy, mChartData)) {
+ updateDetailData();
}
}
@@ -413,9 +412,10 @@
/**
* Accumulate data usage of a network stats entry for the item mapped by the collapse key.
* Creates the item if needed.
- * @param collapseKey the collapse key used to map the item.
- * @param knownItems collection of known (already existing) items.
- * @param entry the network stats entry to extract data usage from.
+ *
+ * @param collapseKey the collapse key used to map the item.
+ * @param knownItems collection of known (already existing) items.
+ * @param entry the network stats entry to extract data usage from.
* @param itemCategory the item is categorized on the list view by this category. Must be
*/
private static long accumulate(int collapseKey, final SparseArray<AppItem> knownItems,
@@ -461,7 +461,7 @@
if (LOGD) {
Log.d(TAG, "hasReadyMobileRadio:"
+ " conn.isNetworkSupported(TYPE_MOBILE)="
- + conn.isNetworkSupported(TYPE_MOBILE)
+ + conn.isNetworkSupported(TYPE_MOBILE)
+ " isReady=" + isReady);
}
return retVal;
@@ -480,10 +480,13 @@
final int slotId = SubscriptionManager.getSlotId(subId);
final boolean isReady = tele.getSimState(slotId) == SIM_STATE_READY;
- boolean retVal = conn.isNetworkSupported(TYPE_MOBILE) && isReady;
- if (LOGD) Log.d(TAG, "hasReadyMobileRadio: subId=" + subId
- + " conn.isNetworkSupported(TYPE_MOBILE)=" + conn.isNetworkSupported(TYPE_MOBILE)
- + " isReady=" + isReady);
+ boolean retVal = conn.isNetworkSupported(TYPE_MOBILE) && isReady;
+ if (LOGD) {
+ Log.d(TAG, "hasReadyMobileRadio: subId=" + subId
+ + " conn.isNetworkSupported(TYPE_MOBILE)="
+ + conn.isNetworkSupported(TYPE_MOBILE)
+ + " isReady=" + isReady);
+ }
return retVal;
}
@@ -524,8 +527,8 @@
mChartData = data;
mChart.setNetworkStats(mChartData.network);
- // calcuate policy cycles based on available data
- updatePolicy(true);
+ // calculate policy cycles based on available data
+ updatePolicy();
}
@Override
diff --git a/src/com/android/settings/datausage/TemplatePreferenceCategory.java b/src/com/android/settings/datausage/TemplatePreferenceCategory.java
index 1ce5f1c..0be5c73 100644
--- a/src/com/android/settings/datausage/TemplatePreferenceCategory.java
+++ b/src/com/android/settings/datausage/TemplatePreferenceCategory.java
@@ -17,10 +17,10 @@
import android.content.Context;
import android.net.NetworkTemplate;
import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceCategory;
import android.util.AttributeSet;
-import com.android.settings.DividedCategory;
-public class TemplatePreferenceCategory extends DividedCategory implements TemplatePreference {
+public class TemplatePreferenceCategory extends PreferenceCategory implements TemplatePreference {
private NetworkTemplate mTemplate;
private int mSubId;
diff --git a/src/com/android/settings/notification/RedactionInterstitial.java b/src/com/android/settings/notification/RedactionInterstitial.java
index f435257..08474a0 100644
--- a/src/com/android/settings/notification/RedactionInterstitial.java
+++ b/src/com/android/settings/notification/RedactionInterstitial.java
@@ -130,7 +130,7 @@
if (v.getId() == R.id.redaction_done_button) {
final RedactionInterstitial activity = (RedactionInterstitial) getActivity();
if (activity != null) {
- activity.setResult(RESULT_OK, activity.getResultIntentData());
+ activity.setResult(RESULT_OK, null);
finish();
}
}
diff --git a/src/com/android/settings/search2/SavedQueryViewHolder.java b/src/com/android/settings/search2/SavedQueryViewHolder.java
index 6629c89..e468eb9 100644
--- a/src/com/android/settings/search2/SavedQueryViewHolder.java
+++ b/src/com/android/settings/search2/SavedQueryViewHolder.java
@@ -36,4 +36,4 @@
titleView.setOnClickListener(v -> fragment.onSavedQueryClicked(result.title));
removeButton.setOnClickListener(v -> fragment.onRemoveSavedQueryClicked(result.title));
}
-}
+}
\ No newline at end of file
diff --git a/src/com/android/settings/wifi/ConfigureWifiSettings.java b/src/com/android/settings/wifi/ConfigureWifiSettings.java
index 78e869b..af80fd4 100644
--- a/src/com/android/settings/wifi/ConfigureWifiSettings.java
+++ b/src/com/android/settings/wifi/ConfigureWifiSettings.java
@@ -19,6 +19,7 @@
import static android.content.Context.WIFI_SERVICE;
import android.content.Context;
+import android.content.Intent;
import android.net.NetworkScoreManager;
import android.net.wifi.WifiManager;
import android.provider.SearchIndexableResource;
@@ -43,7 +44,7 @@
private static final String TAG = "ConfigureWifiSettings";
- private WifiManager mWifiManager;
+ private UseOpenWifiPreferenceController mUseOpenWifiPreferenceController;
@Override
public int getMetricsCategory() {
@@ -58,7 +59,8 @@
@Override
public void onAttach(Context context) {
super.onAttach(context);
- mProgressiveDisclosureMixin.setTileLimit(2);
+ mProgressiveDisclosureMixin.setTileLimit(
+ mUseOpenWifiPreferenceController.isAvailable() ? 3 : 2);
((SettingsActivity) getActivity()).setDisplaySearchMenu(true);
}
@@ -69,23 +71,35 @@
@Override
protected List<PreferenceController> getPreferenceControllers(Context context) {
- mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
+ final NetworkScoreManagerWrapper networkScoreManagerWrapper =
+ new NetworkScoreManagerWrapper(context.getSystemService(NetworkScoreManager.class));
+ mUseOpenWifiPreferenceController = new UseOpenWifiPreferenceController(context, this,
+ networkScoreManagerWrapper, getLifecycle());
+ final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
final List<PreferenceController> controllers = new ArrayList<>();
- controllers.add(new WifiInfoPreferenceController(context, getLifecycle(), mWifiManager));
- controllers.add(new CellularFallbackPreferenceController(context));
- controllers.add(new NotifyOpenNetworksPreferenceController(context, getLifecycle()));
controllers.add(new WifiWakeupPreferenceController(context, getLifecycle()));
controllers.add(new NetworkScorerPickerPreferenceController(context,
- new NetworkScoreManagerWrapper(
- (NetworkScoreManager) getSystemService(NETWORK_SCORE_SERVICE))));
+ networkScoreManagerWrapper));
+ controllers.add(new NotifyOpenNetworksPreferenceController(context, getLifecycle()));
+ controllers.add(mUseOpenWifiPreferenceController);
controllers.add(new WifiSleepPolicyPreferenceController(context));
- controllers.add(new WifiP2pPreferenceController(context, getLifecycle(), mWifiManager));
+ controllers.add(new WifiInfoPreferenceController(context, getLifecycle(), wifiManager));
+ controllers.add(new CellularFallbackPreferenceController(context));
+ controllers.add(new WifiP2pPreferenceController(context, getLifecycle(), wifiManager));
controllers.add(new WifiCallingPreferenceController(context));
controllers.add(new WpsPreferenceController(
- context, getLifecycle(), mWifiManager, getFragmentManager()));
+ context, getLifecycle(), wifiManager, getFragmentManager()));
return controllers;
}
+ @Override
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (mUseOpenWifiPreferenceController == null ||
+ !mUseOpenWifiPreferenceController.onActivityResult(requestCode, resultCode)) {
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+ }
+
public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
new BaseSearchIndexProvider() {
@Override
diff --git a/src/com/android/settings/wifi/UseOpenWifiPreferenceController.java b/src/com/android/settings/wifi/UseOpenWifiPreferenceController.java
new file mode 100644
index 0000000..09f5e92
--- /dev/null
+++ b/src/com/android/settings/wifi/UseOpenWifiPreferenceController.java
@@ -0,0 +1,165 @@
+package com.android.settings.wifi;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.database.ContentObserver;
+import android.net.NetworkScoreManager;
+
+import android.net.NetworkScorerAppData;
+import android.net.Uri;
+import android.os.Handler;
+import android.os.Looper;
+import android.provider.Settings;
+import android.support.annotation.VisibleForTesting;
+import android.support.v14.preference.SwitchPreference;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+import android.text.TextUtils;
+
+import com.android.settings.network.NetworkScoreManagerWrapper;
+import com.android.settings.core.PreferenceController;
+import com.android.settings.core.lifecycle.Lifecycle;
+import com.android.settings.core.lifecycle.LifecycleObserver;
+import com.android.settings.core.lifecycle.events.OnPause;
+import com.android.settings.core.lifecycle.events.OnResume;
+
+/**
+ * {@link PreferenceController} that controls whether a user wants to enable the "use open networks
+ * automatically" feature provider by the current network recommendation provider.
+ */
+public class UseOpenWifiPreferenceController extends PreferenceController
+ implements Preference.OnPreferenceChangeListener, LifecycleObserver, OnResume, OnPause {
+ private static final String KEY_USE_OPEN_WIFI_AUTOMATICALLY = "use_open_wifi_automatically";
+ @VisibleForTesting static final int REQUEST_CODE_OPEN_WIFI_AUTOMATICALLY = 400;
+
+ private final ContentResolver mContentResolver;
+ private final Fragment mFragment;
+ private final NetworkScoreManagerWrapper mNetworkScoreManagerWrapper;
+ private final SettingObserver mSettingObserver;
+
+ private Preference mPreference;
+ private ComponentName mEnableUseWifiComponentName;
+
+ public UseOpenWifiPreferenceController(Context context, Fragment fragment,
+ NetworkScoreManagerWrapper networkScoreManagerWrapper, Lifecycle lifecycle) {
+ super(context);
+ mContentResolver = context.getContentResolver();
+ mFragment = fragment;
+ mNetworkScoreManagerWrapper = networkScoreManagerWrapper;
+ mSettingObserver = new SettingObserver();
+ updateEnableUseWifiComponentName();
+ lifecycle.addObserver(this);
+ }
+
+ private void updateEnableUseWifiComponentName() {
+ NetworkScorerAppData appData = mNetworkScoreManagerWrapper.getActiveScorer();
+ mEnableUseWifiComponentName =
+ appData == null ? null : appData.getEnableUseOpenWifiActivity();
+ }
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+ mPreference = screen.findPreference(KEY_USE_OPEN_WIFI_AUTOMATICALLY);
+ }
+
+ @Override
+ public void onResume() {
+ mSettingObserver.register(mContentResolver);
+ }
+
+ @Override
+ public void onPause() {
+ mSettingObserver.unregister(mContentResolver);
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return mEnableUseWifiComponentName != null;
+ }
+
+ @Override
+ public String getPreferenceKey() {
+ return KEY_USE_OPEN_WIFI_AUTOMATICALLY;
+ }
+
+ @Override
+ public void updateState(Preference preference) {
+ if (!(preference instanceof SwitchPreference)) {
+ return;
+ }
+ final SwitchPreference useOpenWifiPreference = (SwitchPreference) preference;
+ useOpenWifiPreference.setVisible(isAvailable());
+ useOpenWifiPreference.setChecked(isSettingEnabled());
+ }
+
+ @Override
+ public boolean onPreferenceChange(Preference preference, Object newValue) {
+ if (!TextUtils.equals(preference.getKey(), KEY_USE_OPEN_WIFI_AUTOMATICALLY)
+ || !isAvailable()) {
+ return false;
+ }
+
+ if (isSettingEnabled()) {
+ Settings.Global.putString(mContentResolver,
+ Settings.Global.USE_OPEN_WIFI_PACKAGE, "");
+ return true;
+ }
+
+ Intent intent = new Intent(NetworkScoreManager.ACTION_CUSTOM_ENABLE);
+ intent.setComponent(mEnableUseWifiComponentName);
+ mFragment.startActivityForResult(intent, REQUEST_CODE_OPEN_WIFI_AUTOMATICALLY);
+ return false; // Updating state is done in onActivityResult.
+ }
+
+ private boolean isSettingEnabled() {
+ String enabledUseOpenWifiPackage = Settings.Global.getString(mContentResolver,
+ Settings.Global.USE_OPEN_WIFI_PACKAGE);
+ String currentUseOpenWifiPackage = mEnableUseWifiComponentName == null
+ ? null : mEnableUseWifiComponentName.getPackageName();
+ return TextUtils.equals(enabledUseOpenWifiPackage, currentUseOpenWifiPackage);
+ }
+
+ public boolean onActivityResult(int requestCode, int resultCode) {
+ if (requestCode != REQUEST_CODE_OPEN_WIFI_AUTOMATICALLY) {
+ return false;
+ }
+
+ if (resultCode == Activity.RESULT_OK) {
+ Settings.Global.putString(mContentResolver, Settings.Global.USE_OPEN_WIFI_PACKAGE,
+ mEnableUseWifiComponentName.getPackageName());
+ }
+ return true;
+ }
+
+ class SettingObserver extends ContentObserver {
+ private final Uri NETWORK_RECOMMENDATIONS_ENABLED_URI =
+ Settings.Global.getUriFor(Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED);
+
+ public SettingObserver() {
+ super(new Handler(Looper.getMainLooper()));
+ }
+
+ public void register(ContentResolver cr) {
+ cr.registerContentObserver(NETWORK_RECOMMENDATIONS_ENABLED_URI, false, this);
+ onChange(true /* selfChange */, NETWORK_RECOMMENDATIONS_ENABLED_URI);
+ }
+
+ public void unregister(ContentResolver cr) {
+ cr.unregisterContentObserver(this);
+ }
+
+ @Override
+ public void onChange(boolean selfChange, Uri uri) {
+ super.onChange(selfChange, uri);
+ if (NETWORK_RECOMMENDATIONS_ENABLED_URI.equals(uri)) {
+ updateEnableUseWifiComponentName();
+ updateState(mPreference);
+ }
+ }
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/SettingsActivityTest.java b/tests/robotests/src/com/android/settings/SettingsActivityTest.java
index 7822d83..9d53bc8 100644
--- a/tests/robotests/src/com/android/settings/SettingsActivityTest.java
+++ b/tests/robotests/src/com/android/settings/SettingsActivityTest.java
@@ -30,7 +30,6 @@
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
-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;
@@ -60,20 +59,6 @@
}
@Test
- public void testQueryTextChange_shouldUpdate() {
- final String testQuery = "abc";
-
- assertThat(mActivity.mSearchQuery).isNull();
- try {
- mActivity.onQueryTextChange(testQuery);
- } catch (NullPointerException e) {
- // Expected, because searchFeatureProvider is not wired up.
- }
-
- assertThat(mActivity.mSearchQuery).isEqualTo(testQuery);
- }
-
- @Test
public void launchSettingFragment_nullExtraShowFragment_shouldNotCrash()
throws ClassNotFoundException {
mActivity = spy(new SettingsActivity());
diff --git a/tests/robotests/src/com/android/settings/datausage/DataUsageListTest.java b/tests/robotests/src/com/android/settings/datausage/DataUsageListTest.java
new file mode 100644
index 0000000..c5570bb
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/datausage/DataUsageListTest.java
@@ -0,0 +1,71 @@
+/*
+ * 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 com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+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.util.ReflectionHelpers;
+
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class DataUsageListTest {
+
+ @Mock
+ private CellDataPreference.DataStateListener mListener;
+ @Mock
+ private TemplatePreference.NetworkServices mNetworkServices;
+ @Mock
+ private Context mContext;
+ private DataUsageList mDataUsageList;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mNetworkServices.mPolicyEditor = mock(NetworkPolicyEditor.class);
+ mDataUsageList = spy(DataUsageList.class);
+
+ doReturn(mContext).when(mDataUsageList).getContext();
+ ReflectionHelpers.setField(mDataUsageList, "mDataStateListener", mListener);
+ ReflectionHelpers.setField(mDataUsageList, "services", mNetworkServices);
+ }
+
+ @Test
+ public void resumePause_shouldListenUnlistenDataStateChange() {
+ mDataUsageList.onResume();
+
+ verify(mListener).setListener(true, 0, mContext);
+
+ mDataUsageList.onPause();
+
+ verify(mListener).setListener(false, 0, mContext);
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/wifi/UseOpenWifiPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/wifi/UseOpenWifiPreferenceControllerTest.java
new file mode 100644
index 0000000..aa89464
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/wifi/UseOpenWifiPreferenceControllerTest.java
@@ -0,0 +1,221 @@
+/*
+ * 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 static android.provider.Settings.Global.USE_OPEN_WIFI_PACKAGE;
+import static com.android.settings.wifi.UseOpenWifiPreferenceController.REQUEST_CODE_OPEN_WIFI_AUTOMATICALLY;
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.net.NetworkScoreManager;
+import android.net.NetworkScorerAppData;
+import android.provider.Settings;
+import android.support.v14.preference.SwitchPreference;
+import android.support.v7.preference.Preference;
+
+import com.android.settings.network.NetworkScoreManagerWrapper;
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+import com.android.settings.core.lifecycle.Lifecycle;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class UseOpenWifiPreferenceControllerTest {
+ private static ComponentName ENABLE_ACTIVITY_COMPONENT = new ComponentName("package", "activityClass");
+ private static NetworkScorerAppData APP_DATA =
+ new NetworkScorerAppData(0, null, null, ENABLE_ACTIVITY_COMPONENT);
+ private static NetworkScorerAppData APP_DATA_NO_ACTIVITY =
+ new NetworkScorerAppData(0, null, null, null);
+
+ @Mock private Lifecycle mLifecycle;
+ @Mock private Fragment mFragment;
+ @Mock private NetworkScoreManagerWrapper mNetworkScoreManagerWrapper;
+ @Captor private ArgumentCaptor<Intent> mIntentCaptor;
+ private Context mContext;
+ private UseOpenWifiPreferenceController mController;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+
+ mContext = RuntimeEnvironment.application;
+ }
+
+ private void createController() {
+ mController = new UseOpenWifiPreferenceController(
+ mContext, mFragment, mNetworkScoreManagerWrapper, mLifecycle);
+ }
+
+ @Test
+ public void testIsAvailable_noScorer() {
+ when(mNetworkScoreManagerWrapper.getActiveScorer()).thenReturn(null);
+
+ createController();
+
+ assertThat(mController.isAvailable()).isFalse();
+ }
+
+ @Test
+ public void testIsAvailable_noEnableActivity() {
+ when(mNetworkScoreManagerWrapper.getActiveScorer()).thenReturn(APP_DATA_NO_ACTIVITY);
+
+ createController();
+
+ assertThat(mController.isAvailable()).isFalse();
+ }
+
+ @Test
+ public void testIsAvailable_enableActivityExists() {
+ when(mNetworkScoreManagerWrapper.getActiveScorer()).thenReturn(APP_DATA);
+
+ createController();
+
+ assertThat(mController.isAvailable()).isTrue();
+ }
+
+ @Test
+ public void onPreferenceChange_nonMatchingKey_shouldDoNothing() {
+ createController();
+
+ final SwitchPreference pref = new SwitchPreference(mContext);
+
+ assertThat(mController.onPreferenceChange(pref, null)).isFalse();
+ }
+
+ @Test
+ public void onPreferenceChange_notAvailable_shouldDoNothing() {
+ when(mNetworkScoreManagerWrapper.getActiveScorer()).thenReturn(APP_DATA_NO_ACTIVITY);
+
+ createController();
+
+ final Preference pref = new Preference(mContext);
+ pref.setKey(mController.getPreferenceKey());
+
+ assertThat(mController.onPreferenceChange(pref, null)).isFalse();
+ }
+
+ @Test
+ public void onPreferenceChange_matchingKeyAndAvailable_enableShouldStartEnableActivity() {
+ when(mNetworkScoreManagerWrapper.getActiveScorer()).thenReturn(APP_DATA);
+ createController();
+
+ final SwitchPreference pref = new SwitchPreference(mContext);
+ pref.setKey(mController.getPreferenceKey());
+
+ assertThat(mController.onPreferenceChange(pref, null)).isFalse();
+ verify(mFragment).startActivityForResult(mIntentCaptor.capture(),
+ eq(REQUEST_CODE_OPEN_WIFI_AUTOMATICALLY));
+ Intent activityIntent = mIntentCaptor.getValue();
+ assertThat(activityIntent.getComponent()).isEqualTo(ENABLE_ACTIVITY_COMPONENT);
+ assertThat(activityIntent.getAction()).isEqualTo(NetworkScoreManager.ACTION_CUSTOM_ENABLE);
+ }
+
+ @Test
+ public void onPreferenceChange_matchingKeyAndAvailable_disableShouldUpdateSetting() {
+ when(mNetworkScoreManagerWrapper.getActiveScorer()).thenReturn(APP_DATA);
+ Settings.Global.putString(mContext.getContentResolver(), USE_OPEN_WIFI_PACKAGE,
+ ENABLE_ACTIVITY_COMPONENT.getPackageName());
+
+ createController();
+
+ final SwitchPreference pref = new SwitchPreference(mContext);
+ pref.setKey(mController.getPreferenceKey());
+
+ assertThat(mController.onPreferenceChange(pref, null)).isTrue();
+ assertThat(Settings.Global.getString(mContext.getContentResolver(), USE_OPEN_WIFI_PACKAGE))
+ .isEqualTo("");
+ }
+
+ @Test
+ public void onActivityResult_nonmatchingRequestCode_shouldDoNothing() {
+ createController();
+
+ assertThat(mController.onActivityResult(234 /* requestCode */ , Activity.RESULT_OK))
+ .isEqualTo(false);
+ assertThat(Settings.Global.getString(mContext.getContentResolver(), USE_OPEN_WIFI_PACKAGE))
+ .isNull();
+ }
+
+ @Test
+ public void onActivityResult_matchingRequestCode_nonOkResult_shouldDoNothing() {
+ createController();
+
+ assertThat(mController
+ .onActivityResult(REQUEST_CODE_OPEN_WIFI_AUTOMATICALLY, Activity.RESULT_CANCELED))
+ .isEqualTo(true);
+ assertThat(Settings.Global.getString(mContext.getContentResolver(), USE_OPEN_WIFI_PACKAGE))
+ .isNull();
+ }
+
+ @Test
+ public void onActivityResult_matchingRequestCode_okResult_updatesSetting() {
+ when(mNetworkScoreManagerWrapper.getActiveScorer()).thenReturn(APP_DATA);
+ createController();
+
+ assertThat(mController
+ .onActivityResult(REQUEST_CODE_OPEN_WIFI_AUTOMATICALLY, Activity.RESULT_OK))
+ .isEqualTo(true);
+ assertThat(Settings.Global.getString(mContext.getContentResolver(), USE_OPEN_WIFI_PACKAGE))
+ .isEqualTo(ENABLE_ACTIVITY_COMPONENT.getPackageName());
+ }
+
+ @Test
+ public void updateState_preferenceSetCheckedAndSetVisibleWhenSettingsAreEnabled() {
+ when(mNetworkScoreManagerWrapper.getActiveScorer()).thenReturn(APP_DATA);
+ createController();
+
+ final SwitchPreference preference = mock(SwitchPreference.class);
+ Settings.Global.putString(mContext.getContentResolver(), USE_OPEN_WIFI_PACKAGE,
+ ENABLE_ACTIVITY_COMPONENT.getPackageName());
+
+ mController.updateState(preference);
+
+ verify(preference).setVisible(true);
+ verify(preference).setChecked(true);
+ }
+
+ @Test
+ public void updateState_preferenceSetCheckedAndSetVisibleWhenSettingsAreDisabled() {
+ final SwitchPreference preference = mock(SwitchPreference.class);
+ Settings.Global.putString(mContext.getContentResolver(), USE_OPEN_WIFI_PACKAGE, "");
+ createController();
+
+ mController.updateState(preference);
+
+ verify(preference).setVisible(false);
+ verify(preference).setChecked(false);
+ }
+}