2 * Copyright (C) 2010 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.settings.wifi;
19 import static android.os.UserManager.DISALLOW_CONFIG_WIFI;
21 import android.annotation.NonNull;
22 import android.app.Activity;
23 import android.app.Dialog;
24 import android.app.admin.DevicePolicyManager;
25 import android.content.ComponentName;
26 import android.content.ContentResolver;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.pm.PackageManager;
30 import android.content.pm.PackageManager.NameNotFoundException;
31 import android.content.res.Resources;
32 import android.net.ConnectivityManager;
33 import android.net.NetworkInfo;
34 import android.net.NetworkInfo.State;
35 import android.net.wifi.WifiConfiguration;
36 import android.net.wifi.WifiManager;
37 import android.net.wifi.WpsInfo;
38 import android.nfc.NfcAdapter;
39 import android.os.Bundle;
40 import android.os.HandlerThread;
41 import android.os.Process;
42 import android.provider.Settings;
43 import android.support.annotation.VisibleForTesting;
44 import android.support.v7.preference.Preference;
45 import android.support.v7.preference.PreferenceCategory;
46 import android.util.Log;
47 import android.view.ContextMenu;
48 import android.view.ContextMenu.ContextMenuInfo;
49 import android.view.Menu;
50 import android.view.MenuItem;
51 import android.view.View;
52 import android.widget.ProgressBar;
53 import android.widget.Toast;
55 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
56 import com.android.settings.LinkifyUtils;
57 import com.android.settings.R;
58 import com.android.settings.RestrictedSettingsFragment;
59 import com.android.settings.SettingsActivity;
60 import com.android.settings.dashboard.SummaryLoader;
61 import com.android.settings.location.ScanningSettings;
62 import com.android.settings.search.BaseSearchIndexProvider;
63 import com.android.settings.search.Indexable;
64 import com.android.settings.search.SearchIndexableRaw;
65 import com.android.settings.widget.SummaryUpdater.OnSummaryChangeListener;
66 import com.android.settings.widget.SwitchBarController;
67 import com.android.settings.wifi.details.WifiNetworkDetailsFragment;
68 import com.android.settingslib.RestrictedLockUtils;
69 import com.android.settingslib.wifi.AccessPoint;
70 import com.android.settingslib.wifi.AccessPoint.AccessPointListener;
71 import com.android.settingslib.wifi.AccessPointPreference;
72 import com.android.settingslib.wifi.WifiTracker;
73 import com.android.settingslib.wifi.WifiTrackerFactory;
75 import java.util.ArrayList;
76 import java.util.List;
79 * Two types of UI are provided here.
81 * The first is for "usual Settings", appearing as any other Setup fragment.
83 * The second is for Setup Wizard, with a simplified interface that hides the action bar
86 public class WifiSettings extends RestrictedSettingsFragment
87 implements Indexable, WifiTracker.WifiListener, AccessPointListener,
88 WifiDialog.WifiDialogListener {
90 private static final String TAG = "WifiSettings";
91 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
93 /* package */ static final int MENU_ID_WPS_PBC = Menu.FIRST;
94 private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1;
95 private static final int MENU_ID_CONNECT = Menu.FIRST + 6;
96 private static final int MENU_ID_FORGET = Menu.FIRST + 7;
97 private static final int MENU_ID_MODIFY = Menu.FIRST + 8;
98 private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9;
100 public static final int WIFI_DIALOG_ID = 1;
101 /* package */ static final int WPS_PBC_DIALOG_ID = 2;
102 private static final int WPS_PIN_DIALOG_ID = 3;
103 private static final int WRITE_NFC_DIALOG_ID = 6;
105 // Instance state keys
106 private static final String SAVE_DIALOG_MODE = "dialog_mode";
107 private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state";
108 private static final String SAVED_WIFI_NFC_DIALOG_STATE = "wifi_nfc_dlg_state";
110 private static final String PREF_KEY_EMPTY_WIFI_LIST = "wifi_empty_list";
111 private static final String PREF_KEY_CONNECTED_ACCESS_POINTS = "connected_access_point";
112 private static final String PREF_KEY_ACCESS_POINTS = "access_points";
113 private static final String PREF_KEY_ADDITIONAL_SETTINGS = "additional_settings";
114 private static final String PREF_KEY_CONFIGURE_WIFI_SETTINGS = "configure_settings";
115 private static final String PREF_KEY_SAVED_NETWORKS = "saved_networks";
117 private final Runnable mUpdateAccessPointsRunnable = () -> {
118 updateAccessPointPreferences();
120 private final Runnable mHideProgressBarRunnable = () -> {
121 setProgressBarVisible(false);
124 protected WifiManager mWifiManager;
125 private WifiManager.ActionListener mConnectListener;
126 private WifiManager.ActionListener mSaveListener;
127 private WifiManager.ActionListener mForgetListener;
130 * The state of {@link #isUiRestricted()} at {@link #onCreate(Bundle)}}. This is neccesary to
131 * ensure that behavior is consistent if {@link #isUiRestricted()} changes. It could be changed
132 * by the Test DPC tool in AFW mode.
134 private boolean mIsRestricted;
136 private WifiEnabler mWifiEnabler;
137 // An access point being editted is stored here.
138 private AccessPoint mSelectedAccessPoint;
140 private WifiDialog mDialog;
141 private WriteWifiConfigToNfcDialog mWifiToNfcDialog;
143 private ProgressBar mProgressHeader;
145 // this boolean extra specifies whether to disable the Next button when not connected. Used by
146 // account creation outside of setup wizard.
147 private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
148 // This string extra specifies a network to open the connect dialog on, so the user can enter
149 // network credentials. This is used by quick settings for secured networks.
150 private static final String EXTRA_START_CONNECT_SSID = "wifi_start_connect_ssid";
152 // should Next button only be enabled when we have a connection?
153 private boolean mEnableNextOnConnection;
155 // Save the dialog details
156 private int mDialogMode;
157 private AccessPoint mDlgAccessPoint;
158 private Bundle mAccessPointSavedState;
159 private Bundle mWifiNfcDialogSavedState;
161 private WifiTracker mWifiTracker;
162 private String mOpenSsid;
164 private HandlerThread mBgThread;
166 private AccessPointPreference.UserBadgeCache mUserBadgeCache;
168 private PreferenceCategory mConnectedAccessPointPreferenceCategory;
169 private PreferenceCategory mAccessPointsPreferenceCategory;
170 private PreferenceCategory mAdditionalSettingsPreferenceCategory;
171 private Preference mAddPreference;
172 private Preference mConfigureWifiSettingsPreference;
173 private Preference mSavedNetworksPreference;
174 private LinkablePreference mStatusMessagePreference;
177 private static final String DATA_KEY_REFERENCE = "main_toggle_wifi";
179 /* End of "used in Wifi Setup context" */
181 public WifiSettings() {
182 super(DISALLOW_CONFIG_WIFI);
186 public void onViewCreated(View view, Bundle savedInstanceState) {
187 super.onViewCreated(view, savedInstanceState);
188 final Activity activity = getActivity();
189 if (activity != null) {
190 mProgressHeader = (ProgressBar) setPinnedHeaderView(R.layout.wifi_progress_header);
191 setProgressBarVisible(false);
196 public void onCreate(Bundle icicle) {
197 super.onCreate(icicle);
199 // TODO(b/37429702): Add animations and preference comparator back after initial screen is
201 setAnimationAllowed(false);
203 addPreferencesFromResource(R.xml.wifi_settings);
205 mConnectedAccessPointPreferenceCategory =
206 (PreferenceCategory) findPreference(PREF_KEY_CONNECTED_ACCESS_POINTS);
207 mAccessPointsPreferenceCategory =
208 (PreferenceCategory) findPreference(PREF_KEY_ACCESS_POINTS);
209 mAdditionalSettingsPreferenceCategory =
210 (PreferenceCategory) findPreference(PREF_KEY_ADDITIONAL_SETTINGS);
211 mConfigureWifiSettingsPreference = findPreference(PREF_KEY_CONFIGURE_WIFI_SETTINGS);
212 mSavedNetworksPreference = findPreference(PREF_KEY_SAVED_NETWORKS);
214 Context prefContext = getPrefContext();
215 mAddPreference = new Preference(prefContext);
216 mAddPreference.setIcon(R.drawable.ic_menu_add_inset);
217 mAddPreference.setTitle(R.string.wifi_add_network);
218 mStatusMessagePreference = new LinkablePreference(prefContext);
220 mUserBadgeCache = new AccessPointPreference.UserBadgeCache(getPackageManager());
222 mIsRestricted = isUiRestricted();
224 mBgThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
229 public void onDestroy() {
235 public void onActivityCreated(Bundle savedInstanceState) {
236 super.onActivityCreated(savedInstanceState);
238 mWifiTracker = WifiTrackerFactory.create(
239 getActivity(), this, mBgThread.getLooper(), true, true, false);
240 mWifiManager = mWifiTracker.getManager();
242 mConnectListener = new WifiManager.ActionListener() {
244 public void onSuccess() {
247 public void onFailure(int reason) {
248 Activity activity = getActivity();
249 if (activity != null) {
250 Toast.makeText(activity,
251 R.string.wifi_failed_connect_message,
252 Toast.LENGTH_SHORT).show();
257 mSaveListener = new WifiManager.ActionListener() {
259 public void onSuccess() {
262 public void onFailure(int reason) {
263 Activity activity = getActivity();
264 if (activity != null) {
265 Toast.makeText(activity,
266 R.string.wifi_failed_save_message,
267 Toast.LENGTH_SHORT).show();
272 mForgetListener = new WifiManager.ActionListener() {
274 public void onSuccess() {
277 public void onFailure(int reason) {
278 Activity activity = getActivity();
279 if (activity != null) {
280 Toast.makeText(activity,
281 R.string.wifi_failed_forget_message,
282 Toast.LENGTH_SHORT).show();
287 if (savedInstanceState != null) {
288 mDialogMode = savedInstanceState.getInt(SAVE_DIALOG_MODE);
289 if (savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) {
290 mAccessPointSavedState =
291 savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
294 if (savedInstanceState.containsKey(SAVED_WIFI_NFC_DIALOG_STATE)) {
295 mWifiNfcDialogSavedState =
296 savedInstanceState.getBundle(SAVED_WIFI_NFC_DIALOG_STATE);
300 // if we're supposed to enable/disable the Next button based on our current connection
301 // state, start it off in the right state
302 Intent intent = getActivity().getIntent();
303 mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
305 if (mEnableNextOnConnection) {
306 if (hasNextButton()) {
307 final ConnectivityManager connectivity = (ConnectivityManager)
308 getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
309 if (connectivity != null) {
310 NetworkInfo info = connectivity.getNetworkInfo(
311 ConnectivityManager.TYPE_WIFI);
312 changeNextButtonState(info.isConnected());
317 registerForContextMenu(getListView());
318 setHasOptionsMenu(true);
320 if (intent.hasExtra(EXTRA_START_CONNECT_SSID)) {
321 mOpenSsid = intent.getStringExtra(EXTRA_START_CONNECT_SSID);
326 public void onDestroyView() {
327 super.onDestroyView();
329 if (mWifiEnabler != null) {
330 mWifiEnabler.teardownSwitchController();
335 public void onStart() {
338 // On/off switch is hidden for Setup Wizard (returns null)
339 mWifiEnabler = createWifiEnabler();
341 mWifiTracker.startTracking();
344 if (!isUiRestrictedByOnlyAdmin()) {
345 getEmptyTextView().setText(R.string.wifi_empty_list_user_restricted);
347 getPreferenceScreen().removeAll();
351 onWifiStateChanged(mWifiManager.getWifiState());
355 * Only update the AP list if there are not any APs currently shown.
357 * <p>Thus forceUpdate will only be called during cold start or when toggling between wifi on
358 * and off. In other use cases, the previous APs will remain until the next update is received
359 * from {@link WifiTracker}.
361 private void conditionallyForceUpdateAPs() {
362 if (mAccessPointsPreferenceCategory.getPreferenceCount() > 0
363 && mAccessPointsPreferenceCategory.getPreference(0) instanceof
364 AccessPointPreference) {
365 // Make sure we don't update due to callbacks initiated by sticky broadcasts in
367 Log.d(TAG, "Did not force update APs due to existing APs displayed");
368 getView().removeCallbacks(mUpdateAccessPointsRunnable);
371 setProgressBarVisible(true);
372 mWifiTracker.forceUpdate();
374 Log.d(TAG, "WifiSettings force update APs: " + mWifiTracker.getAccessPoints());
376 getView().removeCallbacks(mUpdateAccessPointsRunnable);
377 updateAccessPointPreferences();
381 * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard)
383 private WifiEnabler createWifiEnabler() {
384 final SettingsActivity activity = (SettingsActivity) getActivity();
385 return new WifiEnabler(activity, new SwitchBarController(activity.getSwitchBar()),
386 mMetricsFeatureProvider);
390 public void onResume() {
391 final Activity activity = getActivity();
393 if (mWifiEnabler != null) {
394 mWifiEnabler.resume(activity);
399 public void onPause() {
401 if (mWifiEnabler != null) {
402 mWifiEnabler.pause();
407 public void onStop() {
408 mWifiTracker.stopTracking();
409 getView().removeCallbacks(mUpdateAccessPointsRunnable);
410 getView().removeCallbacks(mHideProgressBarRunnable);
415 public int getMetricsCategory() {
416 return MetricsEvent.WIFI;
420 public void onSaveInstanceState(Bundle outState) {
421 super.onSaveInstanceState(outState);
423 // If the dialog is showing, save its state.
424 if (mDialog != null && mDialog.isShowing()) {
425 outState.putInt(SAVE_DIALOG_MODE, mDialogMode);
426 if (mDlgAccessPoint != null) {
427 mAccessPointSavedState = new Bundle();
428 mDlgAccessPoint.saveWifiState(mAccessPointSavedState);
429 outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState);
433 if (mWifiToNfcDialog != null && mWifiToNfcDialog.isShowing()) {
434 Bundle savedState = new Bundle();
435 mWifiToNfcDialog.saveState(savedState);
436 outState.putBundle(SAVED_WIFI_NFC_DIALOG_STATE, savedState);
441 public boolean onOptionsItemSelected(MenuItem item) {
442 // If the user is not allowed to configure wifi, do not handle menu selections.
447 switch (item.getItemId()) {
448 case MENU_ID_WPS_PBC:
449 showDialog(WPS_PBC_DIALOG_ID);
453 if (getActivity() instanceof SettingsActivity) {
454 ((SettingsActivity) getActivity()).startPreferencePanel(
455 WifiP2pSettings.class.getCanonicalName(),
457 R.string.wifi_p2p_settings_title, null,
460 startFragment(this, WifiP2pSettings.class.getCanonicalName(),
461 R.string.wifi_p2p_settings_title, -1, null);
465 case MENU_ID_WPS_PIN:
466 showDialog(WPS_PIN_DIALOG_ID);
469 return super.onOptionsItemSelected(item);
473 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
474 Preference preference = (Preference) view.getTag();
476 if (preference instanceof LongPressAccessPointPreference) {
477 mSelectedAccessPoint =
478 ((LongPressAccessPointPreference) preference).getAccessPoint();
479 menu.setHeaderTitle(mSelectedAccessPoint.getSsid());
480 if (mSelectedAccessPoint.isConnectable()) {
481 menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect);
484 WifiConfiguration config = mSelectedAccessPoint.getConfig();
485 // Some configs are ineditable
486 if (isEditabilityLockedDown(getActivity(), config)) {
490 if (mSelectedAccessPoint.isSaved() || mSelectedAccessPoint.isEphemeral()) {
491 // Allow forgetting a network if either the network is saved or ephemerally
492 // connected. (In the latter case, "forget" blacklists the network so it won't
493 // be used again, ephemerally).
494 menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget);
496 if (mSelectedAccessPoint.isSaved()) {
497 menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify);
498 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
499 if (nfcAdapter != null && nfcAdapter.isEnabled() &&
500 mSelectedAccessPoint.getSecurity() != AccessPoint.SECURITY_NONE) {
501 // Only allow writing of NFC tags for password-protected networks.
502 menu.add(Menu.NONE, MENU_ID_WRITE_NFC, 0, R.string.wifi_menu_write_to_nfc);
509 public boolean onContextItemSelected(MenuItem item) {
510 if (mSelectedAccessPoint == null) {
511 return super.onContextItemSelected(item);
513 switch (item.getItemId()) {
514 case MENU_ID_CONNECT: {
515 boolean isSavedNetwork = mSelectedAccessPoint.isSaved();
516 if (isSavedNetwork) {
517 connect(mSelectedAccessPoint.getConfig(), isSavedNetwork);
518 } else if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE) {
519 /** Bypass dialog for unsecured networks */
520 mSelectedAccessPoint.generateOpenNetworkConfig();
521 connect(mSelectedAccessPoint.getConfig(), isSavedNetwork);
523 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT);
527 case MENU_ID_FORGET: {
531 case MENU_ID_MODIFY: {
532 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_MODIFY);
535 case MENU_ID_WRITE_NFC:
536 showDialog(WRITE_NFC_DIALOG_ID);
540 return super.onContextItemSelected(item);
544 public boolean onPreferenceTreeClick(Preference preference) {
545 // If the preference has a fragment set, open that
546 if (preference.getFragment() != null) {
547 preference.setOnPreferenceClickListener(null);
548 return super.onPreferenceTreeClick(preference);
551 if (preference instanceof LongPressAccessPointPreference) {
552 mSelectedAccessPoint = ((LongPressAccessPointPreference) preference).getAccessPoint();
553 if (mSelectedAccessPoint == null) {
556 if (mSelectedAccessPoint.isActive()) {
557 return super.onPreferenceTreeClick(preference);
560 * Bypass dialog and connect to unsecured networks, or previously connected saved
561 * networks, or Passpoint provided networks.
563 WifiConfiguration config = mSelectedAccessPoint.getConfig();
564 if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE) {
565 mSelectedAccessPoint.generateOpenNetworkConfig();
566 connect(mSelectedAccessPoint.getConfig(), mSelectedAccessPoint.isSaved());
567 } else if (mSelectedAccessPoint.isSaved() && config != null
568 && config.getNetworkSelectionStatus() != null
569 && config.getNetworkSelectionStatus().getHasEverConnected()) {
570 connect(config, true /* isSavedNetwork */);
571 } else if (mSelectedAccessPoint.isPasspoint()) {
572 // Access point provided by an installed Passpoint provider, connect using
573 // the associated config.
574 connect(config, true /* isSavedNetwork */);
576 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT);
578 } else if (preference == mAddPreference) {
579 onAddNetworkPressed();
581 return super.onPreferenceTreeClick(preference);
586 private void showDialog(AccessPoint accessPoint, int dialogMode) {
587 if (accessPoint != null) {
588 WifiConfiguration config = accessPoint.getConfig();
589 if (isEditabilityLockedDown(getActivity(), config) && accessPoint.isActive()) {
590 RestrictedLockUtils.sendShowAdminSupportDetailsIntent(getActivity(),
591 RestrictedLockUtils.getDeviceOwner(getActivity()));
596 if (mDialog != null) {
597 removeDialog(WIFI_DIALOG_ID);
601 // Save the access point and edit mode
602 mDlgAccessPoint = accessPoint;
603 mDialogMode = dialogMode;
605 showDialog(WIFI_DIALOG_ID);
609 public Dialog onCreateDialog(int dialogId) {
612 AccessPoint ap = mDlgAccessPoint; // For manual launch
613 if (ap == null) { // For re-launch from saved state
614 if (mAccessPointSavedState != null) {
615 ap = new AccessPoint(getActivity(), mAccessPointSavedState);
616 // For repeated orientation changes
617 mDlgAccessPoint = ap;
618 // Reset the saved access point data
619 mAccessPointSavedState = null;
622 // If it's null, fine, it's for Add Network
623 mSelectedAccessPoint = ap;
624 mDialog = new WifiDialog(getActivity(), this, ap, mDialogMode,
625 /* no hide submit/connect */ false);
627 case WPS_PBC_DIALOG_ID:
628 return new WpsDialog(getActivity(), WpsInfo.PBC);
629 case WPS_PIN_DIALOG_ID:
630 return new WpsDialog(getActivity(), WpsInfo.DISPLAY);
631 case WRITE_NFC_DIALOG_ID:
632 if (mSelectedAccessPoint != null) {
633 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(
635 mSelectedAccessPoint.getSecurity(),
636 new WifiManagerWrapper(mWifiManager));
637 } else if (mWifiNfcDialogSavedState != null) {
638 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(getActivity(),
639 mWifiNfcDialogSavedState, new WifiManagerWrapper(mWifiManager));
642 return mWifiToNfcDialog;
644 return super.onCreateDialog(dialogId);
648 public int getDialogMetricsCategory(int dialogId) {
651 return MetricsEvent.DIALOG_WIFI_AP_EDIT;
652 case WPS_PBC_DIALOG_ID:
653 return MetricsEvent.DIALOG_WIFI_PBC;
654 case WPS_PIN_DIALOG_ID:
655 return MetricsEvent.DIALOG_WIFI_PIN;
656 case WRITE_NFC_DIALOG_ID:
657 return MetricsEvent.DIALOG_WIFI_WRITE_NFC;
664 * Called to indicate the list of AccessPoints has been updated and
665 * getAccessPoints should be called to get the latest information.
668 public void onAccessPointsChanged() {
669 Log.d(TAG, "onAccessPointsChanged (WifiTracker) callback initiated");
670 updateAccessPointsDelayed();
674 * Updates access points from {@link WifiManager#getScanResults()}. Adds a delay to have
675 * progress bar displayed before starting to modify APs.
677 private void updateAccessPointsDelayed() {
678 // Safeguard from some delayed event handling
679 if (getActivity() != null && !mIsRestricted && mWifiManager.isWifiEnabled()) {
680 setProgressBarVisible(true);
681 getView().postDelayed(mUpdateAccessPointsRunnable, 300 /* delay milliseconds */);
685 /** Called when the state of Wifi has changed. */
687 public void onWifiStateChanged(int state) {
692 final int wifiState = mWifiManager.getWifiState();
694 case WifiManager.WIFI_STATE_ENABLED:
695 conditionallyForceUpdateAPs();
698 case WifiManager.WIFI_STATE_ENABLING:
699 removeConnectedAccessPointPreference();
700 mAccessPointsPreferenceCategory.removeAll();
701 addMessagePreference(R.string.wifi_starting);
702 setProgressBarVisible(true);
705 case WifiManager.WIFI_STATE_DISABLING:
706 removeConnectedAccessPointPreference();
707 mAccessPointsPreferenceCategory.removeAll();
708 addMessagePreference(R.string.wifi_stopping);
711 case WifiManager.WIFI_STATE_DISABLED:
713 setAdditionalSettingsSummaries();
714 setProgressBarVisible(false);
720 * Called when the connection state of wifi has changed and isConnected
721 * should be called to get the updated state.
724 public void onConnectedChanged() {
725 updateAccessPointsDelayed();
726 changeNextButtonState(mWifiTracker.isConnected());
729 private void updateAccessPointPreferences() {
730 // in case state has changed
731 if (!mWifiManager.isWifiEnabled()) {
734 // AccessPoints are sorted by the WifiTracker
735 final List<AccessPoint> accessPoints = mWifiTracker.getAccessPoints();
737 Log.d(TAG, "updateAccessPoints called for: " + accessPoints);
740 boolean hasAvailableAccessPoints = false;
741 mAccessPointsPreferenceCategory.removePreference(mStatusMessagePreference);
742 cacheRemoveAllPrefs(mAccessPointsPreferenceCategory);
745 configureConnectedAccessPointPreferenceCategory(accessPoints) ? 1 : 0;
746 int numAccessPoints = accessPoints.size();
747 for (; index < numAccessPoints; index++) {
748 AccessPoint accessPoint = accessPoints.get(index);
749 // Ignore access points that are out of range.
750 if (accessPoint.isReachable()) {
751 String key = AccessPointPreference.generatePreferenceKey(accessPoint);
752 hasAvailableAccessPoints = true;
753 LongPressAccessPointPreference pref =
754 (LongPressAccessPointPreference) getCachedPreference(key);
756 pref.setOrder(index);
759 LongPressAccessPointPreference preference =
760 createLongPressActionPointPreference(accessPoint);
761 preference.setKey(key);
762 preference.setOrder(index);
763 if (mOpenSsid != null && mOpenSsid.equals(accessPoint.getSsidStr())
764 && !accessPoint.isSaved()
765 && accessPoint.getSecurity() != AccessPoint.SECURITY_NONE) {
766 onPreferenceTreeClick(preference);
769 mAccessPointsPreferenceCategory.addPreference(preference);
770 accessPoint.setListener(WifiSettings.this);
771 preference.refresh();
774 removeCachedPrefs(mAccessPointsPreferenceCategory);
775 mAddPreference.setOrder(index);
776 mAccessPointsPreferenceCategory.addPreference(mAddPreference);
777 setAdditionalSettingsSummaries();
779 if (!hasAvailableAccessPoints) {
780 setProgressBarVisible(true);
781 Preference pref = new Preference(getPrefContext());
782 pref.setSelectable(false);
783 pref.setSummary(R.string.wifi_empty_list_wifi_on);
784 pref.setOrder(index++);
785 pref.setKey(PREF_KEY_EMPTY_WIFI_LIST);
786 mAccessPointsPreferenceCategory.addPreference(pref);
788 // Continuing showing progress bar for an additional delay to overlap with animation
789 getView().postDelayed(mHideProgressBarRunnable, 1700 /* delay millis */);
794 private LongPressAccessPointPreference createLongPressActionPointPreference(
795 AccessPoint accessPoint) {
796 return new LongPressAccessPointPreference(accessPoint, getPrefContext(), mUserBadgeCache,
797 false, R.drawable.ic_wifi_signal_0, this);
801 * Configure the ConnectedAccessPointPreferenceCategory and return true if the Category was
804 private boolean configureConnectedAccessPointPreferenceCategory(
805 List<AccessPoint> accessPoints) {
806 if (accessPoints.size() == 0) {
807 removeConnectedAccessPointPreference();
811 AccessPoint connectedAp = accessPoints.get(0);
812 if (!connectedAp.isActive()) {
813 removeConnectedAccessPointPreference();
817 // Is the preference category empty?
818 if (mConnectedAccessPointPreferenceCategory.getPreferenceCount() == 0) {
819 addConnectedAccessPointPreference(connectedAp);
823 // Is the previous currently connected SSID different from the new one?
824 if (!((AccessPointPreference)
825 mConnectedAccessPointPreferenceCategory.getPreference(0))
826 .getAccessPoint().getSsidStr().equals(
827 connectedAp.getSsidStr())) {
828 removeConnectedAccessPointPreference();
829 addConnectedAccessPointPreference(connectedAp);
833 // Else same AP is connected, simply refresh the connected access point preference
834 // (first and only access point in this category).
835 ((LongPressAccessPointPreference) mConnectedAccessPointPreferenceCategory.getPreference(0))
841 * Creates a Preference for the given {@link AccessPoint} and adds it to the
842 * {@link #mConnectedAccessPointPreferenceCategory}.
844 private void addConnectedAccessPointPreference(AccessPoint connectedAp) {
845 String key = connectedAp.getBssid();
846 LongPressAccessPointPreference pref = (LongPressAccessPointPreference)
847 getCachedPreference(key);
849 pref = createLongPressActionPointPreference(connectedAp);
852 // Save the state of the current access point in the bundle so that we can restore it
853 // in the Wifi Network Details Fragment
854 pref.getAccessPoint().saveWifiState(pref.getExtras());
855 pref.setFragment(WifiNetworkDetailsFragment.class.getName());
858 mConnectedAccessPointPreferenceCategory.addPreference(pref);
859 mConnectedAccessPointPreferenceCategory.setVisible(true);
862 /** Removes all preferences and hide the {@link #mConnectedAccessPointPreferenceCategory}. */
863 private void removeConnectedAccessPointPreference() {
864 mConnectedAccessPointPreferenceCategory.removeAll();
865 mConnectedAccessPointPreferenceCategory.setVisible(false);
868 private void setAdditionalSettingsSummaries() {
869 mAdditionalSettingsPreferenceCategory.addPreference(mConfigureWifiSettingsPreference);
870 final int defaultWakeupAvailable = getResources().getInteger(
871 com.android.internal.R.integer.config_wifi_wakeup_available);
872 boolean wifiWakeupAvailable = Settings.Global.getInt(
873 getContentResolver(), Settings.Global.WIFI_WAKEUP_AVAILABLE, defaultWakeupAvailable)
875 if (wifiWakeupAvailable) {
876 boolean wifiWakeupEnabled = Settings.Global.getInt(
877 getContentResolver(), Settings.Global.WIFI_WAKEUP_ENABLED, 0) == 1;
878 mConfigureWifiSettingsPreference.setSummary(getString(wifiWakeupEnabled
879 ? R.string.wifi_configure_settings_preference_summary_wakeup_on
880 : R.string.wifi_configure_settings_preference_summary_wakeup_off));
882 int numSavedNetworks = mWifiTracker.getNumSavedNetworks();
883 if (numSavedNetworks > 0) {
884 mAdditionalSettingsPreferenceCategory.addPreference(mSavedNetworksPreference);
885 mSavedNetworksPreference.setSummary(
886 getResources().getQuantityString(R.plurals.wifi_saved_access_points_summary,
887 numSavedNetworks, numSavedNetworks));
889 mAdditionalSettingsPreferenceCategory.removePreference(mSavedNetworksPreference);
893 private void setOffMessage() {
894 final CharSequence title = getText(R.string.wifi_empty_list_wifi_off);
895 // Don't use WifiManager.isScanAlwaysAvailable() to check the Wi-Fi scanning mode. Instead,
896 // read the system settings directly. Because when the device is in Airplane mode, even if
897 // Wi-Fi scanning mode is on, WifiManager.isScanAlwaysAvailable() still returns "off".
898 final boolean wifiScanningMode = Settings.Global.getInt(getActivity().getContentResolver(),
899 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1;
900 final CharSequence description = wifiScanningMode ? getText(R.string.wifi_scan_notify_text)
901 : getText(R.string.wifi_scan_notify_text_scanning_off);
902 final LinkifyUtils.OnClickListener clickListener = new LinkifyUtils.OnClickListener() {
904 public void onClick() {
905 final SettingsActivity activity = (SettingsActivity) getActivity();
906 activity.startPreferencePanel(WifiSettings.this,
907 ScanningSettings.class.getName(),
908 null, R.string.location_scanning_screen_title, null, null, 0);
911 mStatusMessagePreference.setText(title, description, clickListener);
912 removeConnectedAccessPointPreference();
913 mAccessPointsPreferenceCategory.removeAll();
914 mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference);
917 private void addMessagePreference(int messageId) {
918 mStatusMessagePreference.setTitle(messageId);
919 removeConnectedAccessPointPreference();
920 mAccessPointsPreferenceCategory.removeAll();
921 mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference);
924 protected void setProgressBarVisible(boolean visible) {
925 if (mProgressHeader != null) {
926 mProgressHeader.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
931 * Renames/replaces "Next" button when appropriate. "Next" button usually exists in
932 * Wifi setup screens, not in usual wifi settings screen.
934 * @param enabled true when the device is connected to a wifi network.
936 private void changeNextButtonState(boolean enabled) {
937 if (mEnableNextOnConnection && hasNextButton()) {
938 getNextButton().setEnabled(enabled);
943 public void onForget(WifiDialog dialog) {
948 public void onSubmit(WifiDialog dialog) {
949 if (mDialog != null) {
950 submit(mDialog.getController());
954 /* package */ void submit(WifiConfigController configController) {
956 final WifiConfiguration config = configController.getConfig();
958 if (config == null) {
959 if (mSelectedAccessPoint != null
960 && mSelectedAccessPoint.isSaved()) {
961 connect(mSelectedAccessPoint.getConfig(), true /* isSavedNetwork */);
963 } else if (configController.getMode() == WifiConfigUiBase.MODE_MODIFY) {
964 mWifiManager.save(config, mSaveListener);
966 mWifiManager.save(config, mSaveListener);
967 if (mSelectedAccessPoint != null) { // Not an "Add network"
968 connect(config, false /* isSavedNetwork */);
972 mWifiTracker.resumeScanning();
975 /* package */ void forget() {
976 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_FORGET);
977 if (!mSelectedAccessPoint.isSaved()) {
978 if (mSelectedAccessPoint.getNetworkInfo() != null &&
979 mSelectedAccessPoint.getNetworkInfo().getState() != State.DISCONNECTED) {
980 // Network is active but has no network ID - must be ephemeral.
981 mWifiManager.disableEphemeralNetwork(
982 AccessPoint.convertToQuotedString(mSelectedAccessPoint.getSsidStr()));
984 // Should not happen, but a monkey seems to trigger it
985 Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig());
988 } else if (mSelectedAccessPoint.getConfig().isPasspoint()) {
989 mWifiManager.removePasspointConfiguration(mSelectedAccessPoint.getConfig().FQDN);
991 mWifiManager.forget(mSelectedAccessPoint.getConfig().networkId, mForgetListener);
994 mWifiTracker.resumeScanning();
996 // We need to rename/replace "Next" button in wifi setup context.
997 changeNextButtonState(false);
1000 protected void connect(final WifiConfiguration config, boolean isSavedNetwork) {
1001 // Log subtype if configuration is a saved network.
1002 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT,
1004 mWifiManager.connect(config, mConnectListener);
1005 scrollToPreference(mConnectedAccessPointPreferenceCategory);
1008 protected void connect(final int networkId, boolean isSavedNetwork) {
1009 // Log subtype if configuration is a saved network.
1010 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT,
1012 mWifiManager.connect(networkId, mConnectListener);
1016 * Called when "add network" button is pressed.
1018 /* package */ void onAddNetworkPressed() {
1019 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_ADD_NETWORK);
1020 // No exact access point is selected.
1021 mSelectedAccessPoint = null;
1022 showDialog(null, WifiConfigUiBase.MODE_CONNECT);
1026 protected int getHelpResource() {
1027 return R.string.help_url_wifi;
1031 public void onAccessPointChanged(final AccessPoint accessPoint) {
1032 Log.d(TAG, "onAccessPointChanged (singular) callback initiated");
1033 View view = getView();
1035 view.post(new Runnable() {
1038 Object tag = accessPoint.getTag();
1040 ((LongPressAccessPointPreference) tag).refresh();
1048 public void onLevelChanged(AccessPoint accessPoint) {
1049 ((LongPressAccessPointPreference) accessPoint.getTag()).onLevelChanged();
1052 public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
1053 new BaseSearchIndexProvider() {
1055 public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) {
1056 final List<SearchIndexableRaw> result = new ArrayList<>();
1057 final Resources res = context.getResources();
1059 // Add fragment title
1060 SearchIndexableRaw data = new SearchIndexableRaw(context);
1061 data.title = res.getString(R.string.wifi_settings);
1062 data.screenTitle = res.getString(R.string.wifi_settings);
1063 data.keywords = res.getString(R.string.keywords_wifi);
1064 data.key = DATA_KEY_REFERENCE;
1067 // Add saved Wi-Fi access points
1068 final List<AccessPoint> accessPoints =
1069 WifiTracker.getCurrentAccessPoints(context, true, false, false);
1070 for (AccessPoint accessPoint : accessPoints) {
1071 data = new SearchIndexableRaw(context);
1072 data.title = accessPoint.getSsidStr();
1073 data.screenTitle = res.getString(R.string.wifi_settings);
1074 data.enabled = enabled;
1083 * Returns true if the config is not editable through Settings.
1084 * @param context Context of caller
1085 * @param config The WiFi config.
1086 * @return true if the config is not editable through Settings.
1088 static boolean isEditabilityLockedDown(Context context, WifiConfiguration config) {
1089 return !canModifyNetwork(context, config);
1093 * This method is a stripped version of WifiConfigStore.canModifyNetwork.
1094 * TODO: refactor to have only one method.
1095 * @param context Context of caller
1096 * @param config The WiFi config.
1097 * @return true if Settings can modify the config.
1099 static boolean canModifyNetwork(Context context, WifiConfiguration config) {
1100 if (config == null) {
1104 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
1105 Context.DEVICE_POLICY_SERVICE);
1107 // Check if device has DPM capability. If it has and dpm is still null, then we
1108 // treat this case with suspicion and bail out.
1109 final PackageManager pm = context.getPackageManager();
1110 if (pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN) && dpm == null) {
1114 boolean isConfigEligibleForLockdown = false;
1116 final ComponentName deviceOwner = dpm.getDeviceOwnerComponentOnAnyUser();
1117 if (deviceOwner != null) {
1118 final int deviceOwnerUserId = dpm.getDeviceOwnerUserId();
1120 final int deviceOwnerUid = pm.getPackageUidAsUser(deviceOwner.getPackageName(),
1122 isConfigEligibleForLockdown = deviceOwnerUid == config.creatorUid;
1123 } catch (NameNotFoundException e) {
1128 if (!isConfigEligibleForLockdown) {
1132 final ContentResolver resolver = context.getContentResolver();
1133 final boolean isLockdownFeatureEnabled = Settings.Global.getInt(resolver,
1134 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) != 0;
1135 return !isLockdownFeatureEnabled;
1138 private static class SummaryProvider
1139 implements SummaryLoader.SummaryProvider, OnSummaryChangeListener {
1141 private final Context mContext;
1142 private final SummaryLoader mSummaryLoader;
1145 WifiSummaryUpdater mSummaryHelper;
1147 public SummaryProvider(Context context, SummaryLoader summaryLoader) {
1149 mSummaryLoader = summaryLoader;
1150 mSummaryHelper = new WifiSummaryUpdater(mContext, this);
1155 public void setListening(boolean listening) {
1156 mSummaryHelper.register(listening);
1160 public void onSummaryChanged(String summary) {
1161 mSummaryLoader.setSummary(this, summary);
1165 public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY
1166 = new SummaryLoader.SummaryProviderFactory() {
1168 public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity,
1169 SummaryLoader summaryLoader) {
1170 return new SummaryProvider(activity, summaryLoader);