WifiSettings.java revision 69fa52807416ba349d3fd6d7c8811742f5dd74e2
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.app.admin.DevicePolicyManager; 25import android.content.ComponentName; 26import android.content.ContentResolver; 27import android.content.Context; 28import android.content.Intent; 29import android.content.pm.PackageManager; 30import android.content.pm.PackageManager.NameNotFoundException; 31import android.content.res.Resources; 32import android.net.ConnectivityManager; 33import android.net.NetworkInfo; 34import android.net.NetworkInfo.State; 35import android.net.wifi.WifiConfiguration; 36import android.net.wifi.WifiManager; 37import android.net.wifi.WpsInfo; 38import android.nfc.NfcAdapter; 39import android.os.Bundle; 40import android.os.HandlerThread; 41import android.os.Process; 42import android.provider.Settings; 43import android.support.annotation.VisibleForTesting; 44import android.support.v7.preference.Preference; 45import android.support.v7.preference.PreferenceCategory; 46import android.util.Log; 47import android.view.ContextMenu; 48import android.view.ContextMenu.ContextMenuInfo; 49import android.view.Menu; 50import android.view.MenuItem; 51import android.view.View; 52import android.widget.Toast; 53 54import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 55import com.android.settings.LinkifyUtils; 56import com.android.settings.R; 57import com.android.settings.RestrictedSettingsFragment; 58import com.android.settings.SettingsActivity; 59import com.android.settings.dashboard.SummaryLoader; 60import com.android.settings.location.ScanningSettings; 61import com.android.settings.search.BaseSearchIndexProvider; 62import com.android.settings.search.Indexable; 63import com.android.settings.search.SearchIndexableRaw; 64import com.android.settings.widget.SummaryUpdater.OnSummaryChangeListener; 65import com.android.settings.widget.SwitchBarController; 66import com.android.settings.wifi.details.WifiNetworkDetailsFragment; 67import com.android.settingslib.RestrictedLockUtils; 68import com.android.settingslib.wifi.AccessPoint; 69import com.android.settingslib.wifi.AccessPoint.AccessPointListener; 70import com.android.settingslib.wifi.AccessPointPreference; 71import com.android.settingslib.wifi.WifiTracker; 72import com.android.settingslib.wifi.WifiTrackerFactory; 73 74import java.util.ArrayList; 75import java.util.List; 76 77/** 78 * Two types of UI are provided here. 79 * 80 * The first is for "usual Settings", appearing as any other Setup fragment. 81 * 82 * The second is for Setup Wizard, with a simplified interface that hides the action bar 83 * and menus. 84 */ 85public class WifiSettings extends RestrictedSettingsFragment 86 implements Indexable, WifiTracker.WifiListener, AccessPointListener, 87 WifiDialog.WifiDialogListener { 88 89 private static final String TAG = "WifiSettings"; 90 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); 91 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; 98 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; 103 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"; 108 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"; 115 116 private final Runnable mUpdateAccessPointsRunnable = () -> { 117 updateAccessPointPreferences(); 118 }; 119 private final Runnable mHideProgressBarRunnable = () -> { 120 setProgressBarVisible(false); 121 }; 122 123 protected WifiManager mWifiManager; 124 private WifiManager.ActionListener mConnectListener; 125 private WifiManager.ActionListener mSaveListener; 126 private WifiManager.ActionListener mForgetListener; 127 128 /** 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. 132 */ 133 private boolean mIsRestricted; 134 135 private WifiEnabler mWifiEnabler; 136 // An access point being editted is stored here. 137 private AccessPoint mSelectedAccessPoint; 138 139 private WifiDialog mDialog; 140 private WriteWifiConfigToNfcDialog mWifiToNfcDialog; 141 142 private View mProgressHeader; 143 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 149 // things. 150 public static final String EXTRA_START_CONNECT_SSID = "wifi_start_connect_ssid"; 151 152 // should Next button only be enabled when we have a connection? 153 private boolean mEnableNextOnConnection; 154 155 // Save the dialog details 156 private int mDialogMode; 157 private AccessPoint mDlgAccessPoint; 158 private Bundle mAccessPointSavedState; 159 private Bundle mWifiNfcDialogSavedState; 160 161 private WifiTracker mWifiTracker; 162 private String mOpenSsid; 163 164 private HandlerThread mBgThread; 165 166 private AccessPointPreference.UserBadgeCache mUserBadgeCache; 167 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; 175 176 // For Search 177 private static final String DATA_KEY_REFERENCE = "main_toggle_wifi"; 178 179 /* End of "used in Wifi Setup context" */ 180 181 public WifiSettings() { 182 super(DISALLOW_CONFIG_WIFI); 183 } 184 185 @Override 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); 193 } 194 } 195 196 @Override 197 public void onCreate(Bundle icicle) { 198 super.onCreate(icicle); 199 200 // TODO(b/37429702): Add animations and preference comparator back after initial screen is 201 // loaded (ODR). 202 setAnimationAllowed(false); 203 204 addPreferences(); 205 206 mIsRestricted = isUiRestricted(); 207 208 mBgThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND); 209 mBgThread.start(); 210 } 211 212 private void addPreferences() { 213 addPreferencesFromResource(R.xml.wifi_settings); 214 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); 223 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); 229 230 mUserBadgeCache = new AccessPointPreference.UserBadgeCache(getPackageManager()); 231 } 232 233 @Override 234 public void onDestroy() { 235 mBgThread.quit(); 236 super.onDestroy(); 237 } 238 239 @Override 240 public void onActivityCreated(Bundle savedInstanceState) { 241 super.onActivityCreated(savedInstanceState); 242 243 mWifiTracker = WifiTrackerFactory.create( 244 getActivity(), this, mBgThread.getLooper(), true, true, false); 245 mWifiManager = mWifiTracker.getManager(); 246 247 mConnectListener = new WifiManager.ActionListener() { 248 @Override 249 public void onSuccess() { 250 } 251 @Override 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(); 258 } 259 } 260 }; 261 262 mSaveListener = new WifiManager.ActionListener() { 263 @Override 264 public void onSuccess() { 265 } 266 @Override 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(); 273 } 274 } 275 }; 276 277 mForgetListener = new WifiManager.ActionListener() { 278 @Override 279 public void onSuccess() { 280 } 281 @Override 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(); 288 } 289 } 290 }; 291 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); 297 } 298 299 if (savedInstanceState.containsKey(SAVED_WIFI_NFC_DIALOG_STATE)) { 300 mWifiNfcDialogSavedState = 301 savedInstanceState.getBundle(SAVED_WIFI_NFC_DIALOG_STATE); 302 } 303 } 304 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); 309 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()); 318 } 319 } 320 } 321 322 registerForContextMenu(getListView()); 323 setHasOptionsMenu(true); 324 325 if (intent.hasExtra(EXTRA_START_CONNECT_SSID)) { 326 mOpenSsid = intent.getStringExtra(EXTRA_START_CONNECT_SSID); 327 } 328 } 329 330 @Override 331 public void onDestroyView() { 332 super.onDestroyView(); 333 334 if (mWifiEnabler != null) { 335 mWifiEnabler.teardownSwitchController(); 336 } 337 } 338 339 @Override 340 public void onStart() { 341 super.onStart(); 342 343 // On/off switch is hidden for Setup Wizard (returns null) 344 mWifiEnabler = createWifiEnabler(); 345 346 mWifiTracker.startTracking(); 347 348 if (mIsRestricted) { 349 restrictUi(); 350 return; 351 } 352 353 onWifiStateChanged(mWifiManager.getWifiState()); 354 } 355 356 private void restrictUi() { 357 if (!isUiRestrictedByOnlyAdmin()) { 358 getEmptyTextView().setText(R.string.wifi_empty_list_user_restricted); 359 } 360 getPreferenceScreen().removeAll(); 361 } 362 363 /** 364 * Only update the AP list if there are not any APs currently shown. 365 * 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}. 369 */ 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 375 // WifiTracker. 376 Log.d(TAG, "Did not force update APs due to existing APs displayed"); 377 getView().removeCallbacks(mUpdateAccessPointsRunnable); 378 return; 379 } 380 setProgressBarVisible(true); 381 mWifiTracker.forceUpdate(); 382 if (DEBUG) { 383 Log.d(TAG, "WifiSettings force update APs: " + mWifiTracker.getAccessPoints()); 384 } 385 getView().removeCallbacks(mUpdateAccessPointsRunnable); 386 updateAccessPointPreferences(); 387 } 388 389 /** 390 * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard) 391 */ 392 private WifiEnabler createWifiEnabler() { 393 final SettingsActivity activity = (SettingsActivity) getActivity(); 394 return new WifiEnabler(activity, new SwitchBarController(activity.getSwitchBar()), 395 mMetricsFeatureProvider); 396 } 397 398 @Override 399 public void onResume() { 400 final Activity activity = getActivity(); 401 super.onResume(); 402 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) { 408 restrictUi(); 409 } 410 411 if (mWifiEnabler != null) { 412 mWifiEnabler.resume(activity); 413 } 414 } 415 416 @Override 417 public void onPause() { 418 super.onPause(); 419 if (mWifiEnabler != null) { 420 mWifiEnabler.pause(); 421 } 422 } 423 424 @Override 425 public void onStop() { 426 mWifiTracker.stopTracking(); 427 getView().removeCallbacks(mUpdateAccessPointsRunnable); 428 getView().removeCallbacks(mHideProgressBarRunnable); 429 super.onStop(); 430 } 431 432 @Override 433 public void onActivityResult(int requestCode, int resultCode, Intent data) { 434 super.onActivityResult(requestCode, resultCode, data); 435 436 final boolean formerlyRestricted = mIsRestricted; 437 mIsRestricted = isUiRestricted(); 438 if (formerlyRestricted && !mIsRestricted 439 && getPreferenceScreen().getPreferenceCount() == 0) { 440 // De-restrict the ui 441 addPreferences(); 442 } 443 } 444 445 @Override 446 public int getMetricsCategory() { 447 return MetricsEvent.WIFI; 448 } 449 450 @Override 451 public void onSaveInstanceState(Bundle outState) { 452 super.onSaveInstanceState(outState); 453 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); 461 } 462 } 463 464 if (mWifiToNfcDialog != null && mWifiToNfcDialog.isShowing()) { 465 Bundle savedState = new Bundle(); 466 mWifiToNfcDialog.saveState(savedState); 467 outState.putBundle(SAVED_WIFI_NFC_DIALOG_STATE, savedState); 468 } 469 } 470 471 @Override 472 public boolean onOptionsItemSelected(MenuItem item) { 473 // If the user is not allowed to configure wifi, do not handle menu selections. 474 if (mIsRestricted) { 475 return false; 476 } 477 478 switch (item.getItemId()) { 479 case MENU_ID_WPS_PBC: 480 showDialog(WPS_PBC_DIALOG_ID); 481 return true; 482 case MENU_ID_WPS_PIN: 483 showDialog(WPS_PIN_DIALOG_ID); 484 return true; 485 } 486 return super.onOptionsItemSelected(item); 487 } 488 489 @Override 490 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) { 491 Preference preference = (Preference) view.getTag(); 492 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); 499 } 500 501 WifiConfiguration config = mSelectedAccessPoint.getConfig(); 502 // Some configs are ineditable 503 if (isEditabilityLockedDown(getActivity(), config)) { 504 return; 505 } 506 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); 512 } 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); 520 } 521 } 522 } 523 } 524 525 @Override 526 public boolean onContextItemSelected(MenuItem item) { 527 if (mSelectedAccessPoint == null) { 528 return super.onContextItemSelected(item); 529 } 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); 539 } else { 540 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT); 541 } 542 return true; 543 } 544 case MENU_ID_FORGET: { 545 forget(); 546 return true; 547 } 548 case MENU_ID_MODIFY: { 549 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_MODIFY); 550 return true; 551 } 552 case MENU_ID_WRITE_NFC: 553 showDialog(WRITE_NFC_DIALOG_ID); 554 return true; 555 556 } 557 return super.onContextItemSelected(item); 558 } 559 560 @Override 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); 566 } 567 568 if (preference instanceof LongPressAccessPointPreference) { 569 mSelectedAccessPoint = ((LongPressAccessPointPreference) preference).getAccessPoint(); 570 if (mSelectedAccessPoint == null) { 571 return false; 572 } 573 if (mSelectedAccessPoint.isActive()) { 574 return super.onPreferenceTreeClick(preference); 575 } 576 /** 577 * Bypass dialog and connect to unsecured networks, or previously connected saved 578 * networks, or Passpoint provided networks. 579 */ 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 */); 592 } else { 593 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT); 594 } 595 } else if (preference == mAddPreference) { 596 onAddNetworkPressed(); 597 } else { 598 return super.onPreferenceTreeClick(preference); 599 } 600 return true; 601 } 602 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())); 609 return; 610 } 611 } 612 613 if (mDialog != null) { 614 removeDialog(WIFI_DIALOG_ID); 615 mDialog = null; 616 } 617 618 // Save the access point and edit mode 619 mDlgAccessPoint = accessPoint; 620 mDialogMode = dialogMode; 621 622 showDialog(WIFI_DIALOG_ID); 623 } 624 625 @Override 626 public Dialog onCreateDialog(int dialogId) { 627 switch (dialogId) { 628 case WIFI_DIALOG_ID: 629 if (mDlgAccessPoint == null && mAccessPointSavedState == null) { 630 // add new network 631 mDialog = WifiDialog 632 .createFullscreen(getActivity(), this, mDlgAccessPoint, mDialogMode); 633 } else { 634 // modify network 635 if (mDlgAccessPoint == null) { 636 // restore AP from save state 637 mDlgAccessPoint = new AccessPoint(getActivity(), mAccessPointSavedState); 638 // Reset the saved access point data 639 mAccessPointSavedState = null; 640 } 641 mDialog = WifiDialog 642 .createModal(getActivity(), this, mDlgAccessPoint, mDialogMode); 643 } 644 645 mSelectedAccessPoint = mDlgAccessPoint; 646 return mDialog; 647 case WPS_PBC_DIALOG_ID: 648 return new WpsDialog(getActivity(), WpsInfo.PBC); 649 case WPS_PIN_DIALOG_ID: 650 return new WpsDialog(getActivity(), WpsInfo.DISPLAY); 651 case WRITE_NFC_DIALOG_ID: 652 if (mSelectedAccessPoint != null) { 653 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog( 654 getActivity(), 655 mSelectedAccessPoint.getSecurity(), 656 new WifiManagerWrapper(mWifiManager)); 657 } else if (mWifiNfcDialogSavedState != null) { 658 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(getActivity(), 659 mWifiNfcDialogSavedState, new WifiManagerWrapper(mWifiManager)); 660 } 661 662 return mWifiToNfcDialog; 663 } 664 return super.onCreateDialog(dialogId); 665 } 666 667 @Override 668 public int getDialogMetricsCategory(int dialogId) { 669 switch (dialogId) { 670 case WIFI_DIALOG_ID: 671 return MetricsEvent.DIALOG_WIFI_AP_EDIT; 672 case WPS_PBC_DIALOG_ID: 673 return MetricsEvent.DIALOG_WIFI_PBC; 674 case WPS_PIN_DIALOG_ID: 675 return MetricsEvent.DIALOG_WIFI_PIN; 676 case WRITE_NFC_DIALOG_ID: 677 return MetricsEvent.DIALOG_WIFI_WRITE_NFC; 678 default: 679 return 0; 680 } 681 } 682 683 /** 684 * Called to indicate the list of AccessPoints has been updated and 685 * getAccessPoints should be called to get the latest information. 686 */ 687 @Override 688 public void onAccessPointsChanged() { 689 Log.d(TAG, "onAccessPointsChanged (WifiTracker) callback initiated"); 690 updateAccessPointsDelayed(); 691 } 692 693 /** 694 * Updates access points from {@link WifiManager#getScanResults()}. Adds a delay to have 695 * progress bar displayed before starting to modify APs. 696 */ 697 private void updateAccessPointsDelayed() { 698 // Safeguard from some delayed event handling 699 if (getActivity() != null && !mIsRestricted && mWifiManager.isWifiEnabled()) { 700 setProgressBarVisible(true); 701 getView().postDelayed(mUpdateAccessPointsRunnable, 300 /* delay milliseconds */); 702 } 703 } 704 705 /** Called when the state of Wifi has changed. */ 706 @Override 707 public void onWifiStateChanged(int state) { 708 if (mIsRestricted) { 709 return; 710 } 711 712 final int wifiState = mWifiManager.getWifiState(); 713 switch (wifiState) { 714 case WifiManager.WIFI_STATE_ENABLED: 715 conditionallyForceUpdateAPs(); 716 break; 717 718 case WifiManager.WIFI_STATE_ENABLING: 719 removeConnectedAccessPointPreference(); 720 mAccessPointsPreferenceCategory.removeAll(); 721 addMessagePreference(R.string.wifi_starting); 722 setProgressBarVisible(true); 723 break; 724 725 case WifiManager.WIFI_STATE_DISABLING: 726 removeConnectedAccessPointPreference(); 727 mAccessPointsPreferenceCategory.removeAll(); 728 addMessagePreference(R.string.wifi_stopping); 729 break; 730 731 case WifiManager.WIFI_STATE_DISABLED: 732 setOffMessage(); 733 setAdditionalSettingsSummaries(); 734 setProgressBarVisible(false); 735 break; 736 } 737 } 738 739 /** 740 * Called when the connection state of wifi has changed and isConnected 741 * should be called to get the updated state. 742 */ 743 @Override 744 public void onConnectedChanged() { 745 updateAccessPointsDelayed(); 746 changeNextButtonState(mWifiTracker.isConnected()); 747 } 748 749 /** Helper method to return whether an AccessPoint is disabled due to a wrong password */ 750 private static boolean isDisabledByWrongPassword(AccessPoint accessPoint) { 751 WifiConfiguration config = accessPoint.getConfig(); 752 if (config == null) { 753 return false; 754 } 755 WifiConfiguration.NetworkSelectionStatus networkStatus = 756 config.getNetworkSelectionStatus(); 757 if (networkStatus == null || networkStatus.isNetworkEnabled()) { 758 return false; 759 } 760 int reason = networkStatus.getNetworkSelectionDisableReason(); 761 return WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD == reason; 762 } 763 764 private void updateAccessPointPreferences() { 765 // in case state has changed 766 if (!mWifiManager.isWifiEnabled()) { 767 return; 768 } 769 // AccessPoints are sorted by the WifiTracker 770 final List<AccessPoint> accessPoints = mWifiTracker.getAccessPoints(); 771 if (DEBUG) { 772 Log.d(TAG, "updateAccessPoints called for: " + accessPoints); 773 } 774 775 boolean hasAvailableAccessPoints = false; 776 mAccessPointsPreferenceCategory.removePreference(mStatusMessagePreference); 777 cacheRemoveAllPrefs(mAccessPointsPreferenceCategory); 778 779 int index = 780 configureConnectedAccessPointPreferenceCategory(accessPoints) ? 1 : 0; 781 int numAccessPoints = accessPoints.size(); 782 for (; index < numAccessPoints; index++) { 783 AccessPoint accessPoint = accessPoints.get(index); 784 // Ignore access points that are out of range. 785 if (accessPoint.isReachable()) { 786 String key = AccessPointPreference.generatePreferenceKey(accessPoint); 787 hasAvailableAccessPoints = true; 788 LongPressAccessPointPreference pref = 789 (LongPressAccessPointPreference) getCachedPreference(key); 790 if (pref != null) { 791 pref.setOrder(index); 792 continue; 793 } 794 LongPressAccessPointPreference preference = 795 createLongPressActionPointPreference(accessPoint); 796 preference.setKey(key); 797 preference.setOrder(index); 798 if (mOpenSsid != null && mOpenSsid.equals(accessPoint.getSsidStr()) 799 && accessPoint.getSecurity() != AccessPoint.SECURITY_NONE) { 800 if (!accessPoint.isSaved() || isDisabledByWrongPassword(accessPoint)) { 801 onPreferenceTreeClick(preference); 802 mOpenSsid = null; 803 } 804 } 805 mAccessPointsPreferenceCategory.addPreference(preference); 806 accessPoint.setListener(WifiSettings.this); 807 preference.refresh(); 808 } 809 } 810 removeCachedPrefs(mAccessPointsPreferenceCategory); 811 mAddPreference.setOrder(index); 812 mAccessPointsPreferenceCategory.addPreference(mAddPreference); 813 setAdditionalSettingsSummaries(); 814 815 if (!hasAvailableAccessPoints) { 816 setProgressBarVisible(true); 817 Preference pref = new Preference(getPrefContext()); 818 pref.setSelectable(false); 819 pref.setSummary(R.string.wifi_empty_list_wifi_on); 820 pref.setOrder(index++); 821 pref.setKey(PREF_KEY_EMPTY_WIFI_LIST); 822 mAccessPointsPreferenceCategory.addPreference(pref); 823 } else { 824 // Continuing showing progress bar for an additional delay to overlap with animation 825 getView().postDelayed(mHideProgressBarRunnable, 1700 /* delay millis */); 826 } 827 } 828 829 @NonNull 830 private LongPressAccessPointPreference createLongPressActionPointPreference( 831 AccessPoint accessPoint) { 832 return new LongPressAccessPointPreference(accessPoint, getPrefContext(), mUserBadgeCache, 833 false, R.drawable.ic_wifi_signal_0, this); 834 } 835 836 /** 837 * Configure the ConnectedAccessPointPreferenceCategory and return true if the Category was 838 * shown. 839 */ 840 private boolean configureConnectedAccessPointPreferenceCategory( 841 List<AccessPoint> accessPoints) { 842 if (accessPoints.size() == 0) { 843 removeConnectedAccessPointPreference(); 844 return false; 845 } 846 847 AccessPoint connectedAp = accessPoints.get(0); 848 if (!connectedAp.isActive()) { 849 removeConnectedAccessPointPreference(); 850 return false; 851 } 852 853 // Is the preference category empty? 854 if (mConnectedAccessPointPreferenceCategory.getPreferenceCount() == 0) { 855 addConnectedAccessPointPreference(connectedAp); 856 return true; 857 } 858 859 // Is the previous currently connected SSID different from the new one? 860 AccessPointPreference preference = (AccessPointPreference) 861 (mConnectedAccessPointPreferenceCategory.getPreference(0)); 862 // The AccessPoints need to be the same reference to ensure that updates are reflected 863 // in the UI. 864 if (preference.getAccessPoint() != connectedAp) { 865 removeConnectedAccessPointPreference(); 866 addConnectedAccessPointPreference(connectedAp); 867 return true; 868 } 869 870 // Else same AP is connected, simply refresh the connected access point preference 871 // (first and only access point in this category). 872 ((LongPressAccessPointPreference) mConnectedAccessPointPreferenceCategory.getPreference(0)) 873 .refresh(); 874 return true; 875 } 876 877 /** 878 * Creates a Preference for the given {@link AccessPoint} and adds it to the 879 * {@link #mConnectedAccessPointPreferenceCategory}. 880 */ 881 private void addConnectedAccessPointPreference(AccessPoint connectedAp) { 882 String key = connectedAp.getBssid(); 883 LongPressAccessPointPreference pref = (LongPressAccessPointPreference) 884 getCachedPreference(key); 885 if (pref == null) { 886 pref = createLongPressActionPointPreference(connectedAp); 887 } 888 889 // Save the state of the current access point in the bundle so that we can restore it 890 // in the Wifi Network Details Fragment 891 pref.getAccessPoint().saveWifiState(pref.getExtras()); 892 pref.setFragment(WifiNetworkDetailsFragment.class.getName()); 893 pref.refresh(); 894 895 mConnectedAccessPointPreferenceCategory.addPreference(pref); 896 mConnectedAccessPointPreferenceCategory.setVisible(true); 897 } 898 899 /** Removes all preferences and hide the {@link #mConnectedAccessPointPreferenceCategory}. */ 900 private void removeConnectedAccessPointPreference() { 901 mConnectedAccessPointPreferenceCategory.removeAll(); 902 mConnectedAccessPointPreferenceCategory.setVisible(false); 903 } 904 905 private void setAdditionalSettingsSummaries() { 906 mAdditionalSettingsPreferenceCategory.addPreference(mConfigureWifiSettingsPreference); 907 final int defaultWakeupAvailable = getResources().getInteger( 908 com.android.internal.R.integer.config_wifi_wakeup_available); 909 boolean wifiWakeupAvailable = Settings.Global.getInt( 910 getContentResolver(), Settings.Global.WIFI_WAKEUP_AVAILABLE, defaultWakeupAvailable) 911 == 1; 912 if (wifiWakeupAvailable) { 913 boolean wifiWakeupEnabled = Settings.Global.getInt( 914 getContentResolver(), Settings.Global.WIFI_WAKEUP_ENABLED, 0) == 1; 915 mConfigureWifiSettingsPreference.setSummary(getString(wifiWakeupEnabled 916 ? R.string.wifi_configure_settings_preference_summary_wakeup_on 917 : R.string.wifi_configure_settings_preference_summary_wakeup_off)); 918 } 919 int numSavedNetworks = mWifiTracker.getNumSavedNetworks(); 920 if (numSavedNetworks > 0) { 921 mAdditionalSettingsPreferenceCategory.addPreference(mSavedNetworksPreference); 922 mSavedNetworksPreference.setSummary( 923 getResources().getQuantityString(R.plurals.wifi_saved_access_points_summary, 924 numSavedNetworks, numSavedNetworks)); 925 } else { 926 mAdditionalSettingsPreferenceCategory.removePreference(mSavedNetworksPreference); 927 } 928 } 929 930 private void setOffMessage() { 931 final CharSequence title = getText(R.string.wifi_empty_list_wifi_off); 932 // Don't use WifiManager.isScanAlwaysAvailable() to check the Wi-Fi scanning mode. Instead, 933 // read the system settings directly. Because when the device is in Airplane mode, even if 934 // Wi-Fi scanning mode is on, WifiManager.isScanAlwaysAvailable() still returns "off". 935 final boolean wifiScanningMode = Settings.Global.getInt(getActivity().getContentResolver(), 936 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1; 937 final CharSequence description = wifiScanningMode ? getText(R.string.wifi_scan_notify_text) 938 : getText(R.string.wifi_scan_notify_text_scanning_off); 939 final LinkifyUtils.OnClickListener clickListener = new LinkifyUtils.OnClickListener() { 940 @Override 941 public void onClick() { 942 final SettingsActivity activity = (SettingsActivity) getActivity(); 943 activity.startPreferencePanel(WifiSettings.this, 944 ScanningSettings.class.getName(), 945 null, R.string.location_scanning_screen_title, null, null, 0); 946 } 947 }; 948 mStatusMessagePreference.setText(title, description, clickListener); 949 removeConnectedAccessPointPreference(); 950 mAccessPointsPreferenceCategory.removeAll(); 951 mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference); 952 } 953 954 private void addMessagePreference(int messageId) { 955 mStatusMessagePreference.setTitle(messageId); 956 removeConnectedAccessPointPreference(); 957 mAccessPointsPreferenceCategory.removeAll(); 958 mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference); 959 } 960 961 protected void setProgressBarVisible(boolean visible) { 962 if (mProgressHeader != null) { 963 mProgressHeader.setVisibility(visible ? View.VISIBLE : View.GONE); 964 } 965 } 966 967 /** 968 * Renames/replaces "Next" button when appropriate. "Next" button usually exists in 969 * Wifi setup screens, not in usual wifi settings screen. 970 * 971 * @param enabled true when the device is connected to a wifi network. 972 */ 973 private void changeNextButtonState(boolean enabled) { 974 if (mEnableNextOnConnection && hasNextButton()) { 975 getNextButton().setEnabled(enabled); 976 } 977 } 978 979 @Override 980 public void onForget(WifiDialog dialog) { 981 forget(); 982 } 983 984 @Override 985 public void onSubmit(WifiDialog dialog) { 986 if (mDialog != null) { 987 submit(mDialog.getController()); 988 } 989 } 990 991 /* package */ void submit(WifiConfigController configController) { 992 993 final WifiConfiguration config = configController.getConfig(); 994 995 if (config == null) { 996 if (mSelectedAccessPoint != null 997 && mSelectedAccessPoint.isSaved()) { 998 connect(mSelectedAccessPoint.getConfig(), true /* isSavedNetwork */); 999 } 1000 } else if (configController.getMode() == WifiConfigUiBase.MODE_MODIFY) { 1001 mWifiManager.save(config, mSaveListener); 1002 } else { 1003 mWifiManager.save(config, mSaveListener); 1004 if (mSelectedAccessPoint != null) { // Not an "Add network" 1005 connect(config, false /* isSavedNetwork */); 1006 } 1007 } 1008 1009 mWifiTracker.resumeScanning(); 1010 } 1011 1012 /* package */ void forget() { 1013 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_FORGET); 1014 if (!mSelectedAccessPoint.isSaved()) { 1015 if (mSelectedAccessPoint.getNetworkInfo() != null && 1016 mSelectedAccessPoint.getNetworkInfo().getState() != State.DISCONNECTED) { 1017 // Network is active but has no network ID - must be ephemeral. 1018 mWifiManager.disableEphemeralNetwork( 1019 AccessPoint.convertToQuotedString(mSelectedAccessPoint.getSsidStr())); 1020 } else { 1021 // Should not happen, but a monkey seems to trigger it 1022 Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig()); 1023 return; 1024 } 1025 } else if (mSelectedAccessPoint.getConfig().isPasspoint()) { 1026 mWifiManager.removePasspointConfiguration(mSelectedAccessPoint.getConfig().FQDN); 1027 } else { 1028 mWifiManager.forget(mSelectedAccessPoint.getConfig().networkId, mForgetListener); 1029 } 1030 1031 mWifiTracker.resumeScanning(); 1032 1033 // We need to rename/replace "Next" button in wifi setup context. 1034 changeNextButtonState(false); 1035 } 1036 1037 protected void connect(final WifiConfiguration config, boolean isSavedNetwork) { 1038 // Log subtype if configuration is a saved network. 1039 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT, 1040 isSavedNetwork); 1041 mWifiManager.connect(config, mConnectListener); 1042 scrollToPreference(mConnectedAccessPointPreferenceCategory); 1043 } 1044 1045 protected void connect(final int networkId, boolean isSavedNetwork) { 1046 // Log subtype if configuration is a saved network. 1047 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT, 1048 isSavedNetwork); 1049 mWifiManager.connect(networkId, mConnectListener); 1050 } 1051 1052 /** 1053 * Called when "add network" button is pressed. 1054 */ 1055 /* package */ void onAddNetworkPressed() { 1056 mMetricsFeatureProvider.action(getActivity(), MetricsEvent.ACTION_WIFI_ADD_NETWORK); 1057 // No exact access point is selected. 1058 mSelectedAccessPoint = null; 1059 showDialog(null, WifiConfigUiBase.MODE_CONNECT); 1060 } 1061 1062 @Override 1063 protected int getHelpResource() { 1064 return R.string.help_url_wifi; 1065 } 1066 1067 @Override 1068 public void onAccessPointChanged(final AccessPoint accessPoint) { 1069 Log.d(TAG, "onAccessPointChanged (singular) callback initiated"); 1070 View view = getView(); 1071 if (view != null) { 1072 view.post(new Runnable() { 1073 @Override 1074 public void run() { 1075 Object tag = accessPoint.getTag(); 1076 if (tag != null) { 1077 ((LongPressAccessPointPreference) tag).refresh(); 1078 } 1079 } 1080 }); 1081 } 1082 } 1083 1084 @Override 1085 public void onLevelChanged(AccessPoint accessPoint) { 1086 ((LongPressAccessPointPreference) accessPoint.getTag()).onLevelChanged(); 1087 } 1088 1089 public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER = 1090 new BaseSearchIndexProvider() { 1091 @Override 1092 public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) { 1093 final List<SearchIndexableRaw> result = new ArrayList<>(); 1094 final Resources res = context.getResources(); 1095 1096 // Add fragment title 1097 SearchIndexableRaw data = new SearchIndexableRaw(context); 1098 data.title = res.getString(R.string.wifi_settings); 1099 data.screenTitle = res.getString(R.string.wifi_settings); 1100 data.keywords = res.getString(R.string.keywords_wifi); 1101 data.key = DATA_KEY_REFERENCE; 1102 result.add(data); 1103 1104 // Add saved Wi-Fi access points 1105 final List<AccessPoint> accessPoints = 1106 WifiTracker.getCurrentAccessPoints(context, true, false, false); 1107 for (AccessPoint accessPoint : accessPoints) { 1108 data = new SearchIndexableRaw(context); 1109 data.title = accessPoint.getSsidStr(); 1110 data.screenTitle = res.getString(R.string.wifi_settings); 1111 data.enabled = enabled; 1112 result.add(data); 1113 } 1114 1115 return result; 1116 } 1117 }; 1118 1119 /** 1120 * Returns true if the config is not editable through Settings. 1121 * @param context Context of caller 1122 * @param config The WiFi config. 1123 * @return true if the config is not editable through Settings. 1124 */ 1125 static boolean isEditabilityLockedDown(Context context, WifiConfiguration config) { 1126 return !canModifyNetwork(context, config); 1127 } 1128 1129 /** 1130 * This method is a stripped version of WifiConfigStore.canModifyNetwork. 1131 * TODO: refactor to have only one method. 1132 * @param context Context of caller 1133 * @param config The WiFi config. 1134 * @return true if Settings can modify the config. 1135 */ 1136 static boolean canModifyNetwork(Context context, WifiConfiguration config) { 1137 if (config == null) { 1138 return true; 1139 } 1140 1141 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService( 1142 Context.DEVICE_POLICY_SERVICE); 1143 1144 // Check if device has DPM capability. If it has and dpm is still null, then we 1145 // treat this case with suspicion and bail out. 1146 final PackageManager pm = context.getPackageManager(); 1147 if (pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN) && dpm == null) { 1148 return false; 1149 } 1150 1151 boolean isConfigEligibleForLockdown = false; 1152 if (dpm != null) { 1153 final ComponentName deviceOwner = dpm.getDeviceOwnerComponentOnAnyUser(); 1154 if (deviceOwner != null) { 1155 final int deviceOwnerUserId = dpm.getDeviceOwnerUserId(); 1156 try { 1157 final int deviceOwnerUid = pm.getPackageUidAsUser(deviceOwner.getPackageName(), 1158 deviceOwnerUserId); 1159 isConfigEligibleForLockdown = deviceOwnerUid == config.creatorUid; 1160 } catch (NameNotFoundException e) { 1161 // don't care 1162 } 1163 } 1164 } 1165 if (!isConfigEligibleForLockdown) { 1166 return true; 1167 } 1168 1169 final ContentResolver resolver = context.getContentResolver(); 1170 final boolean isLockdownFeatureEnabled = Settings.Global.getInt(resolver, 1171 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) != 0; 1172 return !isLockdownFeatureEnabled; 1173 } 1174 1175 private static class SummaryProvider 1176 implements SummaryLoader.SummaryProvider, OnSummaryChangeListener { 1177 1178 private final Context mContext; 1179 private final SummaryLoader mSummaryLoader; 1180 1181 @VisibleForTesting 1182 WifiSummaryUpdater mSummaryHelper; 1183 1184 public SummaryProvider(Context context, SummaryLoader summaryLoader) { 1185 mContext = context; 1186 mSummaryLoader = summaryLoader; 1187 mSummaryHelper = new WifiSummaryUpdater(mContext, this); 1188 } 1189 1190 1191 @Override 1192 public void setListening(boolean listening) { 1193 mSummaryHelper.register(listening); 1194 } 1195 1196 @Override 1197 public void onSummaryChanged(String summary) { 1198 mSummaryLoader.setSummary(this, summary); 1199 } 1200 } 1201 1202 public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY 1203 = new SummaryLoader.SummaryProviderFactory() { 1204 @Override 1205 public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity, 1206 SummaryLoader summaryLoader) { 1207 return new SummaryProvider(activity, summaryLoader); 1208 } 1209 }; 1210} 1211