WifiSettings.java revision d4292256406d374e923335d1c97752da2909ad7b
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17package com.android.settings.wifi; 18 19import static android.os.UserManager.DISALLOW_CONFIG_WIFI; 20 21import android.annotation.NonNull; 22import android.app.Activity; 23import android.app.Dialog; 24import android.content.ContentResolver; 25import android.content.Context; 26import android.content.Intent; 27import android.content.res.Resources; 28import android.net.ConnectivityManager; 29import android.net.NetworkInfo; 30import android.net.NetworkInfo.State; 31import android.net.wifi.WifiConfiguration; 32import android.net.wifi.WifiManager; 33import android.net.wifi.WpsInfo; 34import android.nfc.NfcAdapter; 35import android.os.Bundle; 36import android.os.PowerManager; 37import android.provider.Settings; 38import android.support.annotation.VisibleForTesting; 39import android.support.v7.preference.Preference; 40import android.support.v7.preference.PreferenceCategory; 41import android.util.Log; 42import android.view.ContextMenu; 43import android.view.ContextMenu.ContextMenuInfo; 44import android.view.Menu; 45import android.view.MenuItem; 46import android.view.View; 47import android.widget.Toast; 48 49import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 50import com.android.settings.LinkifyUtils; 51import com.android.settings.R; 52import com.android.settings.RestrictedSettingsFragment; 53import com.android.settings.SettingsActivity; 54import com.android.settings.dashboard.SummaryLoader; 55import com.android.settings.location.ScanningSettings; 56import com.android.settings.search.BaseSearchIndexProvider; 57import com.android.settings.search.Indexable; 58import com.android.settings.search.SearchIndexableRaw; 59import com.android.settings.widget.SummaryUpdater.OnSummaryChangeListener; 60import com.android.settings.widget.SwitchBarController; 61import com.android.settings.wifi.details.WifiNetworkDetailsFragment; 62import com.android.settings.wrapper.WifiManagerWrapper; 63import com.android.settingslib.RestrictedLockUtils; 64import com.android.settingslib.wifi.AccessPoint; 65import com.android.settingslib.wifi.AccessPoint.AccessPointListener; 66import com.android.settingslib.wifi.AccessPointPreference; 67import com.android.settingslib.wifi.WifiTracker; 68import com.android.settingslib.wifi.WifiTrackerFactory; 69 70import java.util.ArrayList; 71import java.util.List; 72 73/** 74 * Two types of UI are provided here. 75 * 76 * The first is for "usual Settings", appearing as any other Setup fragment. 77 * 78 * The second is for Setup Wizard, with a simplified interface that hides the action bar 79 * and menus. 80 */ 81public class WifiSettings extends RestrictedSettingsFragment 82 implements Indexable, WifiTracker.WifiListener, AccessPointListener, 83 WifiDialog.WifiDialogListener { 84 85 private static final String TAG = "WifiSettings"; 86 87 /* package */ static final int MENU_ID_WPS_PBC = Menu.FIRST; 88 private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1; 89 private static final int MENU_ID_CONNECT = Menu.FIRST + 6; 90 private static final int MENU_ID_FORGET = Menu.FIRST + 7; 91 private static final int MENU_ID_MODIFY = Menu.FIRST + 8; 92 private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9; 93 94 public static final int WIFI_DIALOG_ID = 1; 95 /* package */ static final int WPS_PBC_DIALOG_ID = 2; 96 private static final int WPS_PIN_DIALOG_ID = 3; 97 private static final int WRITE_NFC_DIALOG_ID = 6; 98 99 // Instance state keys 100 private static final String SAVE_DIALOG_MODE = "dialog_mode"; 101 private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state"; 102 private static final String SAVED_WIFI_NFC_DIALOG_STATE = "wifi_nfc_dlg_state"; 103 104 private static final String PREF_KEY_EMPTY_WIFI_LIST = "wifi_empty_list"; 105 private static final String PREF_KEY_CONNECTED_ACCESS_POINTS = "connected_access_point"; 106 private static final String PREF_KEY_ACCESS_POINTS = "access_points"; 107 private static final String PREF_KEY_ADDITIONAL_SETTINGS = "additional_settings"; 108 private static final String PREF_KEY_CONFIGURE_WIFI_SETTINGS = "configure_settings"; 109 private static final String PREF_KEY_SAVED_NETWORKS = "saved_networks"; 110 111 private final Runnable mUpdateAccessPointsRunnable = () -> { 112 updateAccessPointPreferences(); 113 }; 114 private final Runnable mHideProgressBarRunnable = () -> { 115 setProgressBarVisible(false); 116 }; 117 118 protected WifiManager mWifiManager; 119 private WifiManager.ActionListener mConnectListener; 120 private WifiManager.ActionListener mSaveListener; 121 private WifiManager.ActionListener mForgetListener; 122 123 /** 124 * The state of {@link #isUiRestricted()} at {@link #onCreate(Bundle)}}. This is neccesary to 125 * ensure that behavior is consistent if {@link #isUiRestricted()} changes. It could be changed 126 * by the Test DPC tool in AFW mode. 127 */ 128 private boolean mIsRestricted; 129 130 private WifiEnabler mWifiEnabler; 131 // An access point being editted is stored here. 132 private AccessPoint mSelectedAccessPoint; 133 134 private WifiDialog mDialog; 135 private WriteWifiConfigToNfcDialog mWifiToNfcDialog; 136 137 private View mProgressHeader; 138 139 // this boolean extra specifies whether to disable the Next button when not connected. Used by 140 // account creation outside of setup wizard. 141 private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect"; 142 // This string extra specifies a network to open the connect dialog on, so the user can enter 143 // network credentials. This is used by quick settings for secured networks, among other 144 // things. 145 public static final String EXTRA_START_CONNECT_SSID = "wifi_start_connect_ssid"; 146 147 // should Next button only be enabled when we have a connection? 148 private boolean mEnableNextOnConnection; 149 150 // Save the dialog details 151 private int mDialogMode; 152 private AccessPoint mDlgAccessPoint; 153 private Bundle mAccessPointSavedState; 154 private Bundle mWifiNfcDialogSavedState; 155 156 private WifiTracker mWifiTracker; 157 private String mOpenSsid; 158 159 private AccessPointPreference.UserBadgeCache mUserBadgeCache; 160 161 private PreferenceCategory mConnectedAccessPointPreferenceCategory; 162 private PreferenceCategory mAccessPointsPreferenceCategory; 163 private PreferenceCategory mAdditionalSettingsPreferenceCategory; 164 private Preference mAddPreference; 165 private Preference mConfigureWifiSettingsPreference; 166 private Preference mSavedNetworksPreference; 167 private LinkablePreference mStatusMessagePreference; 168 169 // For Search 170 private static final String DATA_KEY_REFERENCE = "main_toggle_wifi"; 171 172 /** 173 * Tracks whether the user initiated a connection via clicking in order to autoscroll to the 174 * network once connected. 175 */ 176 private boolean mClickedConnect; 177 178 /* End of "used in Wifi Setup context" */ 179 180 public WifiSettings() { 181 super(DISALLOW_CONFIG_WIFI); 182 } 183 184 @Override 185 public void onViewCreated(View view, Bundle savedInstanceState) { 186 super.onViewCreated(view, savedInstanceState); 187 final Activity activity = getActivity(); 188 if (activity != null) { 189 mProgressHeader = setPinnedHeaderView(R.layout.wifi_progress_header) 190 .findViewById(R.id.progress_bar_animation); 191 setProgressBarVisible(false); 192 } 193 } 194 195 @Override 196 public void onCreate(Bundle icicle) { 197 super.onCreate(icicle); 198 199 // TODO(b/37429702): Add animations and preference comparator back after initial screen is 200 // loaded (ODR). 201 setAnimationAllowed(false); 202 203 addPreferences(); 204 205 mIsRestricted = isUiRestricted(); 206 } 207 208 private void addPreferences() { 209 addPreferencesFromResource(R.xml.wifi_settings); 210 211 mConnectedAccessPointPreferenceCategory = 212 (PreferenceCategory) findPreference(PREF_KEY_CONNECTED_ACCESS_POINTS); 213 mAccessPointsPreferenceCategory = 214 (PreferenceCategory) findPreference(PREF_KEY_ACCESS_POINTS); 215 mAdditionalSettingsPreferenceCategory = 216 (PreferenceCategory) findPreference(PREF_KEY_ADDITIONAL_SETTINGS); 217 mConfigureWifiSettingsPreference = findPreference(PREF_KEY_CONFIGURE_WIFI_SETTINGS); 218 mSavedNetworksPreference = findPreference(PREF_KEY_SAVED_NETWORKS); 219 220 Context prefContext = getPrefContext(); 221 mAddPreference = new Preference(prefContext); 222 mAddPreference.setIcon(R.drawable.ic_menu_add_inset); 223 mAddPreference.setTitle(R.string.wifi_add_network); 224 mStatusMessagePreference = new LinkablePreference(prefContext); 225 226 mUserBadgeCache = new AccessPointPreference.UserBadgeCache(getPackageManager()); 227 } 228 229 @Override 230 public void onActivityCreated(Bundle savedInstanceState) { 231 super.onActivityCreated(savedInstanceState); 232 233 mWifiTracker = WifiTrackerFactory.create( 234 getActivity(), this, getLifecycle(), true, true); 235 mWifiManager = mWifiTracker.getManager(); 236 237 mConnectListener = new WifiManager.ActionListener() { 238 @Override 239 public void onSuccess() { 240 } 241 @Override 242 public void onFailure(int reason) { 243 Activity activity = getActivity(); 244 if (activity != null) { 245 Toast.makeText(activity, 246 R.string.wifi_failed_connect_message, 247 Toast.LENGTH_SHORT).show(); 248 } 249 } 250 }; 251 252 mSaveListener = new WifiManager.ActionListener() { 253 @Override 254 public void onSuccess() { 255 } 256 @Override 257 public void onFailure(int reason) { 258 Activity activity = getActivity(); 259 if (activity != null) { 260 Toast.makeText(activity, 261 R.string.wifi_failed_save_message, 262 Toast.LENGTH_SHORT).show(); 263 } 264 } 265 }; 266 267 mForgetListener = new WifiManager.ActionListener() { 268 @Override 269 public void onSuccess() { 270 } 271 @Override 272 public void onFailure(int reason) { 273 Activity activity = getActivity(); 274 if (activity != null) { 275 Toast.makeText(activity, 276 R.string.wifi_failed_forget_message, 277 Toast.LENGTH_SHORT).show(); 278 } 279 } 280 }; 281 282 if (savedInstanceState != null) { 283 mDialogMode = savedInstanceState.getInt(SAVE_DIALOG_MODE); 284 if (savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) { 285 mAccessPointSavedState = 286 savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE); 287 } 288 289 if (savedInstanceState.containsKey(SAVED_WIFI_NFC_DIALOG_STATE)) { 290 mWifiNfcDialogSavedState = 291 savedInstanceState.getBundle(SAVED_WIFI_NFC_DIALOG_STATE); 292 } 293 } 294 295 // if we're supposed to enable/disable the Next button based on our current connection 296 // state, start it off in the right state 297 Intent intent = getActivity().getIntent(); 298 mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false); 299 300 if (mEnableNextOnConnection) { 301 if (hasNextButton()) { 302 final ConnectivityManager connectivity = (ConnectivityManager) 303 getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 304 if (connectivity != null) { 305 NetworkInfo info = connectivity.getNetworkInfo( 306 ConnectivityManager.TYPE_WIFI); 307 changeNextButtonState(info.isConnected()); 308 } 309 } 310 } 311 312 registerForContextMenu(getListView()); 313 setHasOptionsMenu(true); 314 315 if (intent.hasExtra(EXTRA_START_CONNECT_SSID)) { 316 mOpenSsid = intent.getStringExtra(EXTRA_START_CONNECT_SSID); 317 } 318 } 319 320 @Override 321 public void onDestroyView() { 322 super.onDestroyView(); 323 324 if (mWifiEnabler != null) { 325 mWifiEnabler.teardownSwitchController(); 326 } 327 } 328 329 @Override 330 public void onStart() { 331 super.onStart(); 332 333 // On/off switch is hidden for Setup Wizard (returns null) 334 mWifiEnabler = createWifiEnabler(); 335 336 if (mIsRestricted) { 337 restrictUi(); 338 return; 339 } 340 341 onWifiStateChanged(mWifiManager.getWifiState()); 342 } 343 344 private void restrictUi() { 345 if (!isUiRestrictedByOnlyAdmin()) { 346 getEmptyTextView().setText(R.string.wifi_empty_list_user_restricted); 347 } 348 getPreferenceScreen().removeAll(); 349 } 350 351 /** 352 * Only update the AP list if there are not any APs currently shown. 353 * 354 * <p>Thus forceUpdate will only be called during cold start or when toggling between wifi on 355 * and off. In other use cases, the previous APs will remain until the next update is received 356 * from {@link WifiTracker}. 357 */ 358 private void conditionallyForceUpdateAPs() { 359 if (mAccessPointsPreferenceCategory.getPreferenceCount() > 0 360 && mAccessPointsPreferenceCategory.getPreference(0) instanceof 361 AccessPointPreference) { 362 // Make sure we don't update due to callbacks initiated by sticky broadcasts in 363 // WifiTracker. 364 Log.d(TAG, "Did not force update APs due to existing APs displayed"); 365 getView().removeCallbacks(mUpdateAccessPointsRunnable); 366 return; 367 } 368 setProgressBarVisible(true); 369 mWifiTracker.forceUpdate(); 370 if (WifiTracker.sVerboseLogging) { 371 Log.i(TAG, "WifiSettings force update APs: " + mWifiTracker.getAccessPoints()); 372 } 373 getView().removeCallbacks(mUpdateAccessPointsRunnable); 374 updateAccessPointPreferences(); 375 } 376 377 /** 378 * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard) 379 */ 380 private WifiEnabler createWifiEnabler() { 381 final SettingsActivity activity = (SettingsActivity) getActivity(); 382 return new WifiEnabler(activity, new SwitchBarController(activity.getSwitchBar()), 383 mMetricsFeatureProvider); 384 } 385 386 @Override 387 public void onResume() { 388 final Activity activity = getActivity(); 389 super.onResume(); 390 391 // Because RestrictedSettingsFragment's onResume potentially requests authorization, 392 // which changes the restriction state, recalculate it. 393 final boolean alreadyImmutablyRestricted = mIsRestricted; 394 mIsRestricted = isUiRestricted(); 395 if (!alreadyImmutablyRestricted && mIsRestricted) { 396 restrictUi(); 397 } 398 399 if (mWifiEnabler != null) { 400 mWifiEnabler.resume(activity); 401 } 402 } 403 404 @Override 405 public void onPause() { 406 super.onPause(); 407 if (mWifiEnabler != null) { 408 mWifiEnabler.pause(); 409 } 410 } 411 412 @Override 413 public void onStop() { 414 getView().removeCallbacks(mUpdateAccessPointsRunnable); 415 getView().removeCallbacks(mHideProgressBarRunnable); 416 super.onStop(); 417 } 418 419 @Override 420 public void onActivityResult(int requestCode, int resultCode, Intent data) { 421 super.onActivityResult(requestCode, resultCode, data); 422 423 final boolean formerlyRestricted = mIsRestricted; 424 mIsRestricted = isUiRestricted(); 425 if (formerlyRestricted && !mIsRestricted 426 && getPreferenceScreen().getPreferenceCount() == 0) { 427 // De-restrict the ui 428 addPreferences(); 429 } 430 } 431 432 @Override 433 public int getMetricsCategory() { 434 return MetricsEvent.WIFI; 435 } 436 437 @Override 438 public void onSaveInstanceState(Bundle outState) { 439 super.onSaveInstanceState(outState); 440 441 // If the dialog is showing, save its state. 442 if (mDialog != null && mDialog.isShowing()) { 443 outState.putInt(SAVE_DIALOG_MODE, mDialogMode); 444 if (mDlgAccessPoint != null) { 445 mAccessPointSavedState = new Bundle(); 446 mDlgAccessPoint.saveWifiState(mAccessPointSavedState); 447 outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState); 448 } 449 } 450 451 if (mWifiToNfcDialog != null && mWifiToNfcDialog.isShowing()) { 452 Bundle savedState = new Bundle(); 453 mWifiToNfcDialog.saveState(savedState); 454 outState.putBundle(SAVED_WIFI_NFC_DIALOG_STATE, savedState); 455 } 456 } 457 458 @Override 459 public boolean onOptionsItemSelected(MenuItem item) { 460 // If the user is not allowed to configure wifi, do not handle menu selections. 461 if (mIsRestricted) { 462 return false; 463 } 464 465 switch (item.getItemId()) { 466 case MENU_ID_WPS_PBC: 467 showDialog(WPS_PBC_DIALOG_ID); 468 return true; 469 case MENU_ID_WPS_PIN: 470 showDialog(WPS_PIN_DIALOG_ID); 471 return true; 472 } 473 return super.onOptionsItemSelected(item); 474 } 475 476 @Override 477 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) { 478 Preference preference = (Preference) view.getTag(); 479 480 if (preference instanceof LongPressAccessPointPreference) { 481 mSelectedAccessPoint = 482 ((LongPressAccessPointPreference) preference).getAccessPoint(); 483 menu.setHeaderTitle(mSelectedAccessPoint.getSsid()); 484 if (mSelectedAccessPoint.isConnectable()) { 485 menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect); 486 } 487 488 WifiConfiguration config = mSelectedAccessPoint.getConfig(); 489 // Some configs are ineditable 490 if (WifiUtils.isNetworkLockedDown(getActivity(), config)) { 491 return; 492 } 493 494 if (mSelectedAccessPoint.isSaved() || mSelectedAccessPoint.isEphemeral()) { 495 // Allow forgetting a network if either the network is saved or ephemerally 496 // connected. (In the latter case, "forget" blacklists the network so it won't 497 // be used again, ephemerally). 498 menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget); 499 } 500 if (mSelectedAccessPoint.isSaved()) { 501 menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify); 502 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); 503 if (nfcAdapter != null && nfcAdapter.isEnabled() && 504 mSelectedAccessPoint.getSecurity() != AccessPoint.SECURITY_NONE) { 505 // Only allow writing of NFC tags for password-protected networks. 506 menu.add(Menu.NONE, MENU_ID_WRITE_NFC, 0, R.string.wifi_menu_write_to_nfc); 507 } 508 } 509 } 510 } 511 512 @Override 513 public boolean onContextItemSelected(MenuItem item) { 514 if (mSelectedAccessPoint == null) { 515 return super.onContextItemSelected(item); 516 } 517 switch (item.getItemId()) { 518 case MENU_ID_CONNECT: { 519 boolean isSavedNetwork = mSelectedAccessPoint.isSaved(); 520 if (isSavedNetwork) { 521 connect(mSelectedAccessPoint.getConfig(), isSavedNetwork); 522 } else if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE) { 523 /** Bypass dialog for unsecured networks */ 524 mSelectedAccessPoint.generateOpenNetworkConfig(); 525 connect(mSelectedAccessPoint.getConfig(), isSavedNetwork); 526 } else { 527 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT); 528 } 529 return true; 530 } 531 case MENU_ID_FORGET: { 532 forget(); 533 return true; 534 } 535 case MENU_ID_MODIFY: { 536 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_MODIFY); 537 return true; 538 } 539 case MENU_ID_WRITE_NFC: 540 showDialog(WRITE_NFC_DIALOG_ID); 541 return true; 542 543 } 544 return super.onContextItemSelected(item); 545 } 546 547 @Override 548 public boolean onPreferenceTreeClick(Preference preference) { 549 // If the preference has a fragment set, open that 550 if (preference.getFragment() != null) { 551 preference.setOnPreferenceClickListener(null); 552 return super.onPreferenceTreeClick(preference); 553 } 554 555 if (preference instanceof LongPressAccessPointPreference) { 556 mSelectedAccessPoint = ((LongPressAccessPointPreference) preference).getAccessPoint(); 557 if (mSelectedAccessPoint == null) { 558 return false; 559 } 560 if (mSelectedAccessPoint.isActive()) { 561 return super.onPreferenceTreeClick(preference); 562 } 563 /** 564 * Bypass dialog and connect to unsecured networks, or previously connected saved 565 * networks, or Passpoint provided networks. 566 */ 567 WifiConfiguration config = mSelectedAccessPoint.getConfig(); 568 if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE) { 569 mSelectedAccessPoint.generateOpenNetworkConfig(); 570 connect(mSelectedAccessPoint.getConfig(), mSelectedAccessPoint.isSaved()); 571 } else if (mSelectedAccessPoint.isSaved() && config != null 572 && config.getNetworkSelectionStatus() != null 573 && config.getNetworkSelectionStatus().getHasEverConnected()) { 574 connect(config, true /* isSavedNetwork */); 575 } else if (mSelectedAccessPoint.isPasspoint()) { 576 // Access point provided by an installed Passpoint provider, connect using 577 // the associated config. 578 connect(config, true /* isSavedNetwork */); 579 } else { 580 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT); 581 } 582 } else if (preference == mAddPreference) { 583 onAddNetworkPressed(); 584 } else { 585 return super.onPreferenceTreeClick(preference); 586 } 587 return true; 588 } 589 590 private void showDialog(AccessPoint accessPoint, int dialogMode) { 591 if (accessPoint != null) { 592 WifiConfiguration config = accessPoint.getConfig(); 593 if (WifiUtils.isNetworkLockedDown(getActivity(), config) && accessPoint.isActive()) { 594 RestrictedLockUtils.sendShowAdminSupportDetailsIntent(getActivity(), 595 RestrictedLockUtils.getDeviceOwner(getActivity())); 596 return; 597 } 598 } 599 600 if (mDialog != null) { 601 removeDialog(WIFI_DIALOG_ID); 602 mDialog = null; 603 } 604 605 // Save the access point and edit mode 606 mDlgAccessPoint = accessPoint; 607 mDialogMode = dialogMode; 608 609 showDialog(WIFI_DIALOG_ID); 610 } 611 612 @Override 613 public Dialog onCreateDialog(int dialogId) { 614 switch (dialogId) { 615 case WIFI_DIALOG_ID: 616 if (mDlgAccessPoint == null && mAccessPointSavedState == null) { 617 // add new network 618 mDialog = WifiDialog 619 .createFullscreen(getActivity(), this, mDlgAccessPoint, mDialogMode); 620 } else { 621 // modify network 622 if (mDlgAccessPoint == null) { 623 // restore AP from save state 624 mDlgAccessPoint = new AccessPoint(getActivity(), mAccessPointSavedState); 625 // Reset the saved access point data 626 mAccessPointSavedState = null; 627 } 628 mDialog = WifiDialog 629 .createModal(getActivity(), this, mDlgAccessPoint, mDialogMode); 630 } 631 632 mSelectedAccessPoint = mDlgAccessPoint; 633 return mDialog; 634 case WPS_PBC_DIALOG_ID: 635 return new WpsDialog(getActivity(), WpsInfo.PBC); 636 case WPS_PIN_DIALOG_ID: 637 return new WpsDialog(getActivity(), WpsInfo.DISPLAY); 638 case WRITE_NFC_DIALOG_ID: 639 if (mSelectedAccessPoint != null) { 640 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog( 641 getActivity(), 642 mSelectedAccessPoint.getSecurity(), 643 new WifiManagerWrapper(mWifiManager)); 644 } else if (mWifiNfcDialogSavedState != null) { 645 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(getActivity(), 646 mWifiNfcDialogSavedState, new WifiManagerWrapper(mWifiManager)); 647 } 648 649 return mWifiToNfcDialog; 650 } 651 return super.onCreateDialog(dialogId); 652 } 653 654 @Override 655 public int getDialogMetricsCategory(int dialogId) { 656 switch (dialogId) { 657 case WIFI_DIALOG_ID: 658 return MetricsEvent.DIALOG_WIFI_AP_EDIT; 659 case WPS_PBC_DIALOG_ID: 660 return MetricsEvent.DIALOG_WIFI_PBC; 661 case WPS_PIN_DIALOG_ID: 662 return MetricsEvent.DIALOG_WIFI_PIN; 663 case WRITE_NFC_DIALOG_ID: 664 return MetricsEvent.DIALOG_WIFI_WRITE_NFC; 665 default: 666 return 0; 667 } 668 } 669 670 /** 671 * Called to indicate the list of AccessPoints has been updated and 672 * getAccessPoints should be called to get the latest information. 673 */ 674 @Override 675 public void onAccessPointsChanged() { 676 Log.d(TAG, "onAccessPointsChanged (WifiTracker) callback initiated"); 677 updateAccessPointsDelayed(); 678 } 679 680 /** 681 * Updates access points from {@link WifiManager#getScanResults()}. Adds a delay to have 682 * progress bar displayed before starting to modify APs. 683 */ 684 private void updateAccessPointsDelayed() { 685 // Safeguard from some delayed event handling 686 if (getActivity() != null && !mIsRestricted && mWifiManager.isWifiEnabled()) { 687 setProgressBarVisible(true); 688 getView().postDelayed(mUpdateAccessPointsRunnable, 300 /* delay milliseconds */); 689 } 690 } 691 692 /** Called when the state of Wifi has changed. */ 693 @Override 694 public void onWifiStateChanged(int state) { 695 if (mIsRestricted) { 696 return; 697 } 698 699 final int wifiState = mWifiManager.getWifiState(); 700 switch (wifiState) { 701 case WifiManager.WIFI_STATE_ENABLED: 702 conditionallyForceUpdateAPs(); 703 break; 704 705 case WifiManager.WIFI_STATE_ENABLING: 706 removeConnectedAccessPointPreference(); 707 mAccessPointsPreferenceCategory.removeAll(); 708 addMessagePreference(R.string.wifi_starting); 709 setProgressBarVisible(true); 710 break; 711 712 case WifiManager.WIFI_STATE_DISABLING: 713 removeConnectedAccessPointPreference(); 714 mAccessPointsPreferenceCategory.removeAll(); 715 addMessagePreference(R.string.wifi_stopping); 716 break; 717 718 case WifiManager.WIFI_STATE_DISABLED: 719 setOffMessage(); 720 setAdditionalSettingsSummaries(); 721 setProgressBarVisible(false); 722 break; 723 } 724 } 725 726 /** 727 * Called when the connection state of wifi has changed. 728 */ 729 @Override 730 public void onConnectedChanged() { 731 changeNextButtonState(mWifiTracker.isConnected()); 732 } 733 734 /** Helper method to return whether an AccessPoint is disabled due to a wrong password */ 735 private static boolean isDisabledByWrongPassword(AccessPoint accessPoint) { 736 WifiConfiguration config = accessPoint.getConfig(); 737 if (config == null) { 738 return false; 739 } 740 WifiConfiguration.NetworkSelectionStatus networkStatus = 741 config.getNetworkSelectionStatus(); 742 if (networkStatus == null || networkStatus.isNetworkEnabled()) { 743 return false; 744 } 745 int reason = networkStatus.getNetworkSelectionDisableReason(); 746 return WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD == reason; 747 } 748 749 private void updateAccessPointPreferences() { 750 // in case state has changed 751 if (!mWifiManager.isWifiEnabled()) { 752 return; 753 } 754 // AccessPoints are sorted by the WifiTracker 755 final List<AccessPoint> accessPoints = mWifiTracker.getAccessPoints(); 756 if (WifiTracker.sVerboseLogging) { 757 Log.i(TAG, "updateAccessPoints called for: " + accessPoints); 758 } 759 760 boolean hasAvailableAccessPoints = false; 761 mAccessPointsPreferenceCategory.removePreference(mStatusMessagePreference); 762 cacheRemoveAllPrefs(mAccessPointsPreferenceCategory); 763 764 int index = 765 configureConnectedAccessPointPreferenceCategory(accessPoints) ? 1 : 0; 766 int numAccessPoints = accessPoints.size(); 767 for (; index < numAccessPoints; index++) { 768 AccessPoint accessPoint = accessPoints.get(index); 769 // Ignore access points that are out of range. 770 if (accessPoint.isReachable()) { 771 String key = AccessPointPreference.generatePreferenceKey(accessPoint); 772 hasAvailableAccessPoints = true; 773 LongPressAccessPointPreference pref = 774 (LongPressAccessPointPreference) getCachedPreference(key); 775 if (pref != null) { 776 pref.setOrder(index); 777 continue; 778 } 779 LongPressAccessPointPreference preference = 780 createLongPressAccessPointPreference(accessPoint); 781 preference.setKey(key); 782 preference.setOrder(index); 783 if (mOpenSsid != null && mOpenSsid.equals(accessPoint.getSsidStr()) 784 && accessPoint.getSecurity() != AccessPoint.SECURITY_NONE) { 785 if (!accessPoint.isSaved() || isDisabledByWrongPassword(accessPoint)) { 786 onPreferenceTreeClick(preference); 787 mOpenSsid = null; 788 } 789 } 790 mAccessPointsPreferenceCategory.addPreference(preference); 791 accessPoint.setListener(WifiSettings.this); 792 preference.refresh(); 793 } 794 } 795 removeCachedPrefs(mAccessPointsPreferenceCategory); 796 mAddPreference.setOrder(index); 797 mAccessPointsPreferenceCategory.addPreference(mAddPreference); 798 setAdditionalSettingsSummaries(); 799 800 if (!hasAvailableAccessPoints) { 801 setProgressBarVisible(true); 802 Preference pref = new Preference(getPrefContext()); 803 pref.setSelectable(false); 804 pref.setSummary(R.string.wifi_empty_list_wifi_on); 805 pref.setOrder(index++); 806 pref.setKey(PREF_KEY_EMPTY_WIFI_LIST); 807 mAccessPointsPreferenceCategory.addPreference(pref); 808 } else { 809 // Continuing showing progress bar for an additional delay to overlap with animation 810 getView().postDelayed(mHideProgressBarRunnable, 1700 /* delay millis */); 811 } 812 } 813 814 @NonNull 815 private LongPressAccessPointPreference createLongPressAccessPointPreference( 816 AccessPoint accessPoint) { 817 return new LongPressAccessPointPreference(accessPoint, getPrefContext(), mUserBadgeCache, 818 false /* forSavedNetworks */, R.drawable.ic_wifi_signal_0, this); 819 } 820 821 @NonNull 822 private ConnectedAccessPointPreference createConnectedAccessPointPreference( 823 AccessPoint accessPoint) { 824 return new ConnectedAccessPointPreference(accessPoint, getPrefContext(), mUserBadgeCache, 825 R.drawable.ic_wifi_signal_0, false /* forSavedNetworks */); 826 } 827 828 /** 829 * Configure the ConnectedAccessPointPreferenceCategory and return true if the Category was 830 * shown. 831 */ 832 private boolean configureConnectedAccessPointPreferenceCategory( 833 List<AccessPoint> accessPoints) { 834 if (accessPoints.size() == 0) { 835 removeConnectedAccessPointPreference(); 836 return false; 837 } 838 839 AccessPoint connectedAp = accessPoints.get(0); 840 if (!connectedAp.isActive()) { 841 removeConnectedAccessPointPreference(); 842 return false; 843 } 844 845 // Is the preference category empty? 846 if (mConnectedAccessPointPreferenceCategory.getPreferenceCount() == 0) { 847 addConnectedAccessPointPreference(connectedAp); 848 return true; 849 } 850 851 // Is the previous currently connected SSID different from the new one? 852 AccessPointPreference preference = (AccessPointPreference) 853 (mConnectedAccessPointPreferenceCategory.getPreference(0)); 854 // The AccessPoints need to be the same reference to ensure that updates are reflected 855 // in the UI. 856 if (preference.getAccessPoint() != connectedAp) { 857 removeConnectedAccessPointPreference(); 858 addConnectedAccessPointPreference(connectedAp); 859 return true; 860 } 861 862 // Else same AP is connected, simply refresh the connected access point preference 863 // (first and only access point in this category). 864 ((AccessPointPreference) mConnectedAccessPointPreferenceCategory.getPreference(0)) 865 .refresh(); 866 return true; 867 } 868 869 /** 870 * Creates a Preference for the given {@link AccessPoint} and adds it to the 871 * {@link #mConnectedAccessPointPreferenceCategory}. 872 */ 873 private void addConnectedAccessPointPreference(AccessPoint connectedAp) { 874 final ConnectedAccessPointPreference pref = createConnectedAccessPointPreference( 875 connectedAp); 876 877 // Launch details page on click. 878 pref.setOnGearClickListener(l -> { 879 pref.getAccessPoint().saveWifiState(pref.getExtras()); 880 881 SettingsActivity activity = (SettingsActivity) WifiSettings.this.getActivity(); 882 activity.startPreferencePanel(this, 883 WifiNetworkDetailsFragment.class.getName(), pref.getExtras(), 884 R.string.wifi_details_title, null, null, 0); 885 }); 886 887 pref.refresh(); 888 889 mConnectedAccessPointPreferenceCategory.addPreference(pref); 890 mConnectedAccessPointPreferenceCategory.setVisible(true); 891 if (mClickedConnect) { 892 mClickedConnect = false; 893 scrollToPreference(mConnectedAccessPointPreferenceCategory); 894 } 895 } 896 897 /** Removes all preferences and hide the {@link #mConnectedAccessPointPreferenceCategory}. */ 898 private void removeConnectedAccessPointPreference() { 899 mConnectedAccessPointPreferenceCategory.removeAll(); 900 mConnectedAccessPointPreferenceCategory.setVisible(false); 901 } 902 903 private void setAdditionalSettingsSummaries() { 904 mAdditionalSettingsPreferenceCategory.addPreference(mConfigureWifiSettingsPreference); 905 final int defaultWakeupAvailable = getResources().getInteger( 906 com.android.internal.R.integer.config_wifi_wakeup_available); 907 boolean wifiWakeupAvailable = Settings.Global.getInt( 908 getContentResolver(), Settings.Global.WIFI_WAKEUP_AVAILABLE, defaultWakeupAvailable) 909 == 1; 910 if (wifiWakeupAvailable) { 911 mConfigureWifiSettingsPreference.setSummary(getString( 912 isWifiWakeupEnabled() 913 ? R.string.wifi_configure_settings_preference_summary_wakeup_on 914 : R.string.wifi_configure_settings_preference_summary_wakeup_off)); 915 } 916 int numSavedNetworks = mWifiTracker.getNumSavedNetworks(); 917 if (numSavedNetworks > 0) { 918 mAdditionalSettingsPreferenceCategory.addPreference(mSavedNetworksPreference); 919 mSavedNetworksPreference.setSummary( 920 getResources().getQuantityString(R.plurals.wifi_saved_access_points_summary, 921 numSavedNetworks, numSavedNetworks)); 922 } else { 923 mAdditionalSettingsPreferenceCategory.removePreference(mSavedNetworksPreference); 924 } 925 } 926 927 private boolean isWifiWakeupEnabled() { 928 PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); 929 ContentResolver contentResolver = getContentResolver(); 930 return Settings.Global.getInt(contentResolver, 931 Settings.Global.WIFI_WAKEUP_ENABLED, 0) == 1 932 && Settings.Global.getInt(contentResolver, 933 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1 934 && Settings.Global.getInt(contentResolver, 935 Settings.Global.AIRPLANE_MODE_ON, 0) == 0 936 && Settings.Global.getInt(contentResolver, 937 Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, 0) == 1 938 && !powerManager.isPowerSaveMode(); 939 } 940 941 private void setOffMessage() { 942 final CharSequence title = getText(R.string.wifi_empty_list_wifi_off); 943 // Don't use WifiManager.isScanAlwaysAvailable() to check the Wi-Fi scanning mode. Instead, 944 // read the system settings directly. Because when the device is in Airplane mode, even if 945 // Wi-Fi scanning mode is on, WifiManager.isScanAlwaysAvailable() still returns "off". 946 final boolean wifiScanningMode = Settings.Global.getInt(getActivity().getContentResolver(), 947 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1; 948 final CharSequence description = wifiScanningMode ? getText(R.string.wifi_scan_notify_text) 949 : getText(R.string.wifi_scan_notify_text_scanning_off); 950 final LinkifyUtils.OnClickListener clickListener = new LinkifyUtils.OnClickListener() { 951 @Override 952 public void onClick() { 953 final SettingsActivity activity = (SettingsActivity) getActivity(); 954 activity.startPreferencePanel(WifiSettings.this, 955 ScanningSettings.class.getName(), 956 null, R.string.location_scanning_screen_title, null, null, 0); 957 } 958 }; 959 mStatusMessagePreference.setText(title, description, clickListener); 960 removeConnectedAccessPointPreference(); 961 mAccessPointsPreferenceCategory.removeAll(); 962 mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference); 963 } 964 965 private void addMessagePreference(int messageId) { 966 mStatusMessagePreference.setTitle(messageId); 967 removeConnectedAccessPointPreference(); 968 mAccessPointsPreferenceCategory.removeAll(); 969 mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference); 970 } 971 972 protected void setProgressBarVisible(boolean visible) { 973 if (mProgressHeader != null) { 974 mProgressHeader.setVisibility(visible ? View.VISIBLE : View.GONE); 975 } 976 } 977 978 /** 979 * Renames/replaces "Next" button when appropriate. "Next" button usually exists in 980 * Wifi setup screens, not in usual wifi settings screen. 981 * 982 * @param enabled true when the device is connected to a wifi network. 983 */ 984 private void changeNextButtonState(boolean enabled) { 985 if (mEnableNextOnConnection && hasNextButton()) { 986 getNextButton().setEnabled(enabled); 987 } 988 } 989 990 @Override 991 public void onForget(WifiDialog dialog) { 992 forget(); 993 } 994 995 @Override 996 public void onSubmit(WifiDialog dialog) { 997 if (mDialog != null) { 998 submit(mDialog.getController()); 999 } 1000 } 1001 1002 /* package */ void submit(WifiConfigController configController) { 1003 1004 final WifiConfiguration config = configController.getConfig(); 1005 1006 if (config == null) { 1007 if (mSelectedAccessPoint != null 1008 && mSelectedAccessPoint.isSaved()) { 1009 connect(mSelectedAccessPoint.getConfig(), true /* isSavedNetwork */); 1010 } 1011 } else if (configController.getMode() == WifiConfigUiBase.MODE_MODIFY) { 1012 mWifiManager.save(config, mSaveListener); 1013 } else { 1014 mWifiManager.save(config, mSaveListener); 1015 if (mSelectedAccessPoint != null) { // Not an "Add network" 1016 connect(config, false /* isSavedNetwork */); 1017 } 1018 } 1019 1020 mWifiTracker.resumeScanning(); 1021 } 1022 1023 /* package */ void forget() { 1024 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_FORGET); 1025 if (!mSelectedAccessPoint.isSaved()) { 1026 if (mSelectedAccessPoint.getNetworkInfo() != null && 1027 mSelectedAccessPoint.getNetworkInfo().getState() != State.DISCONNECTED) { 1028 // Network is active but has no network ID - must be ephemeral. 1029 mWifiManager.disableEphemeralNetwork( 1030 AccessPoint.convertToQuotedString(mSelectedAccessPoint.getSsidStr())); 1031 } else { 1032 // Should not happen, but a monkey seems to trigger it 1033 Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig()); 1034 return; 1035 } 1036 } else if (mSelectedAccessPoint.getConfig().isPasspoint()) { 1037 mWifiManager.removePasspointConfiguration(mSelectedAccessPoint.getConfig().FQDN); 1038 } else { 1039 mWifiManager.forget(mSelectedAccessPoint.getConfig().networkId, mForgetListener); 1040 } 1041 1042 mWifiTracker.resumeScanning(); 1043 1044 // We need to rename/replace "Next" button in wifi setup context. 1045 changeNextButtonState(false); 1046 } 1047 1048 protected void connect(final WifiConfiguration config, boolean isSavedNetwork) { 1049 // Log subtype if configuration is a saved network. 1050 mMetricsFeatureProvider.action(getVisibilityLogger(), MetricsEvent.ACTION_WIFI_CONNECT, 1051 isSavedNetwork); 1052 mWifiManager.connect(config, mConnectListener); 1053 mClickedConnect = true; 1054 } 1055 1056 protected void connect(final int networkId, boolean isSavedNetwork) { 1057 // Log subtype if configuration is a saved network. 1058 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT, 1059 isSavedNetwork); 1060 mWifiManager.connect(networkId, mConnectListener); 1061 } 1062 1063 /** 1064 * Called when "add network" button is pressed. 1065 */ 1066 /* package */ void onAddNetworkPressed() { 1067 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_ADD_NETWORK); 1068 // No exact access point is selected. 1069 mSelectedAccessPoint = null; 1070 showDialog(null, WifiConfigUiBase.MODE_CONNECT); 1071 } 1072 1073 @Override 1074 protected int getHelpResource() { 1075 return R.string.help_url_wifi; 1076 } 1077 1078 @Override 1079 public void onAccessPointChanged(final AccessPoint accessPoint) { 1080 Log.d(TAG, "onAccessPointChanged (singular) callback initiated"); 1081 View view = getView(); 1082 if (view != null) { 1083 view.post(new Runnable() { 1084 @Override 1085 public void run() { 1086 Object tag = accessPoint.getTag(); 1087 if (tag != null) { 1088 ((AccessPointPreference) tag).refresh(); 1089 } 1090 } 1091 }); 1092 } 1093 } 1094 1095 @Override 1096 public void onLevelChanged(AccessPoint accessPoint) { 1097 ((AccessPointPreference) accessPoint.getTag()).onLevelChanged(); 1098 } 1099 1100 public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER = 1101 new BaseSearchIndexProvider() { 1102 @Override 1103 public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) { 1104 final List<SearchIndexableRaw> result = new ArrayList<>(); 1105 final Resources res = context.getResources(); 1106 1107 // Add fragment title 1108 SearchIndexableRaw data = new SearchIndexableRaw(context); 1109 data.title = res.getString(R.string.wifi_settings); 1110 data.screenTitle = res.getString(R.string.wifi_settings); 1111 data.keywords = res.getString(R.string.keywords_wifi); 1112 data.key = DATA_KEY_REFERENCE; 1113 result.add(data); 1114 1115 return result; 1116 } 1117 }; 1118 1119 private static class SummaryProvider 1120 implements SummaryLoader.SummaryProvider, OnSummaryChangeListener { 1121 1122 private final Context mContext; 1123 private final SummaryLoader mSummaryLoader; 1124 1125 @VisibleForTesting 1126 WifiSummaryUpdater mSummaryHelper; 1127 1128 public SummaryProvider(Context context, SummaryLoader summaryLoader) { 1129 mContext = context; 1130 mSummaryLoader = summaryLoader; 1131 mSummaryHelper = new WifiSummaryUpdater(mContext, this); 1132 } 1133 1134 1135 @Override 1136 public void setListening(boolean listening) { 1137 mSummaryHelper.register(listening); 1138 } 1139 1140 @Override 1141 public void onSummaryChanged(String summary) { 1142 mSummaryLoader.setSummary(this, summary); 1143 } 1144 } 1145 1146 public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY 1147 = new SummaryLoader.SummaryProviderFactory() { 1148 @Override 1149 public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity, 1150 SummaryLoader summaryLoader) { 1151 return new SummaryProvider(activity, summaryLoader); 1152 } 1153 }; 1154} 1155