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.Toast;
54 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
55 import com.android.settings.LinkifyUtils;
56 import com.android.settings.R;
57 import com.android.settings.RestrictedSettingsFragment;
58 import com.android.settings.SettingsActivity;
59 import com.android.settings.dashboard.SummaryLoader;
60 import com.android.settings.location.ScanningSettings;
61 import com.android.settings.search.BaseSearchIndexProvider;
62 import com.android.settings.search.Indexable;
63 import com.android.settings.search.SearchIndexableRaw;
64 import com.android.settings.widget.SummaryUpdater.OnSummaryChangeListener;
65 import com.android.settings.widget.SwitchBarController;
66 import com.android.settings.wifi.details.WifiNetworkDetailsFragment;
67 import com.android.settingslib.RestrictedLockUtils;
68 import com.android.settingslib.wifi.AccessPoint;
69 import com.android.settingslib.wifi.AccessPoint.AccessPointListener;
70 import com.android.settingslib.wifi.AccessPointPreference;
71 import com.android.settingslib.wifi.WifiTracker;
72 import com.android.settingslib.wifi.WifiTrackerFactory;
74 import java.util.ArrayList;
75 import java.util.List;
78 * Two types of UI are provided here.
80 * The first is for "usual Settings", appearing as any other Setup fragment.
82 * The second is for Setup Wizard, with a simplified interface that hides the action bar
85 public class WifiSettings extends RestrictedSettingsFragment
86 implements Indexable, WifiTracker.WifiListener, AccessPointListener,
87 WifiDialog.WifiDialogListener {
89 private static final String TAG = "WifiSettings";
90 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
92 /* package */ static final int MENU_ID_WPS_PBC = Menu.FIRST;
93 private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1;
94 private static final int MENU_ID_CONNECT = Menu.FIRST + 6;
95 private static final int MENU_ID_FORGET = Menu.FIRST + 7;
96 private static final int MENU_ID_MODIFY = Menu.FIRST + 8;
97 private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9;
99 public static final int WIFI_DIALOG_ID = 1;
100 /* package */ static final int WPS_PBC_DIALOG_ID = 2;
101 private static final int WPS_PIN_DIALOG_ID = 3;
102 private static final int WRITE_NFC_DIALOG_ID = 6;
104 // Instance state keys
105 private static final String SAVE_DIALOG_MODE = "dialog_mode";
106 private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state";
107 private static final String SAVED_WIFI_NFC_DIALOG_STATE = "wifi_nfc_dlg_state";
109 private static final String PREF_KEY_EMPTY_WIFI_LIST = "wifi_empty_list";
110 private static final String PREF_KEY_CONNECTED_ACCESS_POINTS = "connected_access_point";
111 private static final String PREF_KEY_ACCESS_POINTS = "access_points";
112 private static final String PREF_KEY_ADDITIONAL_SETTINGS = "additional_settings";
113 private static final String PREF_KEY_CONFIGURE_WIFI_SETTINGS = "configure_settings";
114 private static final String PREF_KEY_SAVED_NETWORKS = "saved_networks";
116 private final Runnable mUpdateAccessPointsRunnable = () -> {
117 updateAccessPointPreferences();
119 private final Runnable mHideProgressBarRunnable = () -> {
120 setProgressBarVisible(false);
123 protected WifiManager mWifiManager;
124 private WifiManager.ActionListener mConnectListener;
125 private WifiManager.ActionListener mSaveListener;
126 private WifiManager.ActionListener mForgetListener;
129 * The state of {@link #isUiRestricted()} at {@link #onCreate(Bundle)}}. This is neccesary to
130 * ensure that behavior is consistent if {@link #isUiRestricted()} changes. It could be changed
131 * by the Test DPC tool in AFW mode.
133 private boolean mIsRestricted;
135 private WifiEnabler mWifiEnabler;
136 // An access point being editted is stored here.
137 private AccessPoint mSelectedAccessPoint;
139 private WifiDialog mDialog;
140 private WriteWifiConfigToNfcDialog mWifiToNfcDialog;
142 private View mProgressHeader;
144 // this boolean extra specifies whether to disable the Next button when not connected. Used by
145 // account creation outside of setup wizard.
146 private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
147 // This string extra specifies a network to open the connect dialog on, so the user can enter
148 // network credentials. This is used by quick settings for secured networks, among other
150 public 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 = setPinnedHeaderView(R.layout.wifi_progress_header)
191 .findViewById(R.id.progress_bar_animation);
192 setProgressBarVisible(false);
197 public void onCreate(Bundle icicle) {
198 super.onCreate(icicle);
200 // TODO(b/37429702): Add animations and preference comparator back after initial screen is
202 setAnimationAllowed(false);
206 mIsRestricted = isUiRestricted();
208 mBgThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
212 private void addPreferences() {
213 addPreferencesFromResource(R.xml.wifi_settings);
215 mConnectedAccessPointPreferenceCategory =
216 (PreferenceCategory) findPreference(PREF_KEY_CONNECTED_ACCESS_POINTS);
217 mAccessPointsPreferenceCategory =
218 (PreferenceCategory) findPreference(PREF_KEY_ACCESS_POINTS);
219 mAdditionalSettingsPreferenceCategory =
220 (PreferenceCategory) findPreference(PREF_KEY_ADDITIONAL_SETTINGS);
221 mConfigureWifiSettingsPreference = findPreference(PREF_KEY_CONFIGURE_WIFI_SETTINGS);
222 mSavedNetworksPreference = findPreference(PREF_KEY_SAVED_NETWORKS);
224 Context prefContext = getPrefContext();
225 mAddPreference = new Preference(prefContext);
226 mAddPreference.setIcon(R.drawable.ic_menu_add_inset);
227 mAddPreference.setTitle(R.string.wifi_add_network);
228 mStatusMessagePreference = new LinkablePreference(prefContext);
230 mUserBadgeCache = new AccessPointPreference.UserBadgeCache(getPackageManager());
234 public void onDestroy() {
240 public void onActivityCreated(Bundle savedInstanceState) {
241 super.onActivityCreated(savedInstanceState);
243 mWifiTracker = WifiTrackerFactory.create(
244 getActivity(), this, mBgThread.getLooper(), true, true, false);
245 mWifiManager = mWifiTracker.getManager();
247 mConnectListener = new WifiManager.ActionListener() {
249 public void onSuccess() {
252 public void onFailure(int reason) {
253 Activity activity = getActivity();
254 if (activity != null) {
255 Toast.makeText(activity,
256 R.string.wifi_failed_connect_message,
257 Toast.LENGTH_SHORT).show();
262 mSaveListener = new WifiManager.ActionListener() {
264 public void onSuccess() {
267 public void onFailure(int reason) {
268 Activity activity = getActivity();
269 if (activity != null) {
270 Toast.makeText(activity,
271 R.string.wifi_failed_save_message,
272 Toast.LENGTH_SHORT).show();
277 mForgetListener = new WifiManager.ActionListener() {
279 public void onSuccess() {
282 public void onFailure(int reason) {
283 Activity activity = getActivity();
284 if (activity != null) {
285 Toast.makeText(activity,
286 R.string.wifi_failed_forget_message,
287 Toast.LENGTH_SHORT).show();
292 if (savedInstanceState != null) {
293 mDialogMode = savedInstanceState.getInt(SAVE_DIALOG_MODE);
294 if (savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) {
295 mAccessPointSavedState =
296 savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
299 if (savedInstanceState.containsKey(SAVED_WIFI_NFC_DIALOG_STATE)) {
300 mWifiNfcDialogSavedState =
301 savedInstanceState.getBundle(SAVED_WIFI_NFC_DIALOG_STATE);
305 // if we're supposed to enable/disable the Next button based on our current connection
306 // state, start it off in the right state
307 Intent intent = getActivity().getIntent();
308 mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
310 if (mEnableNextOnConnection) {
311 if (hasNextButton()) {
312 final ConnectivityManager connectivity = (ConnectivityManager)
313 getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
314 if (connectivity != null) {
315 NetworkInfo info = connectivity.getNetworkInfo(
316 ConnectivityManager.TYPE_WIFI);
317 changeNextButtonState(info.isConnected());
322 registerForContextMenu(getListView());
323 setHasOptionsMenu(true);
325 if (intent.hasExtra(EXTRA_START_CONNECT_SSID)) {
326 mOpenSsid = intent.getStringExtra(EXTRA_START_CONNECT_SSID);
331 public void onDestroyView() {
332 super.onDestroyView();
334 if (mWifiEnabler != null) {
335 mWifiEnabler.teardownSwitchController();
340 public void onStart() {
343 // On/off switch is hidden for Setup Wizard (returns null)
344 mWifiEnabler = createWifiEnabler();
346 mWifiTracker.startTracking();
353 onWifiStateChanged(mWifiManager.getWifiState());
356 private void restrictUi() {
357 if (!isUiRestrictedByOnlyAdmin()) {
358 getEmptyTextView().setText(R.string.wifi_empty_list_user_restricted);
360 getPreferenceScreen().removeAll();
364 * Only update the AP list if there are not any APs currently shown.
366 * <p>Thus forceUpdate will only be called during cold start or when toggling between wifi on
367 * and off. In other use cases, the previous APs will remain until the next update is received
368 * from {@link WifiTracker}.
370 private void conditionallyForceUpdateAPs() {
371 if (mAccessPointsPreferenceCategory.getPreferenceCount() > 0
372 && mAccessPointsPreferenceCategory.getPreference(0) instanceof
373 AccessPointPreference) {
374 // Make sure we don't update due to callbacks initiated by sticky broadcasts in
376 Log.d(TAG, "Did not force update APs due to existing APs displayed");
377 getView().removeCallbacks(mUpdateAccessPointsRunnable);
380 setProgressBarVisible(true);
381 mWifiTracker.forceUpdate();
383 Log.d(TAG, "WifiSettings force update APs: " + mWifiTracker.getAccessPoints());
385 getView().removeCallbacks(mUpdateAccessPointsRunnable);
386 updateAccessPointPreferences();
390 * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard)
392 private WifiEnabler createWifiEnabler() {
393 final SettingsActivity activity = (SettingsActivity) getActivity();
394 return new WifiEnabler(activity, new SwitchBarController(activity.getSwitchBar()),
395 mMetricsFeatureProvider);
399 public void onResume() {
400 final Activity activity = getActivity();
403 // Because RestrictedSettingsFragment's onResume potentially requests authorization,
404 // which changes the restriction state, recalculate it.
405 final boolean alreadyImmutablyRestricted = mIsRestricted;
406 mIsRestricted = isUiRestricted();
407 if (!alreadyImmutablyRestricted && mIsRestricted) {
411 if (mWifiEnabler != null) {
412 mWifiEnabler.resume(activity);
417 public void onPause() {
419 if (mWifiEnabler != null) {
420 mWifiEnabler.pause();
425 public void onStop() {
426 mWifiTracker.stopTracking();
427 getView().removeCallbacks(mUpdateAccessPointsRunnable);
428 getView().removeCallbacks(mHideProgressBarRunnable);
433 public void onActivityResult(int requestCode, int resultCode, Intent data) {
434 super.onActivityResult(requestCode, resultCode, data);
436 final boolean formerlyRestricted = mIsRestricted;
437 mIsRestricted = isUiRestricted();
438 if (formerlyRestricted && !mIsRestricted
439 && getPreferenceScreen().getPreferenceCount() == 0) {
440 // De-restrict the ui
446 public int getMetricsCategory() {
447 return MetricsEvent.WIFI;
451 public void onSaveInstanceState(Bundle outState) {
452 super.onSaveInstanceState(outState);
454 // If the dialog is showing, save its state.
455 if (mDialog != null && mDialog.isShowing()) {
456 outState.putInt(SAVE_DIALOG_MODE, mDialogMode);
457 if (mDlgAccessPoint != null) {
458 mAccessPointSavedState = new Bundle();
459 mDlgAccessPoint.saveWifiState(mAccessPointSavedState);
460 outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState);
464 if (mWifiToNfcDialog != null && mWifiToNfcDialog.isShowing()) {
465 Bundle savedState = new Bundle();
466 mWifiToNfcDialog.saveState(savedState);
467 outState.putBundle(SAVED_WIFI_NFC_DIALOG_STATE, savedState);
472 public boolean onOptionsItemSelected(MenuItem item) {
473 // If the user is not allowed to configure wifi, do not handle menu selections.
478 switch (item.getItemId()) {
479 case MENU_ID_WPS_PBC:
480 showDialog(WPS_PBC_DIALOG_ID);
482 case MENU_ID_WPS_PIN:
483 showDialog(WPS_PIN_DIALOG_ID);
486 return super.onOptionsItemSelected(item);
490 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
491 Preference preference = (Preference) view.getTag();
493 if (preference instanceof LongPressAccessPointPreference) {
494 mSelectedAccessPoint =
495 ((LongPressAccessPointPreference) preference).getAccessPoint();
496 menu.setHeaderTitle(mSelectedAccessPoint.getSsid());
497 if (mSelectedAccessPoint.isConnectable()) {
498 menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect);
501 WifiConfiguration config = mSelectedAccessPoint.getConfig();
502 // Some configs are ineditable
503 if (isEditabilityLockedDown(getActivity(), config)) {
507 if (mSelectedAccessPoint.isSaved() || mSelectedAccessPoint.isEphemeral()) {
508 // Allow forgetting a network if either the network is saved or ephemerally
509 // connected. (In the latter case, "forget" blacklists the network so it won't
510 // be used again, ephemerally).
511 menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget);
513 if (mSelectedAccessPoint.isSaved()) {
514 menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify);
515 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
516 if (nfcAdapter != null && nfcAdapter.isEnabled() &&
517 mSelectedAccessPoint.getSecurity() != AccessPoint.SECURITY_NONE) {
518 // Only allow writing of NFC tags for password-protected networks.
519 menu.add(Menu.NONE, MENU_ID_WRITE_NFC, 0, R.string.wifi_menu_write_to_nfc);
526 public boolean onContextItemSelected(MenuItem item) {
527 if (mSelectedAccessPoint == null) {
528 return super.onContextItemSelected(item);
530 switch (item.getItemId()) {
531 case MENU_ID_CONNECT: {
532 boolean isSavedNetwork = mSelectedAccessPoint.isSaved();
533 if (isSavedNetwork) {
534 connect(mSelectedAccessPoint.getConfig(), isSavedNetwork);
535 } else if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE) {
536 /** Bypass dialog for unsecured networks */
537 mSelectedAccessPoint.generateOpenNetworkConfig();
538 connect(mSelectedAccessPoint.getConfig(), isSavedNetwork);
540 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT);
544 case MENU_ID_FORGET: {
548 case MENU_ID_MODIFY: {
549 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_MODIFY);
552 case MENU_ID_WRITE_NFC:
553 showDialog(WRITE_NFC_DIALOG_ID);
557 return super.onContextItemSelected(item);
561 public boolean onPreferenceTreeClick(Preference preference) {
562 // If the preference has a fragment set, open that
563 if (preference.getFragment() != null) {
564 preference.setOnPreferenceClickListener(null);
565 return super.onPreferenceTreeClick(preference);
568 if (preference instanceof LongPressAccessPointPreference) {
569 mSelectedAccessPoint = ((LongPressAccessPointPreference) preference).getAccessPoint();
570 if (mSelectedAccessPoint == null) {
573 if (mSelectedAccessPoint.isActive()) {
574 return super.onPreferenceTreeClick(preference);
577 * Bypass dialog and connect to unsecured networks, or previously connected saved
578 * networks, or Passpoint provided networks.
580 WifiConfiguration config = mSelectedAccessPoint.getConfig();
581 if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE) {
582 mSelectedAccessPoint.generateOpenNetworkConfig();
583 connect(mSelectedAccessPoint.getConfig(), mSelectedAccessPoint.isSaved());
584 } else if (mSelectedAccessPoint.isSaved() && config != null
585 && config.getNetworkSelectionStatus() != null
586 && config.getNetworkSelectionStatus().getHasEverConnected()) {
587 connect(config, true /* isSavedNetwork */);
588 } else if (mSelectedAccessPoint.isPasspoint()) {
589 // Access point provided by an installed Passpoint provider, connect using
590 // the associated config.
591 connect(config, true /* isSavedNetwork */);
593 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT);
595 } else if (preference == mAddPreference) {
596 onAddNetworkPressed();
598 return super.onPreferenceTreeClick(preference);
603 private void showDialog(AccessPoint accessPoint, int dialogMode) {
604 if (accessPoint != null) {
605 WifiConfiguration config = accessPoint.getConfig();
606 if (isEditabilityLockedDown(getActivity(), config) && accessPoint.isActive()) {
607 RestrictedLockUtils.sendShowAdminSupportDetailsIntent(getActivity(),
608 RestrictedLockUtils.getDeviceOwner(getActivity()));
613 if (mDialog != null) {
614 removeDialog(WIFI_DIALOG_ID);
618 // Save the access point and edit mode
619 mDlgAccessPoint = accessPoint;
620 mDialogMode = dialogMode;
622 showDialog(WIFI_DIALOG_ID);
626 public Dialog onCreateDialog(int dialogId) {
629 AccessPoint ap = mDlgAccessPoint; // For manual launch
630 if (ap == null) { // For re-launch from saved state
631 if (mAccessPointSavedState != null) {
632 ap = new AccessPoint(getActivity(), mAccessPointSavedState);
633 // For repeated orientation changes
634 mDlgAccessPoint = ap;
635 // Reset the saved access point data
636 mAccessPointSavedState = null;
639 // If it's null, fine, it's for Add Network
640 mSelectedAccessPoint = ap;
641 mDialog = new WifiDialog(getActivity(), this, ap, mDialogMode,
642 /* no hide submit/connect */ false);
644 case WPS_PBC_DIALOG_ID:
645 return new WpsDialog(getActivity(), WpsInfo.PBC);
646 case WPS_PIN_DIALOG_ID:
647 return new WpsDialog(getActivity(), WpsInfo.DISPLAY);
648 case WRITE_NFC_DIALOG_ID:
649 if (mSelectedAccessPoint != null) {
650 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(
652 mSelectedAccessPoint.getSecurity(),
653 new WifiManagerWrapper(mWifiManager));
654 } else if (mWifiNfcDialogSavedState != null) {
655 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(getActivity(),
656 mWifiNfcDialogSavedState, new WifiManagerWrapper(mWifiManager));
659 return mWifiToNfcDialog;
661 return super.onCreateDialog(dialogId);
665 public int getDialogMetricsCategory(int dialogId) {
668 return MetricsEvent.DIALOG_WIFI_AP_EDIT;
669 case WPS_PBC_DIALOG_ID:
670 return MetricsEvent.DIALOG_WIFI_PBC;
671 case WPS_PIN_DIALOG_ID:
672 return MetricsEvent.DIALOG_WIFI_PIN;
673 case WRITE_NFC_DIALOG_ID:
674 return MetricsEvent.DIALOG_WIFI_WRITE_NFC;
681 * Called to indicate the list of AccessPoints has been updated and
682 * getAccessPoints should be called to get the latest information.
685 public void onAccessPointsChanged() {
686 Log.d(TAG, "onAccessPointsChanged (WifiTracker) callback initiated");
687 updateAccessPointsDelayed();
691 * Updates access points from {@link WifiManager#getScanResults()}. Adds a delay to have
692 * progress bar displayed before starting to modify APs.
694 private void updateAccessPointsDelayed() {
695 // Safeguard from some delayed event handling
696 if (getActivity() != null && !mIsRestricted && mWifiManager.isWifiEnabled()) {
697 setProgressBarVisible(true);
698 getView().postDelayed(mUpdateAccessPointsRunnable, 300 /* delay milliseconds */);
702 /** Called when the state of Wifi has changed. */
704 public void onWifiStateChanged(int state) {
709 final int wifiState = mWifiManager.getWifiState();
711 case WifiManager.WIFI_STATE_ENABLED:
712 conditionallyForceUpdateAPs();
715 case WifiManager.WIFI_STATE_ENABLING:
716 removeConnectedAccessPointPreference();
717 mAccessPointsPreferenceCategory.removeAll();
718 addMessagePreference(R.string.wifi_starting);
719 setProgressBarVisible(true);
722 case WifiManager.WIFI_STATE_DISABLING:
723 removeConnectedAccessPointPreference();
724 mAccessPointsPreferenceCategory.removeAll();
725 addMessagePreference(R.string.wifi_stopping);
728 case WifiManager.WIFI_STATE_DISABLED:
730 setAdditionalSettingsSummaries();
731 setProgressBarVisible(false);
737 * Called when the connection state of wifi has changed and isConnected
738 * should be called to get the updated state.
741 public void onConnectedChanged() {
742 updateAccessPointsDelayed();
743 changeNextButtonState(mWifiTracker.isConnected());
746 /** Helper method to return whether an AccessPoint is disabled due to a wrong password */
747 private static boolean isDisabledByWrongPassword(AccessPoint accessPoint) {
748 WifiConfiguration config = accessPoint.getConfig();
749 if (config == null) {
752 WifiConfiguration.NetworkSelectionStatus networkStatus =
753 config.getNetworkSelectionStatus();
754 if (networkStatus == null || networkStatus.isNetworkEnabled()) {
757 int reason = networkStatus.getNetworkSelectionDisableReason();
758 return WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD == reason;
761 private void updateAccessPointPreferences() {
762 // in case state has changed
763 if (!mWifiManager.isWifiEnabled()) {
766 // AccessPoints are sorted by the WifiTracker
767 final List<AccessPoint> accessPoints = mWifiTracker.getAccessPoints();
769 Log.d(TAG, "updateAccessPoints called for: " + accessPoints);
772 boolean hasAvailableAccessPoints = false;
773 mAccessPointsPreferenceCategory.removePreference(mStatusMessagePreference);
774 cacheRemoveAllPrefs(mAccessPointsPreferenceCategory);
777 configureConnectedAccessPointPreferenceCategory(accessPoints) ? 1 : 0;
778 int numAccessPoints = accessPoints.size();
779 for (; index < numAccessPoints; index++) {
780 AccessPoint accessPoint = accessPoints.get(index);
781 // Ignore access points that are out of range.
782 if (accessPoint.isReachable()) {
783 String key = AccessPointPreference.generatePreferenceKey(accessPoint);
784 hasAvailableAccessPoints = true;
785 LongPressAccessPointPreference pref =
786 (LongPressAccessPointPreference) getCachedPreference(key);
788 pref.setOrder(index);
791 LongPressAccessPointPreference preference =
792 createLongPressActionPointPreference(accessPoint);
793 preference.setKey(key);
794 preference.setOrder(index);
795 if (mOpenSsid != null && mOpenSsid.equals(accessPoint.getSsidStr())
796 && accessPoint.getSecurity() != AccessPoint.SECURITY_NONE) {
797 if (!accessPoint.isSaved() || isDisabledByWrongPassword(accessPoint)) {
798 onPreferenceTreeClick(preference);
802 mAccessPointsPreferenceCategory.addPreference(preference);
803 accessPoint.setListener(WifiSettings.this);
804 preference.refresh();
807 removeCachedPrefs(mAccessPointsPreferenceCategory);
808 mAddPreference.setOrder(index);
809 mAccessPointsPreferenceCategory.addPreference(mAddPreference);
810 setAdditionalSettingsSummaries();
812 if (!hasAvailableAccessPoints) {
813 setProgressBarVisible(true);
814 Preference pref = new Preference(getPrefContext());
815 pref.setSelectable(false);
816 pref.setSummary(R.string.wifi_empty_list_wifi_on);
817 pref.setOrder(index++);
818 pref.setKey(PREF_KEY_EMPTY_WIFI_LIST);
819 mAccessPointsPreferenceCategory.addPreference(pref);
821 // Continuing showing progress bar for an additional delay to overlap with animation
822 getView().postDelayed(mHideProgressBarRunnable, 1700 /* delay millis */);
827 private LongPressAccessPointPreference createLongPressActionPointPreference(
828 AccessPoint accessPoint) {
829 return new LongPressAccessPointPreference(accessPoint, getPrefContext(), mUserBadgeCache,
830 false, R.drawable.ic_wifi_signal_0, this);
834 * Configure the ConnectedAccessPointPreferenceCategory and return true if the Category was
837 private boolean configureConnectedAccessPointPreferenceCategory(
838 List<AccessPoint> accessPoints) {
839 if (accessPoints.size() == 0) {
840 removeConnectedAccessPointPreference();
844 AccessPoint connectedAp = accessPoints.get(0);
845 if (!connectedAp.isActive()) {
846 removeConnectedAccessPointPreference();
850 // Is the preference category empty?
851 if (mConnectedAccessPointPreferenceCategory.getPreferenceCount() == 0) {
852 addConnectedAccessPointPreference(connectedAp);
856 // Is the previous currently connected SSID different from the new one?
857 if (!((AccessPointPreference)
858 mConnectedAccessPointPreferenceCategory.getPreference(0))
859 .getAccessPoint().getSsidStr().equals(
860 connectedAp.getSsidStr())) {
861 removeConnectedAccessPointPreference();
862 addConnectedAccessPointPreference(connectedAp);
866 // Else same AP is connected, simply refresh the connected access point preference
867 // (first and only access point in this category).
868 ((LongPressAccessPointPreference) mConnectedAccessPointPreferenceCategory.getPreference(0))
874 * Creates a Preference for the given {@link AccessPoint} and adds it to the
875 * {@link #mConnectedAccessPointPreferenceCategory}.
877 private void addConnectedAccessPointPreference(AccessPoint connectedAp) {
878 String key = connectedAp.getBssid();
879 LongPressAccessPointPreference pref = (LongPressAccessPointPreference)
880 getCachedPreference(key);
882 pref = createLongPressActionPointPreference(connectedAp);
885 // Save the state of the current access point in the bundle so that we can restore it
886 // in the Wifi Network Details Fragment
887 pref.getAccessPoint().saveWifiState(pref.getExtras());
888 pref.setFragment(WifiNetworkDetailsFragment.class.getName());
891 mConnectedAccessPointPreferenceCategory.addPreference(pref);
892 mConnectedAccessPointPreferenceCategory.setVisible(true);
895 /** Removes all preferences and hide the {@link #mConnectedAccessPointPreferenceCategory}. */
896 private void removeConnectedAccessPointPreference() {
897 mConnectedAccessPointPreferenceCategory.removeAll();
898 mConnectedAccessPointPreferenceCategory.setVisible(false);
901 private void setAdditionalSettingsSummaries() {
902 mAdditionalSettingsPreferenceCategory.addPreference(mConfigureWifiSettingsPreference);
903 final int defaultWakeupAvailable = getResources().getInteger(
904 com.android.internal.R.integer.config_wifi_wakeup_available);
905 boolean wifiWakeupAvailable = Settings.Global.getInt(
906 getContentResolver(), Settings.Global.WIFI_WAKEUP_AVAILABLE, defaultWakeupAvailable)
908 if (wifiWakeupAvailable) {
909 boolean wifiWakeupEnabled = Settings.Global.getInt(
910 getContentResolver(), Settings.Global.WIFI_WAKEUP_ENABLED, 0) == 1;
911 mConfigureWifiSettingsPreference.setSummary(getString(wifiWakeupEnabled
912 ? R.string.wifi_configure_settings_preference_summary_wakeup_on
913 : R.string.wifi_configure_settings_preference_summary_wakeup_off));
915 int numSavedNetworks = mWifiTracker.getNumSavedNetworks();
916 if (numSavedNetworks > 0) {
917 mAdditionalSettingsPreferenceCategory.addPreference(mSavedNetworksPreference);
918 mSavedNetworksPreference.setSummary(
919 getResources().getQuantityString(R.plurals.wifi_saved_access_points_summary,
920 numSavedNetworks, numSavedNetworks));
922 mAdditionalSettingsPreferenceCategory.removePreference(mSavedNetworksPreference);
926 private void setOffMessage() {
927 final CharSequence title = getText(R.string.wifi_empty_list_wifi_off);
928 // Don't use WifiManager.isScanAlwaysAvailable() to check the Wi-Fi scanning mode. Instead,
929 // read the system settings directly. Because when the device is in Airplane mode, even if
930 // Wi-Fi scanning mode is on, WifiManager.isScanAlwaysAvailable() still returns "off".
931 final boolean wifiScanningMode = Settings.Global.getInt(getActivity().getContentResolver(),
932 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1;
933 final CharSequence description = wifiScanningMode ? getText(R.string.wifi_scan_notify_text)
934 : getText(R.string.wifi_scan_notify_text_scanning_off);
935 final LinkifyUtils.OnClickListener clickListener = new LinkifyUtils.OnClickListener() {
937 public void onClick() {
938 final SettingsActivity activity = (SettingsActivity) getActivity();
939 activity.startPreferencePanel(WifiSettings.this,
940 ScanningSettings.class.getName(),
941 null, R.string.location_scanning_screen_title, null, null, 0);
944 mStatusMessagePreference.setText(title, description, clickListener);
945 removeConnectedAccessPointPreference();
946 mAccessPointsPreferenceCategory.removeAll();
947 mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference);
950 private void addMessagePreference(int messageId) {
951 mStatusMessagePreference.setTitle(messageId);
952 removeConnectedAccessPointPreference();
953 mAccessPointsPreferenceCategory.removeAll();
954 mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference);
957 protected void setProgressBarVisible(boolean visible) {
958 if (mProgressHeader != null) {
959 mProgressHeader.setVisibility(visible ? View.VISIBLE : View.GONE);
964 * Renames/replaces "Next" button when appropriate. "Next" button usually exists in
965 * Wifi setup screens, not in usual wifi settings screen.
967 * @param enabled true when the device is connected to a wifi network.
969 private void changeNextButtonState(boolean enabled) {
970 if (mEnableNextOnConnection && hasNextButton()) {
971 getNextButton().setEnabled(enabled);
976 public void onForget(WifiDialog dialog) {
981 public void onSubmit(WifiDialog dialog) {
982 if (mDialog != null) {
983 submit(mDialog.getController());
987 /* package */ void submit(WifiConfigController configController) {
989 final WifiConfiguration config = configController.getConfig();
991 if (config == null) {
992 if (mSelectedAccessPoint != null
993 && mSelectedAccessPoint.isSaved()) {
994 connect(mSelectedAccessPoint.getConfig(), true /* isSavedNetwork */);
996 } else if (configController.getMode() == WifiConfigUiBase.MODE_MODIFY) {
997 mWifiManager.save(config, mSaveListener);
999 mWifiManager.save(config, mSaveListener);
1000 if (mSelectedAccessPoint != null) { // Not an "Add network"
1001 connect(config, false /* isSavedNetwork */);
1005 mWifiTracker.resumeScanning();
1008 /* package */ void forget() {
1009 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_FORGET);
1010 if (!mSelectedAccessPoint.isSaved()) {
1011 if (mSelectedAccessPoint.getNetworkInfo() != null &&
1012 mSelectedAccessPoint.getNetworkInfo().getState() != State.DISCONNECTED) {
1013 // Network is active but has no network ID - must be ephemeral.
1014 mWifiManager.disableEphemeralNetwork(
1015 AccessPoint.convertToQuotedString(mSelectedAccessPoint.getSsidStr()));
1017 // Should not happen, but a monkey seems to trigger it
1018 Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig());
1021 } else if (mSelectedAccessPoint.getConfig().isPasspoint()) {
1022 mWifiManager.removePasspointConfiguration(mSelectedAccessPoint.getConfig().FQDN);
1024 mWifiManager.forget(mSelectedAccessPoint.getConfig().networkId, mForgetListener);
1027 mWifiTracker.resumeScanning();
1029 // We need to rename/replace "Next" button in wifi setup context.
1030 changeNextButtonState(false);
1033 protected void connect(final WifiConfiguration config, boolean isSavedNetwork) {
1034 // Log subtype if configuration is a saved network.
1035 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT,
1037 mWifiManager.connect(config, mConnectListener);
1038 scrollToPreference(mConnectedAccessPointPreferenceCategory);
1041 protected void connect(final int networkId, boolean isSavedNetwork) {
1042 // Log subtype if configuration is a saved network.
1043 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT,
1045 mWifiManager.connect(networkId, mConnectListener);
1049 * Called when "add network" button is pressed.
1051 /* package */ void onAddNetworkPressed() {
1052 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_ADD_NETWORK);
1053 // No exact access point is selected.
1054 mSelectedAccessPoint = null;
1055 showDialog(null, WifiConfigUiBase.MODE_CONNECT);
1059 protected int getHelpResource() {
1060 return R.string.help_url_wifi;
1064 public void onAccessPointChanged(final AccessPoint accessPoint) {
1065 Log.d(TAG, "onAccessPointChanged (singular) callback initiated");
1066 View view = getView();
1068 view.post(new Runnable() {
1071 Object tag = accessPoint.getTag();
1073 ((LongPressAccessPointPreference) tag).refresh();
1081 public void onLevelChanged(AccessPoint accessPoint) {
1082 ((LongPressAccessPointPreference) accessPoint.getTag()).onLevelChanged();
1085 public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
1086 new BaseSearchIndexProvider() {
1088 public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) {
1089 final List<SearchIndexableRaw> result = new ArrayList<>();
1090 final Resources res = context.getResources();
1092 // Add fragment title
1093 SearchIndexableRaw data = new SearchIndexableRaw(context);
1094 data.title = res.getString(R.string.wifi_settings);
1095 data.screenTitle = res.getString(R.string.wifi_settings);
1096 data.keywords = res.getString(R.string.keywords_wifi);
1097 data.key = DATA_KEY_REFERENCE;
1100 // Add saved Wi-Fi access points
1101 final List<AccessPoint> accessPoints =
1102 WifiTracker.getCurrentAccessPoints(context, true, false, false);
1103 for (AccessPoint accessPoint : accessPoints) {
1104 data = new SearchIndexableRaw(context);
1105 data.title = accessPoint.getSsidStr();
1106 data.screenTitle = res.getString(R.string.wifi_settings);
1107 data.enabled = enabled;
1116 * Returns true if the config is not editable through Settings.
1117 * @param context Context of caller
1118 * @param config The WiFi config.
1119 * @return true if the config is not editable through Settings.
1121 static boolean isEditabilityLockedDown(Context context, WifiConfiguration config) {
1122 return !canModifyNetwork(context, config);
1126 * This method is a stripped version of WifiConfigStore.canModifyNetwork.
1127 * TODO: refactor to have only one method.
1128 * @param context Context of caller
1129 * @param config The WiFi config.
1130 * @return true if Settings can modify the config.
1132 static boolean canModifyNetwork(Context context, WifiConfiguration config) {
1133 if (config == null) {
1137 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
1138 Context.DEVICE_POLICY_SERVICE);
1140 // Check if device has DPM capability. If it has and dpm is still null, then we
1141 // treat this case with suspicion and bail out.
1142 final PackageManager pm = context.getPackageManager();
1143 if (pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN) && dpm == null) {
1147 boolean isConfigEligibleForLockdown = false;
1149 final ComponentName deviceOwner = dpm.getDeviceOwnerComponentOnAnyUser();
1150 if (deviceOwner != null) {
1151 final int deviceOwnerUserId = dpm.getDeviceOwnerUserId();
1153 final int deviceOwnerUid = pm.getPackageUidAsUser(deviceOwner.getPackageName(),
1155 isConfigEligibleForLockdown = deviceOwnerUid == config.creatorUid;
1156 } catch (NameNotFoundException e) {
1161 if (!isConfigEligibleForLockdown) {
1165 final ContentResolver resolver = context.getContentResolver();
1166 final boolean isLockdownFeatureEnabled = Settings.Global.getInt(resolver,
1167 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) != 0;
1168 return !isLockdownFeatureEnabled;
1171 private static class SummaryProvider
1172 implements SummaryLoader.SummaryProvider, OnSummaryChangeListener {
1174 private final Context mContext;
1175 private final SummaryLoader mSummaryLoader;
1178 WifiSummaryUpdater mSummaryHelper;
1180 public SummaryProvider(Context context, SummaryLoader summaryLoader) {
1182 mSummaryLoader = summaryLoader;
1183 mSummaryHelper = new WifiSummaryUpdater(mContext, this);
1188 public void setListening(boolean listening) {
1189 mSummaryHelper.register(listening);
1193 public void onSummaryChanged(String summary) {
1194 mSummaryLoader.setSummary(this, summary);
1198 public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY
1199 = new SummaryLoader.SummaryProviderFactory() {
1201 public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity,
1202 SummaryLoader summaryLoader) {
1203 return new SummaryProvider(activity, summaryLoader);