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.text.TextUtils;
47 import android.util.Log;
48 import android.view.ContextMenu;
49 import android.view.ContextMenu.ContextMenuInfo;
50 import android.view.Menu;
51 import android.view.MenuItem;
52 import android.view.View;
53 import android.widget.ProgressBar;
54 import android.widget.Toast;
56 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
57 import com.android.settings.LinkifyUtils;
58 import com.android.settings.R;
59 import com.android.settings.RestrictedSettingsFragment;
60 import com.android.settings.SettingsActivity;
61 import com.android.settings.dashboard.SummaryLoader;
62 import com.android.settings.location.ScanningSettings;
63 import com.android.settings.search.BaseSearchIndexProvider;
64 import com.android.settings.search.Indexable;
65 import com.android.settings.search.SearchIndexableRaw;
66 import com.android.settings.widget.SummaryUpdater.OnSummaryChangeListener;
67 import com.android.settings.widget.SwitchBarController;
68 import com.android.settings.wifi.details.WifiNetworkDetailsFragment;
69 import com.android.settingslib.RestrictedLockUtils;
70 import com.android.settingslib.wifi.AccessPoint;
71 import com.android.settingslib.wifi.AccessPoint.AccessPointListener;
72 import com.android.settingslib.wifi.AccessPointPreference;
73 import com.android.settingslib.wifi.WifiTracker;
74 import com.android.settingslib.wifi.WifiTrackerFactory;
76 import java.util.ArrayList;
77 import java.util.List;
80 * Two types of UI are provided here.
82 * The first is for "usual Settings", appearing as any other Setup fragment.
84 * The second is for Setup Wizard, with a simplified interface that hides the action bar
87 public class WifiSettings extends RestrictedSettingsFragment
88 implements Indexable, WifiTracker.WifiListener, AccessPointListener,
89 WifiDialog.WifiDialogListener {
91 private static final String TAG = "WifiSettings";
92 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
94 /* package */ static final int MENU_ID_WPS_PBC = Menu.FIRST;
95 private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1;
96 private static final int MENU_ID_CONNECT = Menu.FIRST + 6;
97 private static final int MENU_ID_FORGET = Menu.FIRST + 7;
98 private static final int MENU_ID_MODIFY = Menu.FIRST + 8;
99 private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9;
101 public static final int WIFI_DIALOG_ID = 1;
102 /* package */ static final int WPS_PBC_DIALOG_ID = 2;
103 private static final int WPS_PIN_DIALOG_ID = 3;
104 private static final int WRITE_NFC_DIALOG_ID = 6;
106 // Instance state keys
107 private static final String SAVE_DIALOG_MODE = "dialog_mode";
108 private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state";
109 private static final String SAVED_WIFI_NFC_DIALOG_STATE = "wifi_nfc_dlg_state";
111 private static final String PREF_KEY_EMPTY_WIFI_LIST = "wifi_empty_list";
112 private static final String PREF_KEY_CONNECTED_ACCESS_POINTS = "connected_access_point";
113 private static final String PREF_KEY_ACCESS_POINTS = "access_points";
114 private static final String PREF_KEY_ADDITIONAL_SETTINGS = "additional_settings";
115 private static final String PREF_KEY_CONFIGURE_WIFI_SETTINGS = "configure_settings";
116 private static final String PREF_KEY_SAVED_NETWORKS = "saved_networks";
118 private final Runnable mUpdateAccessPointsRunnable = () -> {
119 updateAccessPointPreferences();
121 private final Runnable mHideProgressBarRunnable = () -> {
122 setProgressBarVisible(false);
125 protected WifiManager mWifiManager;
126 private WifiManager.ActionListener mConnectListener;
127 private WifiManager.ActionListener mSaveListener;
128 private WifiManager.ActionListener mForgetListener;
131 * The state of {@link #isUiRestricted()} at {@link #onCreate(Bundle)}}. This is neccesary to
132 * ensure that behavior is consistent if {@link #isUiRestricted()} changes. It could be changed
133 * by the Test DPC tool in AFW mode.
135 private boolean mIsRestricted;
137 private WifiEnabler mWifiEnabler;
138 // An access point being editted is stored here.
139 private AccessPoint mSelectedAccessPoint;
141 private WifiDialog mDialog;
142 private WriteWifiConfigToNfcDialog mWifiToNfcDialog;
144 private ProgressBar mProgressHeader;
146 // this boolean extra specifies whether to disable the Next button when not connected. Used by
147 // account creation outside of setup wizard.
148 private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
149 // This string extra specifies a network to open the connect dialog on, so the user can enter
150 // network credentials. This is used by quick settings for secured networks.
151 private static final String EXTRA_START_CONNECT_SSID = "wifi_start_connect_ssid";
153 // should Next button only be enabled when we have a connection?
154 private boolean mEnableNextOnConnection;
156 // Save the dialog details
157 private int mDialogMode;
158 private AccessPoint mDlgAccessPoint;
159 private Bundle mAccessPointSavedState;
160 private Bundle mWifiNfcDialogSavedState;
162 private WifiTracker mWifiTracker;
163 private String mOpenSsid;
165 private HandlerThread mBgThread;
167 private AccessPointPreference.UserBadgeCache mUserBadgeCache;
169 private PreferenceCategory mConnectedAccessPointPreferenceCategory;
170 private PreferenceCategory mAccessPointsPreferenceCategory;
171 private PreferenceCategory mAdditionalSettingsPreferenceCategory;
172 private Preference mAddPreference;
173 private Preference mConfigureWifiSettingsPreference;
174 private Preference mSavedNetworksPreference;
175 private LinkablePreference mStatusMessagePreference;
178 private static final String DATA_KEY_REFERENCE = "main_toggle_wifi";
180 /* End of "used in Wifi Setup context" */
182 public WifiSettings() {
183 super(DISALLOW_CONFIG_WIFI);
187 public void onViewCreated(View view, Bundle savedInstanceState) {
188 super.onViewCreated(view, savedInstanceState);
189 final Activity activity = getActivity();
190 if (activity != null) {
191 mProgressHeader = (ProgressBar) setPinnedHeaderView(R.layout.wifi_progress_header);
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);
204 addPreferencesFromResource(R.xml.wifi_settings);
206 mConnectedAccessPointPreferenceCategory =
207 (PreferenceCategory) findPreference(PREF_KEY_CONNECTED_ACCESS_POINTS);
208 mAccessPointsPreferenceCategory =
209 (PreferenceCategory) findPreference(PREF_KEY_ACCESS_POINTS);
210 mAdditionalSettingsPreferenceCategory =
211 (PreferenceCategory) findPreference(PREF_KEY_ADDITIONAL_SETTINGS);
212 mConfigureWifiSettingsPreference = findPreference(PREF_KEY_CONFIGURE_WIFI_SETTINGS);
213 mSavedNetworksPreference = findPreference(PREF_KEY_SAVED_NETWORKS);
215 Context prefContext = getPrefContext();
216 mAddPreference = new Preference(prefContext);
217 mAddPreference.setIcon(R.drawable.ic_menu_add_inset);
218 mAddPreference.setTitle(R.string.wifi_add_network);
219 mStatusMessagePreference = new LinkablePreference(prefContext);
221 mUserBadgeCache = new AccessPointPreference.UserBadgeCache(getPackageManager());
223 mIsRestricted = isUiRestricted();
225 mBgThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
230 public void onDestroy() {
236 public void onActivityCreated(Bundle savedInstanceState) {
237 super.onActivityCreated(savedInstanceState);
239 mWifiTracker = WifiTrackerFactory.create(
240 getActivity(), this, mBgThread.getLooper(), true, true, false);
241 mWifiManager = mWifiTracker.getManager();
243 mConnectListener = new WifiManager.ActionListener() {
245 public void onSuccess() {
248 public void onFailure(int reason) {
249 Activity activity = getActivity();
250 if (activity != null) {
251 Toast.makeText(activity,
252 R.string.wifi_failed_connect_message,
253 Toast.LENGTH_SHORT).show();
258 mSaveListener = new WifiManager.ActionListener() {
260 public void onSuccess() {
263 public void onFailure(int reason) {
264 Activity activity = getActivity();
265 if (activity != null) {
266 Toast.makeText(activity,
267 R.string.wifi_failed_save_message,
268 Toast.LENGTH_SHORT).show();
273 mForgetListener = new WifiManager.ActionListener() {
275 public void onSuccess() {
278 public void onFailure(int reason) {
279 Activity activity = getActivity();
280 if (activity != null) {
281 Toast.makeText(activity,
282 R.string.wifi_failed_forget_message,
283 Toast.LENGTH_SHORT).show();
288 if (savedInstanceState != null) {
289 mDialogMode = savedInstanceState.getInt(SAVE_DIALOG_MODE);
290 if (savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) {
291 mAccessPointSavedState =
292 savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
295 if (savedInstanceState.containsKey(SAVED_WIFI_NFC_DIALOG_STATE)) {
296 mWifiNfcDialogSavedState =
297 savedInstanceState.getBundle(SAVED_WIFI_NFC_DIALOG_STATE);
301 // if we're supposed to enable/disable the Next button based on our current connection
302 // state, start it off in the right state
303 Intent intent = getActivity().getIntent();
304 mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
306 if (mEnableNextOnConnection) {
307 if (hasNextButton()) {
308 final ConnectivityManager connectivity = (ConnectivityManager)
309 getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
310 if (connectivity != null) {
311 NetworkInfo info = connectivity.getNetworkInfo(
312 ConnectivityManager.TYPE_WIFI);
313 changeNextButtonState(info.isConnected());
318 registerForContextMenu(getListView());
319 setHasOptionsMenu(true);
321 if (intent.hasExtra(EXTRA_START_CONNECT_SSID)) {
322 mOpenSsid = intent.getStringExtra(EXTRA_START_CONNECT_SSID);
327 public void onDestroyView() {
328 super.onDestroyView();
330 if (mWifiEnabler != null) {
331 mWifiEnabler.teardownSwitchController();
336 public void onStart() {
339 // On/off switch is hidden for Setup Wizard (returns null)
340 mWifiEnabler = createWifiEnabler();
342 mWifiTracker.startTracking();
345 if (!isUiRestrictedByOnlyAdmin()) {
346 getEmptyTextView().setText(R.string.wifi_empty_list_user_restricted);
348 getPreferenceScreen().removeAll();
352 onWifiStateChanged(mWifiManager.getWifiState());
356 * Only update the AP list if there are not any APs currently shown.
358 * <p>Thus forceUpdate will only be called during cold start or when toggling between wifi on
359 * and off. In other use cases, the previous APs will remain until the next update is received
360 * from {@link WifiTracker}.
362 private void conditionallyForceUpdateAPs() {
363 if (mAccessPointsPreferenceCategory.getPreferenceCount() > 0
364 && mAccessPointsPreferenceCategory.getPreference(0) instanceof
365 AccessPointPreference) {
366 // Make sure we don't update due to callbacks initiated by sticky broadcasts in
368 Log.d(TAG, "Did not force update APs due to existing APs displayed");
369 getView().removeCallbacks(mUpdateAccessPointsRunnable);
372 setProgressBarVisible(true);
373 mWifiTracker.forceUpdate();
375 Log.d(TAG, "WifiSettings force update APs: " + mWifiTracker.getAccessPoints());
377 getView().removeCallbacks(mUpdateAccessPointsRunnable);
378 updateAccessPointPreferences();
382 * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard)
384 private WifiEnabler createWifiEnabler() {
385 final SettingsActivity activity = (SettingsActivity) getActivity();
386 return new WifiEnabler(activity, new SwitchBarController(activity.getSwitchBar()),
387 mMetricsFeatureProvider);
391 public void onResume() {
392 final Activity activity = getActivity();
394 if (mWifiEnabler != null) {
395 mWifiEnabler.resume(activity);
400 public void onPause() {
402 if (mWifiEnabler != null) {
403 mWifiEnabler.pause();
408 public void onStop() {
409 mWifiTracker.stopTracking();
410 getView().removeCallbacks(mUpdateAccessPointsRunnable);
411 getView().removeCallbacks(mHideProgressBarRunnable);
416 public int getMetricsCategory() {
417 return MetricsEvent.WIFI;
421 public void onSaveInstanceState(Bundle outState) {
422 super.onSaveInstanceState(outState);
424 // If the dialog is showing, save its state.
425 if (mDialog != null && mDialog.isShowing()) {
426 outState.putInt(SAVE_DIALOG_MODE, mDialogMode);
427 if (mDlgAccessPoint != null) {
428 mAccessPointSavedState = new Bundle();
429 mDlgAccessPoint.saveWifiState(mAccessPointSavedState);
430 outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState);
434 if (mWifiToNfcDialog != null && mWifiToNfcDialog.isShowing()) {
435 Bundle savedState = new Bundle();
436 mWifiToNfcDialog.saveState(savedState);
437 outState.putBundle(SAVED_WIFI_NFC_DIALOG_STATE, savedState);
442 public boolean onOptionsItemSelected(MenuItem item) {
443 // If the user is not allowed to configure wifi, do not handle menu selections.
448 switch (item.getItemId()) {
449 case MENU_ID_WPS_PBC:
450 showDialog(WPS_PBC_DIALOG_ID);
452 case MENU_ID_WPS_PIN:
453 showDialog(WPS_PIN_DIALOG_ID);
456 return super.onOptionsItemSelected(item);
460 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
461 Preference preference = (Preference) view.getTag();
463 if (preference instanceof LongPressAccessPointPreference) {
464 mSelectedAccessPoint =
465 ((LongPressAccessPointPreference) preference).getAccessPoint();
466 menu.setHeaderTitle(mSelectedAccessPoint.getSsid());
467 if (mSelectedAccessPoint.isConnectable()) {
468 menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect);
471 WifiConfiguration config = mSelectedAccessPoint.getConfig();
472 // Some configs are ineditable
473 if (isEditabilityLockedDown(getActivity(), config)) {
477 if (mSelectedAccessPoint.isSaved() || mSelectedAccessPoint.isEphemeral()) {
478 // Allow forgetting a network if either the network is saved or ephemerally
479 // connected. (In the latter case, "forget" blacklists the network so it won't
480 // be used again, ephemerally).
481 menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget);
483 if (mSelectedAccessPoint.isSaved()) {
484 menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify);
485 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
486 if (nfcAdapter != null && nfcAdapter.isEnabled() &&
487 mSelectedAccessPoint.getSecurity() != AccessPoint.SECURITY_NONE) {
488 // Only allow writing of NFC tags for password-protected networks.
489 menu.add(Menu.NONE, MENU_ID_WRITE_NFC, 0, R.string.wifi_menu_write_to_nfc);
496 public boolean onContextItemSelected(MenuItem item) {
497 if (mSelectedAccessPoint == null) {
498 return super.onContextItemSelected(item);
500 switch (item.getItemId()) {
501 case MENU_ID_CONNECT: {
502 boolean isSavedNetwork = mSelectedAccessPoint.isSaved();
503 if (isSavedNetwork) {
504 connect(mSelectedAccessPoint.getConfig(), isSavedNetwork);
505 } else if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE) {
506 /** Bypass dialog for unsecured networks */
507 mSelectedAccessPoint.generateOpenNetworkConfig();
508 connect(mSelectedAccessPoint.getConfig(), isSavedNetwork);
510 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT);
514 case MENU_ID_FORGET: {
518 case MENU_ID_MODIFY: {
519 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_MODIFY);
522 case MENU_ID_WRITE_NFC:
523 showDialog(WRITE_NFC_DIALOG_ID);
527 return super.onContextItemSelected(item);
531 public boolean onPreferenceTreeClick(Preference preference) {
532 // If the preference has a fragment set, open that
533 if (preference.getFragment() != null) {
534 preference.setOnPreferenceClickListener(null);
535 return super.onPreferenceTreeClick(preference);
538 if (preference instanceof LongPressAccessPointPreference) {
539 mSelectedAccessPoint = ((LongPressAccessPointPreference) preference).getAccessPoint();
540 if (mSelectedAccessPoint == null) {
543 if (mSelectedAccessPoint.isActive()) {
544 return super.onPreferenceTreeClick(preference);
547 * Bypass dialog and connect to unsecured networks, or previously connected saved
548 * networks, or Passpoint provided networks.
550 WifiConfiguration config = mSelectedAccessPoint.getConfig();
551 if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE) {
552 mSelectedAccessPoint.generateOpenNetworkConfig();
553 connect(mSelectedAccessPoint.getConfig(), mSelectedAccessPoint.isSaved());
554 } else if (mSelectedAccessPoint.isSaved() && config != null
555 && config.getNetworkSelectionStatus() != null
556 && config.getNetworkSelectionStatus().getHasEverConnected()) {
557 connect(config, true /* isSavedNetwork */);
558 } else if (mSelectedAccessPoint.isPasspoint()) {
559 // Access point provided by an installed Passpoint provider, connect using
560 // the associated config.
561 connect(config, true /* isSavedNetwork */);
563 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT);
565 } else if (preference == mAddPreference) {
566 onAddNetworkPressed();
568 return super.onPreferenceTreeClick(preference);
573 private void showDialog(AccessPoint accessPoint, int dialogMode) {
574 if (accessPoint != null) {
575 WifiConfiguration config = accessPoint.getConfig();
576 if (isEditabilityLockedDown(getActivity(), config) && accessPoint.isActive()) {
577 RestrictedLockUtils.sendShowAdminSupportDetailsIntent(getActivity(),
578 RestrictedLockUtils.getDeviceOwner(getActivity()));
583 if (mDialog != null) {
584 removeDialog(WIFI_DIALOG_ID);
588 // Save the access point and edit mode
589 mDlgAccessPoint = accessPoint;
590 mDialogMode = dialogMode;
592 showDialog(WIFI_DIALOG_ID);
596 public Dialog onCreateDialog(int dialogId) {
599 AccessPoint ap = mDlgAccessPoint; // For manual launch
600 if (ap == null) { // For re-launch from saved state
601 if (mAccessPointSavedState != null) {
602 ap = new AccessPoint(getActivity(), mAccessPointSavedState);
603 // For repeated orientation changes
604 mDlgAccessPoint = ap;
605 // Reset the saved access point data
606 mAccessPointSavedState = null;
609 // If it's null, fine, it's for Add Network
610 mSelectedAccessPoint = ap;
611 mDialog = new WifiDialog(getActivity(), this, ap, mDialogMode,
612 /* no hide submit/connect */ false);
614 case WPS_PBC_DIALOG_ID:
615 return new WpsDialog(getActivity(), WpsInfo.PBC);
616 case WPS_PIN_DIALOG_ID:
617 return new WpsDialog(getActivity(), WpsInfo.DISPLAY);
618 case WRITE_NFC_DIALOG_ID:
619 if (mSelectedAccessPoint != null) {
620 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(
622 mSelectedAccessPoint.getSecurity(),
623 new WifiManagerWrapper(mWifiManager));
624 } else if (mWifiNfcDialogSavedState != null) {
625 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(getActivity(),
626 mWifiNfcDialogSavedState, new WifiManagerWrapper(mWifiManager));
629 return mWifiToNfcDialog;
631 return super.onCreateDialog(dialogId);
635 public int getDialogMetricsCategory(int dialogId) {
638 return MetricsEvent.DIALOG_WIFI_AP_EDIT;
639 case WPS_PBC_DIALOG_ID:
640 return MetricsEvent.DIALOG_WIFI_PBC;
641 case WPS_PIN_DIALOG_ID:
642 return MetricsEvent.DIALOG_WIFI_PIN;
643 case WRITE_NFC_DIALOG_ID:
644 return MetricsEvent.DIALOG_WIFI_WRITE_NFC;
651 * Called to indicate the list of AccessPoints has been updated and
652 * getAccessPoints should be called to get the latest information.
655 public void onAccessPointsChanged() {
656 Log.d(TAG, "onAccessPointsChanged (WifiTracker) callback initiated");
657 updateAccessPointsDelayed();
661 * Updates access points from {@link WifiManager#getScanResults()}. Adds a delay to have
662 * progress bar displayed before starting to modify APs.
664 private void updateAccessPointsDelayed() {
665 // Safeguard from some delayed event handling
666 if (getActivity() != null && !mIsRestricted && mWifiManager.isWifiEnabled()) {
667 setProgressBarVisible(true);
668 getView().postDelayed(mUpdateAccessPointsRunnable, 300 /* delay milliseconds */);
672 /** Called when the state of Wifi has changed. */
674 public void onWifiStateChanged(int state) {
679 final int wifiState = mWifiManager.getWifiState();
681 case WifiManager.WIFI_STATE_ENABLED:
682 conditionallyForceUpdateAPs();
685 case WifiManager.WIFI_STATE_ENABLING:
686 removeConnectedAccessPointPreference();
687 mAccessPointsPreferenceCategory.removeAll();
688 addMessagePreference(R.string.wifi_starting);
689 setProgressBarVisible(true);
692 case WifiManager.WIFI_STATE_DISABLING:
693 removeConnectedAccessPointPreference();
694 mAccessPointsPreferenceCategory.removeAll();
695 addMessagePreference(R.string.wifi_stopping);
698 case WifiManager.WIFI_STATE_DISABLED:
700 setProgressBarVisible(false);
706 * Called when the connection state of wifi has changed and isConnected
707 * should be called to get the updated state.
710 public void onConnectedChanged() {
711 updateAccessPointsDelayed();
712 changeNextButtonState(mWifiTracker.isConnected());
715 private void updateAccessPointPreferences() {
716 // in case state has changed
717 if (!mWifiManager.isWifiEnabled()) {
720 // AccessPoints are sorted by the WifiTracker
721 final List<AccessPoint> accessPoints = mWifiTracker.getAccessPoints();
723 Log.d(TAG, "updateAccessPoints called for: " + accessPoints);
726 boolean hasAvailableAccessPoints = false;
727 mAccessPointsPreferenceCategory.removePreference(mStatusMessagePreference);
728 cacheRemoveAllPrefs(mAccessPointsPreferenceCategory);
731 configureConnectedAccessPointPreferenceCategory(accessPoints) ? 1 : 0;
732 int numAccessPoints = accessPoints.size();
733 for (; index < numAccessPoints; index++) {
734 AccessPoint accessPoint = accessPoints.get(index);
735 // Ignore access points that are out of range.
736 if (accessPoint.isReachable()) {
737 String key = accessPoint.getBssid();
738 if (TextUtils.isEmpty(key)) {
739 key = accessPoint.getSsidStr();
741 hasAvailableAccessPoints = true;
742 LongPressAccessPointPreference pref =
743 (LongPressAccessPointPreference) getCachedPreference(key);
745 pref.setOrder(index);
748 LongPressAccessPointPreference preference =
749 createLongPressActionPointPreference(accessPoint);
750 preference.setKey(key);
751 preference.setOrder(index);
752 if (mOpenSsid != null && mOpenSsid.equals(accessPoint.getSsidStr())
753 && !accessPoint.isSaved()
754 && accessPoint.getSecurity() != AccessPoint.SECURITY_NONE) {
755 onPreferenceTreeClick(preference);
758 mAccessPointsPreferenceCategory.addPreference(preference);
759 accessPoint.setListener(WifiSettings.this);
760 preference.refresh();
763 removeCachedPrefs(mAccessPointsPreferenceCategory);
764 mAddPreference.setOrder(index);
765 mAccessPointsPreferenceCategory.addPreference(mAddPreference);
766 setAdditionalSettingsSummaries();
768 if (!hasAvailableAccessPoints) {
769 setProgressBarVisible(true);
770 Preference pref = new Preference(getPrefContext());
771 pref.setSelectable(false);
772 pref.setSummary(R.string.wifi_empty_list_wifi_on);
773 pref.setOrder(index++);
774 pref.setKey(PREF_KEY_EMPTY_WIFI_LIST);
775 mAccessPointsPreferenceCategory.addPreference(pref);
777 // Continuing showing progress bar for an additional delay to overlap with animation
778 getView().postDelayed(mHideProgressBarRunnable, 1700 /* delay millis */);
783 private LongPressAccessPointPreference createLongPressActionPointPreference(
784 AccessPoint accessPoint) {
785 return new LongPressAccessPointPreference(accessPoint, getPrefContext(), mUserBadgeCache,
786 false, R.drawable.ic_wifi_signal_0, this);
790 * Configure the ConnectedAccessPointPreferenceCategory and return true if the Category was
793 private boolean configureConnectedAccessPointPreferenceCategory(
794 List<AccessPoint> accessPoints) {
795 if (accessPoints.size() == 0) {
796 removeConnectedAccessPointPreference();
800 AccessPoint connectedAp = accessPoints.get(0);
801 if (!connectedAp.isActive()) {
802 removeConnectedAccessPointPreference();
806 // Is the preference category empty?
807 if (mConnectedAccessPointPreferenceCategory.getPreferenceCount() == 0) {
808 addConnectedAccessPointPreference(connectedAp);
812 // Is the previous currently connected SSID different from the new one?
813 if (!((AccessPointPreference)
814 mConnectedAccessPointPreferenceCategory.getPreference(0))
815 .getAccessPoint().getSsidStr().equals(
816 connectedAp.getSsidStr())) {
817 removeConnectedAccessPointPreference();
818 addConnectedAccessPointPreference(connectedAp);
822 // Else same AP is connected, simply refresh the connected access point preference
823 // (first and only access point in this category).
824 ((LongPressAccessPointPreference) mConnectedAccessPointPreferenceCategory.getPreference(0))
830 * Creates a Preference for the given {@link AccessPoint} and adds it to the
831 * {@link #mConnectedAccessPointPreferenceCategory}.
833 private void addConnectedAccessPointPreference(AccessPoint connectedAp) {
834 String key = connectedAp.getBssid();
835 LongPressAccessPointPreference pref = (LongPressAccessPointPreference)
836 getCachedPreference(key);
838 pref = createLongPressActionPointPreference(connectedAp);
841 // Save the state of the current access point in the bundle so that we can restore it
842 // in the Wifi Network Details Fragment
843 pref.getAccessPoint().saveWifiState(pref.getExtras());
844 pref.setFragment(WifiNetworkDetailsFragment.class.getName());
847 mConnectedAccessPointPreferenceCategory.addPreference(pref);
848 mConnectedAccessPointPreferenceCategory.setVisible(true);
851 /** Removes all preferences and hide the {@link #mConnectedAccessPointPreferenceCategory}. */
852 private void removeConnectedAccessPointPreference() {
853 mConnectedAccessPointPreferenceCategory.removeAll();
854 mConnectedAccessPointPreferenceCategory.setVisible(false);
857 private void setAdditionalSettingsSummaries() {
858 mAdditionalSettingsPreferenceCategory.addPreference(mConfigureWifiSettingsPreference);
859 final int defaultWakeupAvailable = getResources().getInteger(
860 com.android.internal.R.integer.config_wifi_wakeup_available);
861 boolean wifiWakeupAvailable = Settings.Global.getInt(
862 getContentResolver(), Settings.Global.WIFI_WAKEUP_AVAILABLE, defaultWakeupAvailable)
864 if (wifiWakeupAvailable) {
865 boolean wifiWakeupEnabled = Settings.Global.getInt(
866 getContentResolver(), Settings.Global.WIFI_WAKEUP_ENABLED, 0) == 1;
867 mConfigureWifiSettingsPreference.setSummary(getString(wifiWakeupEnabled
868 ? R.string.wifi_configure_settings_preference_summary_wakeup_on
869 : R.string.wifi_configure_settings_preference_summary_wakeup_off));
871 int numSavedNetworks = mWifiTracker.getNumSavedNetworks();
872 if (numSavedNetworks > 0) {
873 mAdditionalSettingsPreferenceCategory.addPreference(mSavedNetworksPreference);
874 mSavedNetworksPreference.setSummary(
875 getResources().getQuantityString(R.plurals.wifi_saved_access_points_summary,
876 numSavedNetworks, numSavedNetworks));
878 mAdditionalSettingsPreferenceCategory.removePreference(mSavedNetworksPreference);
882 private void setOffMessage() {
883 final CharSequence title = getText(R.string.wifi_empty_list_wifi_off);
884 // Don't use WifiManager.isScanAlwaysAvailable() to check the Wi-Fi scanning mode. Instead,
885 // read the system settings directly. Because when the device is in Airplane mode, even if
886 // Wi-Fi scanning mode is on, WifiManager.isScanAlwaysAvailable() still returns "off".
887 final boolean wifiScanningMode = Settings.Global.getInt(getActivity().getContentResolver(),
888 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1;
889 final CharSequence description = wifiScanningMode ? getText(R.string.wifi_scan_notify_text)
890 : getText(R.string.wifi_scan_notify_text_scanning_off);
891 final LinkifyUtils.OnClickListener clickListener = new LinkifyUtils.OnClickListener() {
893 public void onClick() {
894 final SettingsActivity activity = (SettingsActivity) getActivity();
895 activity.startPreferencePanel(WifiSettings.this,
896 ScanningSettings.class.getName(),
897 null, R.string.location_scanning_screen_title, null, null, 0);
900 mStatusMessagePreference.setText(title, description, clickListener);
901 removeConnectedAccessPointPreference();
902 mAccessPointsPreferenceCategory.removeAll();
903 mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference);
906 private void addMessagePreference(int messageId) {
907 mStatusMessagePreference.setTitle(messageId);
908 removeConnectedAccessPointPreference();
909 mAccessPointsPreferenceCategory.removeAll();
910 mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference);
913 protected void setProgressBarVisible(boolean visible) {
914 if (mProgressHeader != null) {
915 mProgressHeader.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
920 * Renames/replaces "Next" button when appropriate. "Next" button usually exists in
921 * Wifi setup screens, not in usual wifi settings screen.
923 * @param enabled true when the device is connected to a wifi network.
925 private void changeNextButtonState(boolean enabled) {
926 if (mEnableNextOnConnection && hasNextButton()) {
927 getNextButton().setEnabled(enabled);
932 public void onForget(WifiDialog dialog) {
937 public void onSubmit(WifiDialog dialog) {
938 if (mDialog != null) {
939 submit(mDialog.getController());
943 /* package */ void submit(WifiConfigController configController) {
945 final WifiConfiguration config = configController.getConfig();
947 if (config == null) {
948 if (mSelectedAccessPoint != null
949 && mSelectedAccessPoint.isSaved()) {
950 connect(mSelectedAccessPoint.getConfig(), true /* isSavedNetwork */);
952 } else if (configController.getMode() == WifiConfigUiBase.MODE_MODIFY) {
953 mWifiManager.save(config, mSaveListener);
955 mWifiManager.save(config, mSaveListener);
956 if (mSelectedAccessPoint != null) { // Not an "Add network"
957 connect(config, false /* isSavedNetwork */);
961 mWifiTracker.resumeScanning();
964 /* package */ void forget() {
965 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_FORGET);
966 if (!mSelectedAccessPoint.isSaved()) {
967 if (mSelectedAccessPoint.getNetworkInfo() != null &&
968 mSelectedAccessPoint.getNetworkInfo().getState() != State.DISCONNECTED) {
969 // Network is active but has no network ID - must be ephemeral.
970 mWifiManager.disableEphemeralNetwork(
971 AccessPoint.convertToQuotedString(mSelectedAccessPoint.getSsidStr()));
973 // Should not happen, but a monkey seems to trigger it
974 Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig());
977 } else if (mSelectedAccessPoint.getConfig().isPasspoint()) {
978 mWifiManager.removePasspointConfiguration(mSelectedAccessPoint.getConfig().FQDN);
980 mWifiManager.forget(mSelectedAccessPoint.getConfig().networkId, mForgetListener);
983 mWifiTracker.resumeScanning();
985 // We need to rename/replace "Next" button in wifi setup context.
986 changeNextButtonState(false);
989 protected void connect(final WifiConfiguration config, boolean isSavedNetwork) {
990 // Log subtype if configuration is a saved network.
991 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT,
993 mWifiManager.connect(config, mConnectListener);
996 protected void connect(final int networkId, boolean isSavedNetwork) {
997 // Log subtype if configuration is a saved network.
998 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT,
1000 mWifiManager.connect(networkId, mConnectListener);
1004 * Called when "add network" button is pressed.
1006 /* package */ void onAddNetworkPressed() {
1007 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_ADD_NETWORK);
1008 // No exact access point is selected.
1009 mSelectedAccessPoint = null;
1010 showDialog(null, WifiConfigUiBase.MODE_CONNECT);
1014 protected int getHelpResource() {
1015 return R.string.help_url_wifi;
1019 public void onAccessPointChanged(final AccessPoint accessPoint) {
1020 Log.d(TAG, "onAccessPointChanged (singular) callback initiated");
1021 View view = getView();
1023 view.post(new Runnable() {
1026 Object tag = accessPoint.getTag();
1028 ((LongPressAccessPointPreference) tag).refresh();
1036 public void onLevelChanged(AccessPoint accessPoint) {
1037 ((LongPressAccessPointPreference) accessPoint.getTag()).onLevelChanged();
1040 public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
1041 new BaseSearchIndexProvider() {
1043 public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) {
1044 final List<SearchIndexableRaw> result = new ArrayList<>();
1045 final Resources res = context.getResources();
1047 // Add fragment title
1048 SearchIndexableRaw data = new SearchIndexableRaw(context);
1049 data.title = res.getString(R.string.wifi_settings);
1050 data.screenTitle = res.getString(R.string.wifi_settings);
1051 data.keywords = res.getString(R.string.keywords_wifi);
1052 data.key = DATA_KEY_REFERENCE;
1055 // Add saved Wi-Fi access points
1056 final List<AccessPoint> accessPoints =
1057 WifiTracker.getCurrentAccessPoints(context, true, false, false);
1058 for (AccessPoint accessPoint : accessPoints) {
1059 data = new SearchIndexableRaw(context);
1060 data.title = accessPoint.getSsidStr();
1061 data.screenTitle = res.getString(R.string.wifi_settings);
1062 data.enabled = enabled;
1071 * Returns true if the config is not editable through Settings.
1072 * @param context Context of caller
1073 * @param config The WiFi config.
1074 * @return true if the config is not editable through Settings.
1076 static boolean isEditabilityLockedDown(Context context, WifiConfiguration config) {
1077 return !canModifyNetwork(context, config);
1081 * This method is a stripped version of WifiConfigStore.canModifyNetwork.
1082 * TODO: refactor to have only one method.
1083 * @param context Context of caller
1084 * @param config The WiFi config.
1085 * @return true if Settings can modify the config.
1087 static boolean canModifyNetwork(Context context, WifiConfiguration config) {
1088 if (config == null) {
1092 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
1093 Context.DEVICE_POLICY_SERVICE);
1095 // Check if device has DPM capability. If it has and dpm is still null, then we
1096 // treat this case with suspicion and bail out.
1097 final PackageManager pm = context.getPackageManager();
1098 if (pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN) && dpm == null) {
1102 boolean isConfigEligibleForLockdown = false;
1104 final ComponentName deviceOwner = dpm.getDeviceOwnerComponentOnAnyUser();
1105 if (deviceOwner != null) {
1106 final int deviceOwnerUserId = dpm.getDeviceOwnerUserId();
1108 final int deviceOwnerUid = pm.getPackageUidAsUser(deviceOwner.getPackageName(),
1110 isConfigEligibleForLockdown = deviceOwnerUid == config.creatorUid;
1111 } catch (NameNotFoundException e) {
1116 if (!isConfigEligibleForLockdown) {
1120 final ContentResolver resolver = context.getContentResolver();
1121 final boolean isLockdownFeatureEnabled = Settings.Global.getInt(resolver,
1122 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) != 0;
1123 return !isLockdownFeatureEnabled;
1126 private static class SummaryProvider
1127 implements SummaryLoader.SummaryProvider, OnSummaryChangeListener {
1129 private final Context mContext;
1130 private final SummaryLoader mSummaryLoader;
1133 WifiSummaryUpdater mSummaryHelper;
1135 public SummaryProvider(Context context, SummaryLoader summaryLoader) {
1137 mSummaryLoader = summaryLoader;
1138 mSummaryHelper = new WifiSummaryUpdater(mContext, this);
1143 public void setListening(boolean listening) {
1144 mSummaryHelper.register(listening);
1148 public void onSummaryChanged(String summary) {
1149 mSummaryLoader.setSummary(this, summary);
1153 public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY
1154 = new SummaryLoader.SummaryProviderFactory() {
1156 public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity,
1157 SummaryLoader summaryLoader) {
1158 return new SummaryProvider(activity, summaryLoader);