WifiSettings.java revision a620f52e647b531698ab5ec8fad8871d963b7599
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 android.app.Activity; 20import android.app.Dialog; 21import android.app.admin.DevicePolicyManager; 22import android.content.BroadcastReceiver; 23import android.content.ComponentName; 24import android.content.ContentResolver; 25import android.content.Context; 26import android.content.Intent; 27import android.content.IntentFilter; 28import android.content.pm.PackageManager; 29import android.content.pm.PackageManager.NameNotFoundException; 30import android.content.res.Resources; 31import android.net.ConnectivityManager; 32import android.net.NetworkInfo; 33import android.net.NetworkInfo.State; 34import android.net.wifi.WifiConfiguration; 35import android.net.wifi.WifiManager; 36import android.net.wifi.WpsInfo; 37import android.nfc.NfcAdapter; 38import android.os.Bundle; 39import android.os.HandlerThread; 40import android.os.Process; 41import android.provider.Settings; 42import android.support.v7.preference.Preference; 43import android.support.v7.preference.PreferenceViewHolder; 44import android.text.Spannable; 45import android.text.TextUtils; 46import android.text.style.TextAppearanceSpan; 47import android.util.Log; 48import android.view.ContextMenu; 49import android.view.ContextMenu.ContextMenuInfo; 50import android.view.Menu; 51import android.view.MenuInflater; 52import android.view.MenuItem; 53import android.view.View; 54import android.widget.ProgressBar; 55import android.widget.TextView; 56import android.widget.TextView.BufferType; 57import android.widget.Toast; 58 59import com.android.internal.logging.MetricsLogger; 60import com.android.internal.logging.MetricsProto.MetricsEvent; 61import com.android.settings.LinkifyUtils; 62import com.android.settings.R; 63import com.android.settings.RestrictedSettingsFragment; 64import com.android.settings.SettingsActivity; 65import com.android.settings.dashboard.SummaryLoader; 66import com.android.settings.location.ScanningSettings; 67import com.android.settings.search.BaseSearchIndexProvider; 68import com.android.settings.search.Indexable; 69import com.android.settings.search.SearchIndexableRaw; 70import com.android.settingslib.RestrictedLockUtils; 71import com.android.settingslib.wifi.AccessPoint; 72import com.android.settingslib.wifi.AccessPoint.AccessPointListener; 73import com.android.settingslib.wifi.AccessPointPreference; 74import com.android.settingslib.wifi.WifiStatusTracker; 75import com.android.settingslib.wifi.WifiTracker; 76 77import java.util.ArrayList; 78import java.util.Collection; 79import java.util.List; 80 81import static android.os.UserManager.DISALLOW_CONFIG_WIFI; 82 83/** 84 * Two types of UI are provided here. 85 * 86 * The first is for "usual Settings", appearing as any other Setup fragment. 87 * 88 * The second is for Setup Wizard, with a simplified interface that hides the action bar 89 * and menus. 90 */ 91public class WifiSettings extends RestrictedSettingsFragment 92 implements Indexable, WifiTracker.WifiListener, AccessPointListener, 93 WifiDialog.WifiDialogListener { 94 95 private static final String TAG = "WifiSettings"; 96 97 /* package */ static final int MENU_ID_WPS_PBC = Menu.FIRST; 98 private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1; 99 private static final int MENU_ID_ADVANCED = Menu.FIRST + 4; 100 private static final int MENU_ID_SCAN = Menu.FIRST + 5; 101 private static final int MENU_ID_CONNECT = Menu.FIRST + 6; 102 private static final int MENU_ID_FORGET = Menu.FIRST + 7; 103 private static final int MENU_ID_MODIFY = Menu.FIRST + 8; 104 private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9; 105 private static final int MENU_ID_CONFIGURE = Menu.FIRST + 10; 106 107 public static final int WIFI_DIALOG_ID = 1; 108 /* package */ static final int WPS_PBC_DIALOG_ID = 2; 109 private static final int WPS_PIN_DIALOG_ID = 3; 110 private static final int WRITE_NFC_DIALOG_ID = 6; 111 112 // Instance state keys 113 private static final String SAVE_DIALOG_MODE = "dialog_mode"; 114 private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state"; 115 private static final String SAVED_WIFI_NFC_DIALOG_STATE = "wifi_nfc_dlg_state"; 116 117 private static final String PREF_KEY_EMPTY_WIFI_LIST = "wifi_empty_list"; 118 119 protected WifiManager mWifiManager; 120 private WifiManager.ActionListener mConnectListener; 121 private WifiManager.ActionListener mSaveListener; 122 private WifiManager.ActionListener mForgetListener; 123 124 private WifiEnabler mWifiEnabler; 125 // An access point being editted is stored here. 126 private AccessPoint mSelectedAccessPoint; 127 128 private WifiDialog mDialog; 129 private WriteWifiConfigToNfcDialog mWifiToNfcDialog; 130 131 private ProgressBar mProgressHeader; 132 133 // this boolean extra specifies whether to disable the Next button when not connected. Used by 134 // account creation outside of setup wizard. 135 private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect"; 136 // This string extra specifies a network to open the connect dialog on, so the user can enter 137 // network credentials. This is used by quick settings for secured networks. 138 private static final String EXTRA_START_CONNECT_SSID = "wifi_start_connect_ssid"; 139 140 // should Next button only be enabled when we have a connection? 141 private boolean mEnableNextOnConnection; 142 143 // Save the dialog details 144 private int mDialogMode; 145 private AccessPoint mDlgAccessPoint; 146 private Bundle mAccessPointSavedState; 147 private Bundle mWifiNfcDialogSavedState; 148 149 private WifiTracker mWifiTracker; 150 private String mOpenSsid; 151 152 private HandlerThread mBgThread; 153 154 private AccessPointPreference.UserBadgeCache mUserBadgeCache; 155 private Preference mAddPreference; 156 157 private MenuItem mScanMenuItem; 158 159 /* End of "used in Wifi Setup context" */ 160 161 public WifiSettings() { 162 super(DISALLOW_CONFIG_WIFI); 163 } 164 165 @Override 166 public void onViewCreated(View view, Bundle savedInstanceState) { 167 super.onViewCreated(view, savedInstanceState); 168 final Activity activity = getActivity(); 169 if (activity != null) { 170 mProgressHeader = (ProgressBar) setPinnedHeaderView(R.layout.wifi_progress_header); 171 setProgressBarVisible(false); 172 } 173 } 174 175 @Override 176 public void onCreate(Bundle icicle) { 177 super.onCreate(icicle); 178 addPreferencesFromResource(R.xml.wifi_settings); 179 mAddPreference = new Preference(getContext()); 180 mAddPreference.setIcon(R.drawable.ic_menu_add_inset); 181 mAddPreference.setTitle(R.string.wifi_add_network); 182 183 mUserBadgeCache = new AccessPointPreference.UserBadgeCache(getPackageManager()); 184 185 mBgThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND); 186 mBgThread.start(); 187 } 188 189 @Override 190 public void onDestroy() { 191 mBgThread.quit(); 192 super.onDestroy(); 193 } 194 195 @Override 196 public void onActivityCreated(Bundle savedInstanceState) { 197 super.onActivityCreated(savedInstanceState); 198 199 mWifiTracker = 200 new WifiTracker(getActivity(), this, mBgThread.getLooper(), true, true, false); 201 mWifiManager = mWifiTracker.getManager(); 202 203 mConnectListener = new WifiManager.ActionListener() { 204 @Override 205 public void onSuccess() { 206 } 207 @Override 208 public void onFailure(int reason) { 209 Activity activity = getActivity(); 210 if (activity != null) { 211 Toast.makeText(activity, 212 R.string.wifi_failed_connect_message, 213 Toast.LENGTH_SHORT).show(); 214 } 215 } 216 }; 217 218 mSaveListener = new WifiManager.ActionListener() { 219 @Override 220 public void onSuccess() { 221 } 222 @Override 223 public void onFailure(int reason) { 224 Activity activity = getActivity(); 225 if (activity != null) { 226 Toast.makeText(activity, 227 R.string.wifi_failed_save_message, 228 Toast.LENGTH_SHORT).show(); 229 } 230 } 231 }; 232 233 mForgetListener = new WifiManager.ActionListener() { 234 @Override 235 public void onSuccess() { 236 } 237 @Override 238 public void onFailure(int reason) { 239 Activity activity = getActivity(); 240 if (activity != null) { 241 Toast.makeText(activity, 242 R.string.wifi_failed_forget_message, 243 Toast.LENGTH_SHORT).show(); 244 } 245 } 246 }; 247 248 if (savedInstanceState != null) { 249 mDialogMode = savedInstanceState.getInt(SAVE_DIALOG_MODE); 250 if (savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) { 251 mAccessPointSavedState = 252 savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE); 253 } 254 255 if (savedInstanceState.containsKey(SAVED_WIFI_NFC_DIALOG_STATE)) { 256 mWifiNfcDialogSavedState = 257 savedInstanceState.getBundle(SAVED_WIFI_NFC_DIALOG_STATE); 258 } 259 } 260 261 // if we're supposed to enable/disable the Next button based on our current connection 262 // state, start it off in the right state 263 Intent intent = getActivity().getIntent(); 264 mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false); 265 266 if (mEnableNextOnConnection) { 267 if (hasNextButton()) { 268 final ConnectivityManager connectivity = (ConnectivityManager) 269 getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 270 if (connectivity != null) { 271 NetworkInfo info = connectivity.getNetworkInfo( 272 ConnectivityManager.TYPE_WIFI); 273 changeNextButtonState(info.isConnected()); 274 } 275 } 276 } 277 278 registerForContextMenu(getListView()); 279 setHasOptionsMenu(true); 280 281 if (intent.hasExtra(EXTRA_START_CONNECT_SSID)) { 282 mOpenSsid = intent.getStringExtra(EXTRA_START_CONNECT_SSID); 283 onAccessPointsChanged(); 284 } 285 } 286 287 @Override 288 public void onDestroyView() { 289 super.onDestroyView(); 290 291 if (mWifiEnabler != null) { 292 mWifiEnabler.teardownSwitchBar(); 293 } 294 } 295 296 @Override 297 public void onStart() { 298 super.onStart(); 299 300 // On/off switch is hidden for Setup Wizard (returns null) 301 mWifiEnabler = createWifiEnabler(); 302 } 303 304 /** 305 * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard) 306 */ 307 /* package */ WifiEnabler createWifiEnabler() { 308 final SettingsActivity activity = (SettingsActivity) getActivity(); 309 return new WifiEnabler(activity, activity.getSwitchBar()); 310 } 311 312 @Override 313 public void onResume() { 314 final Activity activity = getActivity(); 315 super.onResume(); 316 removePreference("dummy"); 317 if (mWifiEnabler != null) { 318 mWifiEnabler.resume(activity); 319 } 320 321 mWifiTracker.startTracking(); 322 activity.invalidateOptionsMenu(); 323 } 324 325 @Override 326 public void onPause() { 327 super.onPause(); 328 if (mWifiEnabler != null) { 329 mWifiEnabler.pause(); 330 } 331 332 mWifiTracker.stopTracking(); 333 } 334 335 @Override 336 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 337 // If the user is not allowed to configure wifi, do not show the menu. 338 if (isUiRestricted()) return; 339 340 addOptionsMenuItems(menu); 341 super.onCreateOptionsMenu(menu, inflater); 342 } 343 344 /** 345 * @param menu 346 */ 347 void addOptionsMenuItems(Menu menu) { 348 final boolean wifiIsEnabled = mWifiTracker.isWifiEnabled(); 349 mScanMenuItem = menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.menu_stats_refresh); 350 mScanMenuItem.setEnabled(wifiIsEnabled) 351 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 352 menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced) 353 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 354 menu.add(Menu.NONE, MENU_ID_CONFIGURE, 0, R.string.wifi_menu_configure) 355 .setIcon(R.drawable.ic_settings_24dp) 356 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 357 } 358 359 @Override 360 protected int getMetricsCategory() { 361 return MetricsEvent.WIFI; 362 } 363 364 @Override 365 public void onSaveInstanceState(Bundle outState) { 366 super.onSaveInstanceState(outState); 367 368 // If the dialog is showing, save its state. 369 if (mDialog != null && mDialog.isShowing()) { 370 outState.putInt(SAVE_DIALOG_MODE, mDialogMode); 371 if (mDlgAccessPoint != null) { 372 mAccessPointSavedState = new Bundle(); 373 mDlgAccessPoint.saveWifiState(mAccessPointSavedState); 374 outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState); 375 } 376 } 377 378 if (mWifiToNfcDialog != null && mWifiToNfcDialog.isShowing()) { 379 Bundle savedState = new Bundle(); 380 mWifiToNfcDialog.saveState(savedState); 381 outState.putBundle(SAVED_WIFI_NFC_DIALOG_STATE, savedState); 382 } 383 } 384 385 @Override 386 public boolean onOptionsItemSelected(MenuItem item) { 387 // If the user is not allowed to configure wifi, do not handle menu selections. 388 if (isUiRestricted()) return false; 389 390 switch (item.getItemId()) { 391 case MENU_ID_WPS_PBC: 392 showDialog(WPS_PBC_DIALOG_ID); 393 return true; 394 /* 395 case MENU_ID_P2P: 396 if (getActivity() instanceof SettingsActivity) { 397 ((SettingsActivity) getActivity()).startPreferencePanel( 398 WifiP2pSettings.class.getCanonicalName(), 399 null, 400 R.string.wifi_p2p_settings_title, null, 401 this, 0); 402 } else { 403 startFragment(this, WifiP2pSettings.class.getCanonicalName(), 404 R.string.wifi_p2p_settings_title, -1, null); 405 } 406 return true; 407 */ 408 case MENU_ID_WPS_PIN: 409 showDialog(WPS_PIN_DIALOG_ID); 410 return true; 411 case MENU_ID_SCAN: 412 MetricsLogger.action(getActivity(), MetricsEvent.ACTION_WIFI_FORCE_SCAN); 413 mWifiTracker.forceScan(); 414 return true; 415 case MENU_ID_ADVANCED: 416 if (getActivity() instanceof SettingsActivity) { 417 ((SettingsActivity) getActivity()).startPreferencePanel( 418 AdvancedWifiSettings.class.getCanonicalName(), null, 419 R.string.wifi_advanced_titlebar, null, this, 0); 420 } else { 421 startFragment(this, AdvancedWifiSettings.class.getCanonicalName(), 422 R.string.wifi_advanced_titlebar, -1 /* Do not request a results */, 423 null); 424 } 425 return true; 426 case MENU_ID_CONFIGURE: 427 if (getActivity() instanceof SettingsActivity) { 428 ((SettingsActivity) getActivity()).startPreferencePanel( 429 ConfigureWifiSettings.class.getCanonicalName(), null, 430 R.string.wifi_configure_titlebar, null, this, 0); 431 } else { 432 startFragment(this, ConfigureWifiSettings.class.getCanonicalName(), 433 R.string.wifi_configure_titlebar, -1 /* Do not request a results */, 434 null); 435 } 436 return true; 437 438 } 439 return super.onOptionsItemSelected(item); 440 } 441 442 @Override 443 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) { 444 Preference preference = (Preference) view.getTag(); 445 446 if (preference instanceof LongPressAccessPointPreference) { 447 mSelectedAccessPoint = 448 ((LongPressAccessPointPreference) preference).getAccessPoint(); 449 menu.setHeaderTitle(mSelectedAccessPoint.getSsid()); 450 if (mSelectedAccessPoint.isConnectable()) { 451 menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect); 452 } 453 454 WifiConfiguration config = mSelectedAccessPoint.getConfig(); 455 // Some configs are ineditable 456 if (isEditabilityLockedDown(getActivity(), config)) { 457 return; 458 } 459 460 if (mSelectedAccessPoint.isSaved() || mSelectedAccessPoint.isEphemeral()) { 461 // Allow forgetting a network if either the network is saved or ephemerally 462 // connected. (In the latter case, "forget" blacklists the network so it won't 463 // be used again, ephemerally). 464 menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget); 465 } 466 if (mSelectedAccessPoint.isSaved()) { 467 menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify); 468 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); 469 if (nfcAdapter != null && nfcAdapter.isEnabled() && 470 mSelectedAccessPoint.getSecurity() != AccessPoint.SECURITY_NONE) { 471 // Only allow writing of NFC tags for password-protected networks. 472 menu.add(Menu.NONE, MENU_ID_WRITE_NFC, 0, R.string.wifi_menu_write_to_nfc); 473 } 474 } 475 } 476 } 477 478 @Override 479 public boolean onContextItemSelected(MenuItem item) { 480 if (mSelectedAccessPoint == null) { 481 return super.onContextItemSelected(item); 482 } 483 switch (item.getItemId()) { 484 case MENU_ID_CONNECT: { 485 if (mSelectedAccessPoint.isSaved()) { 486 connect(mSelectedAccessPoint.getConfig()); 487 } else if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE) { 488 /** Bypass dialog for unsecured networks */ 489 mSelectedAccessPoint.generateOpenNetworkConfig(); 490 connect(mSelectedAccessPoint.getConfig()); 491 } else { 492 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT); 493 } 494 return true; 495 } 496 case MENU_ID_FORGET: { 497 forget(); 498 return true; 499 } 500 case MENU_ID_MODIFY: { 501 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_MODIFY); 502 return true; 503 } 504 case MENU_ID_WRITE_NFC: 505 showDialog(WRITE_NFC_DIALOG_ID); 506 return true; 507 508 } 509 return super.onContextItemSelected(item); 510 } 511 512 @Override 513 public boolean onPreferenceTreeClick(Preference preference) { 514 if (preference instanceof LongPressAccessPointPreference) { 515 mSelectedAccessPoint = ((LongPressAccessPointPreference) preference).getAccessPoint(); 516 if (mSelectedAccessPoint == null) { 517 return false; 518 } 519 /** Bypass dialog for unsecured, unsaved, and inactive networks */ 520 if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE && 521 !mSelectedAccessPoint.isSaved() && !mSelectedAccessPoint.isActive()) { 522 mSelectedAccessPoint.generateOpenNetworkConfig(); 523 connect(mSelectedAccessPoint.getConfig()); 524 } else if (mSelectedAccessPoint.isSaved()) { 525 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_VIEW); 526 } else { 527 showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT); 528 } 529 } else if (preference == mAddPreference) { 530 onAddNetworkPressed(); 531 } else { 532 return super.onPreferenceTreeClick(preference); 533 } 534 return true; 535 } 536 537 private void showDialog(AccessPoint accessPoint, int dialogMode) { 538 if (accessPoint != null) { 539 WifiConfiguration config = accessPoint.getConfig(); 540 if (isEditabilityLockedDown(getActivity(), config) && accessPoint.isActive()) { 541 RestrictedLockUtils.sendShowAdminSupportDetailsIntent(getActivity(), 542 RestrictedLockUtils.getDeviceOwner(getActivity())); 543 return; 544 } 545 } 546 547 if (mDialog != null) { 548 removeDialog(WIFI_DIALOG_ID); 549 mDialog = null; 550 } 551 552 // Save the access point and edit mode 553 mDlgAccessPoint = accessPoint; 554 mDialogMode = dialogMode; 555 556 showDialog(WIFI_DIALOG_ID); 557 } 558 559 @Override 560 public Dialog onCreateDialog(int dialogId) { 561 switch (dialogId) { 562 case WIFI_DIALOG_ID: 563 AccessPoint ap = mDlgAccessPoint; // For manual launch 564 if (ap == null) { // For re-launch from saved state 565 if (mAccessPointSavedState != null) { 566 ap = new AccessPoint(getActivity(), mAccessPointSavedState); 567 // For repeated orientation changes 568 mDlgAccessPoint = ap; 569 // Reset the saved access point data 570 mAccessPointSavedState = null; 571 } 572 } 573 // If it's null, fine, it's for Add Network 574 mSelectedAccessPoint = ap; 575 mDialog = new WifiDialog(getActivity(), this, ap, mDialogMode, 576 /* no hide submit/connect */ false); 577 return mDialog; 578 case WPS_PBC_DIALOG_ID: 579 return new WpsDialog(getActivity(), WpsInfo.PBC); 580 case WPS_PIN_DIALOG_ID: 581 return new WpsDialog(getActivity(), WpsInfo.DISPLAY); 582 case WRITE_NFC_DIALOG_ID: 583 if (mSelectedAccessPoint != null) { 584 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog( 585 getActivity(), mSelectedAccessPoint.getConfig().networkId, 586 mSelectedAccessPoint.getSecurity(), 587 mWifiManager); 588 } else if (mWifiNfcDialogSavedState != null) { 589 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog( 590 getActivity(), mWifiNfcDialogSavedState, mWifiManager); 591 } 592 593 return mWifiToNfcDialog; 594 } 595 return super.onCreateDialog(dialogId); 596 } 597 598 /** 599 * Shows the latest access points available with supplemental information like 600 * the strength of network and the security for it. 601 */ 602 @Override 603 public void onAccessPointsChanged() { 604 // Safeguard from some delayed event handling 605 if (getActivity() == null) return; 606 final int wifiState = mWifiManager.getWifiState(); 607 if (isUiRestricted()) { 608 if (!isUiRestrictedByOnlyAdmin()) { 609 if (WifiManager.WIFI_STATE_DISABLED == wifiState) { 610 addMessagePreference(R.string.wifi_empty_list_wifi_off); 611 } 612 else { 613 addMessagePreference(R.string.wifi_empty_list_user_restricted); 614 } 615 } 616 getPreferenceScreen().removeAll(); 617 return; 618 } 619 620 switch (wifiState) { 621 case WifiManager.WIFI_STATE_ENABLED: 622 // AccessPoints are automatically sorted with TreeSet. 623 final Collection<AccessPoint> accessPoints = 624 mWifiTracker.getAccessPoints(); 625 626 boolean hasAvailableAccessPoints = false; 627 int index = 0; 628 cacheRemoveAllPrefs(getPreferenceScreen()); 629 for (AccessPoint accessPoint : accessPoints) { 630 // Ignore access points that are out of range. 631 if (accessPoint.getLevel() != -1) { 632 String key = accessPoint.getBssid(); 633 if (TextUtils.isEmpty(key)) { 634 key = accessPoint.getSsidStr(); 635 } 636 hasAvailableAccessPoints = true; 637 LongPressAccessPointPreference pref = (LongPressAccessPointPreference) 638 getCachedPreference(key); 639 if (pref != null) { 640 pref.setOrder(index++); 641 continue; 642 } 643 LongPressAccessPointPreference 644 preference = new LongPressAccessPointPreference(accessPoint, 645 getPrefContext(), mUserBadgeCache, false, 646 R.drawable.ic_wifi_signal_0, this); 647 preference.setKey(key); 648 preference.setOrder(index++); 649 if (mOpenSsid != null && mOpenSsid.equals(accessPoint.getSsidStr()) 650 && !accessPoint.isSaved() 651 && accessPoint.getSecurity() != AccessPoint.SECURITY_NONE) { 652 onPreferenceTreeClick(preference); 653 mOpenSsid = null; 654 } 655 getPreferenceScreen().addPreference(preference); 656 accessPoint.setListener(this); 657 preference.refresh(); 658 } 659 } 660 removeCachedPrefs(getPreferenceScreen()); 661 if (!hasAvailableAccessPoints) { 662 setProgressBarVisible(true); 663 Preference pref = new Preference(getContext()) { 664 @Override 665 public void onBindViewHolder(PreferenceViewHolder holder) { 666 super.onBindViewHolder(holder); 667 // Show a line on each side of add network. 668 holder.setDividerAllowedBelow(true); 669 } 670 }; 671 pref.setSelectable(false); 672 pref.setSummary(R.string.wifi_empty_list_wifi_on); 673 pref.setOrder(0); 674 pref.setKey(PREF_KEY_EMPTY_WIFI_LIST); 675 getPreferenceScreen().addPreference(pref); 676 mAddPreference.setOrder(1); 677 getPreferenceScreen().addPreference(mAddPreference); 678 } else { 679 mAddPreference.setOrder(index++); 680 getPreferenceScreen().addPreference(mAddPreference); 681 setProgressBarVisible(false); 682 } 683 if (mScanMenuItem != null) { 684 mScanMenuItem.setEnabled(true); 685 } 686 break; 687 688 case WifiManager.WIFI_STATE_ENABLING: 689 getPreferenceScreen().removeAll(); 690 setProgressBarVisible(true); 691 break; 692 693 case WifiManager.WIFI_STATE_DISABLING: 694 addMessagePreference(R.string.wifi_stopping); 695 setProgressBarVisible(true); 696 break; 697 698 case WifiManager.WIFI_STATE_DISABLED: 699 setOffMessage(); 700 setProgressBarVisible(false); 701 if (mScanMenuItem != null) { 702 mScanMenuItem.setEnabled(false); 703 } 704 break; 705 } 706 } 707 708 private void setOffMessage() { 709 if (isUiRestricted()) { 710 if (!isUiRestrictedByOnlyAdmin()) { 711 addMessagePreference(R.string.wifi_empty_list_wifi_off); 712 } 713 getPreferenceScreen().removeAll(); 714 return; 715 } 716 717 TextView emptyTextView = getEmptyTextView(); 718 if (emptyTextView == null) { 719 return; 720 } 721 722 final CharSequence briefText = getText(R.string.wifi_empty_list_wifi_off); 723 724 // Don't use WifiManager.isScanAlwaysAvailable() to check the Wi-Fi scanning mode. Instead, 725 // read the system settings directly. Because when the device is in Airplane mode, even if 726 // Wi-Fi scanning mode is on, WifiManager.isScanAlwaysAvailable() still returns "off". 727 final ContentResolver resolver = getActivity().getContentResolver(); 728 final boolean wifiScanningMode = Settings.Global.getInt( 729 resolver, Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1; 730 731 if (!wifiScanningMode) { 732 // Show only the brief text if the user is not allowed to configure scanning settings, 733 // or the scanning mode has been turned off. 734 emptyTextView.setText(briefText, BufferType.SPANNABLE); 735 } else { 736 // Append the description of scanning settings with link. 737 final StringBuilder contentBuilder = new StringBuilder(); 738 contentBuilder.append(briefText); 739 contentBuilder.append("\n\n"); 740 contentBuilder.append(getText(R.string.wifi_scan_notify_text)); 741 LinkifyUtils.linkify(emptyTextView, contentBuilder, new LinkifyUtils.OnClickListener() { 742 @Override 743 public void onClick() { 744 final SettingsActivity activity = 745 (SettingsActivity) WifiSettings.this.getActivity(); 746 activity.startPreferencePanel(ScanningSettings.class.getName(), null, 747 R.string.location_scanning_screen_title, null, null, 0); 748 } 749 }); 750 } 751 // Embolden and enlarge the brief description anyway. 752 Spannable boldSpan = (Spannable) emptyTextView.getText(); 753 boldSpan.setSpan( 754 new TextAppearanceSpan(getActivity(), android.R.style.TextAppearance_Medium), 0, 755 briefText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 756 getPreferenceScreen().removeAll(); 757 } 758 759 private void addMessagePreference(int messageId) { 760 TextView emptyTextView = getEmptyTextView(); 761 if (emptyTextView != null) emptyTextView.setText(messageId); 762 getPreferenceScreen().removeAll(); 763 } 764 765 protected void setProgressBarVisible(boolean visible) { 766 if (mProgressHeader != null) { 767 mProgressHeader.setVisibility(visible && !isUiRestricted() ? View.VISIBLE : View.GONE); 768 } 769 } 770 771 @Override 772 public void onWifiStateChanged(int state) { 773 switch (state) { 774 case WifiManager.WIFI_STATE_ENABLING: 775 addMessagePreference(R.string.wifi_starting); 776 setProgressBarVisible(true); 777 break; 778 779 case WifiManager.WIFI_STATE_DISABLED: 780 setOffMessage(); 781 setProgressBarVisible(false); 782 break; 783 } 784 } 785 786 @Override 787 public void onConnectedChanged() { 788 changeNextButtonState(mWifiTracker.isConnected()); 789 } 790 791 /** 792 * Renames/replaces "Next" button when appropriate. "Next" button usually exists in 793 * Wifi setup screens, not in usual wifi settings screen. 794 * 795 * @param enabled true when the device is connected to a wifi network. 796 */ 797 private void changeNextButtonState(boolean enabled) { 798 if (mEnableNextOnConnection && hasNextButton()) { 799 getNextButton().setEnabled(enabled); 800 } 801 } 802 803 @Override 804 public void onForget(WifiDialog dialog) { 805 forget(); 806 } 807 808 @Override 809 public void onSubmit(WifiDialog dialog) { 810 if (mDialog != null) { 811 submit(mDialog.getController()); 812 } 813 } 814 815 /* package */ void submit(WifiConfigController configController) { 816 817 final WifiConfiguration config = configController.getConfig(); 818 819 if (config == null) { 820 if (mSelectedAccessPoint != null 821 && mSelectedAccessPoint.isSaved()) { 822 connect(mSelectedAccessPoint.getConfig()); 823 } 824 } else if (configController.getMode() == WifiConfigUiBase.MODE_MODIFY) { 825 mWifiManager.save(config, mSaveListener); 826 } else { 827 mWifiManager.save(config, mSaveListener); 828 if (mSelectedAccessPoint != null) { // Not an "Add network" 829 connect(config); 830 } 831 } 832 833 mWifiTracker.resumeScanning(); 834 } 835 836 /* package */ void forget() { 837 MetricsLogger.action(getActivity(), MetricsEvent.ACTION_WIFI_FORGET); 838 if (!mSelectedAccessPoint.isSaved()) { 839 if (mSelectedAccessPoint.getNetworkInfo() != null && 840 mSelectedAccessPoint.getNetworkInfo().getState() != State.DISCONNECTED) { 841 // Network is active but has no network ID - must be ephemeral. 842 mWifiManager.disableEphemeralNetwork( 843 AccessPoint.convertToQuotedString(mSelectedAccessPoint.getSsidStr())); 844 } else { 845 // Should not happen, but a monkey seems to trigger it 846 Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig()); 847 return; 848 } 849 } else if (mSelectedAccessPoint.getConfig().isPasspoint()) { 850 mWifiManager.removePasspointConfiguration(mSelectedAccessPoint.getConfig().FQDN); 851 } else { 852 mWifiManager.forget(mSelectedAccessPoint.getConfig().networkId, mForgetListener); 853 } 854 855 mWifiTracker.resumeScanning(); 856 857 // We need to rename/replace "Next" button in wifi setup context. 858 changeNextButtonState(false); 859 } 860 861 protected void connect(final WifiConfiguration config) { 862 MetricsLogger.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT); 863 mWifiManager.connect(config, mConnectListener); 864 } 865 866 protected void connect(final int networkId) { 867 MetricsLogger.action(getActivity(), MetricsEvent.ACTION_WIFI_CONNECT); 868 mWifiManager.connect(networkId, mConnectListener); 869 } 870 871 /** 872 * Called when "add network" button is pressed. 873 */ 874 /* package */ void onAddNetworkPressed() { 875 MetricsLogger.action(getActivity(), MetricsEvent.ACTION_WIFI_ADD_NETWORK); 876 // No exact access point is selected. 877 mSelectedAccessPoint = null; 878 showDialog(null, WifiConfigUiBase.MODE_CONNECT); 879 } 880 881 @Override 882 protected int getHelpResource() { 883 return R.string.help_url_wifi; 884 } 885 886 @Override 887 public void onAccessPointChanged(final AccessPoint accessPoint) { 888 View view = getView(); 889 if (view != null) { 890 view.post(new Runnable() { 891 @Override 892 public void run() { 893 Object tag = accessPoint.getTag(); 894 if (tag != null) { 895 ((LongPressAccessPointPreference) tag).refresh(); 896 } 897 } 898 }); 899 } 900 } 901 902 @Override 903 public void onLevelChanged(AccessPoint accessPoint) { 904 ((LongPressAccessPointPreference) accessPoint.getTag()).onLevelChanged(); 905 } 906 907 public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER = 908 new BaseSearchIndexProvider() { 909 @Override 910 public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) { 911 final List<SearchIndexableRaw> result = new ArrayList<>(); 912 final Resources res = context.getResources(); 913 914 // Add fragment title 915 SearchIndexableRaw data = new SearchIndexableRaw(context); 916 data.title = res.getString(R.string.wifi_settings); 917 data.screenTitle = res.getString(R.string.wifi_settings); 918 data.keywords = res.getString(R.string.keywords_wifi); 919 result.add(data); 920 921 // Add saved Wi-Fi access points 922 final Collection<AccessPoint> accessPoints = 923 WifiTracker.getCurrentAccessPoints(context, true, false, false); 924 for (AccessPoint accessPoint : accessPoints) { 925 data = new SearchIndexableRaw(context); 926 data.title = accessPoint.getSsidStr(); 927 data.screenTitle = res.getString(R.string.wifi_settings); 928 data.enabled = enabled; 929 result.add(data); 930 } 931 932 return result; 933 } 934 }; 935 936 /** 937 * Returns true if the config is not editable through Settings. 938 * @param context Context of caller 939 * @param config The WiFi config. 940 * @return true if the config is not editable through Settings. 941 */ 942 static boolean isEditabilityLockedDown(Context context, WifiConfiguration config) { 943 return !canModifyNetwork(context, config); 944 } 945 946 /** 947 * This method is a stripped version of WifiConfigStore.canModifyNetwork. 948 * TODO: refactor to have only one method. 949 * @param context Context of caller 950 * @param config The WiFi config. 951 * @return true if Settings can modify the config. 952 */ 953 static boolean canModifyNetwork(Context context, WifiConfiguration config) { 954 if (config == null) { 955 return true; 956 } 957 958 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService( 959 Context.DEVICE_POLICY_SERVICE); 960 961 // Check if device has DPM capability. If it has and dpm is still null, then we 962 // treat this case with suspicion and bail out. 963 final PackageManager pm = context.getPackageManager(); 964 if (pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN) && dpm == null) { 965 return false; 966 } 967 968 boolean isConfigEligibleForLockdown = false; 969 if (dpm != null) { 970 final ComponentName deviceOwner = dpm.getDeviceOwnerComponentOnAnyUser(); 971 if (deviceOwner != null) { 972 final int deviceOwnerUserId = dpm.getDeviceOwnerUserId(); 973 try { 974 final int deviceOwnerUid = pm.getPackageUidAsUser(deviceOwner.getPackageName(), 975 deviceOwnerUserId); 976 isConfigEligibleForLockdown = deviceOwnerUid == config.creatorUid; 977 } catch (NameNotFoundException e) { 978 // don't care 979 } 980 } 981 } 982 if (!isConfigEligibleForLockdown) { 983 return true; 984 } 985 986 final ContentResolver resolver = context.getContentResolver(); 987 final boolean isLockdownFeatureEnabled = Settings.Global.getInt(resolver, 988 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) != 0; 989 return !isLockdownFeatureEnabled; 990 } 991 992 private static class SummaryProvider extends BroadcastReceiver 993 implements SummaryLoader.SummaryProvider { 994 995 private final Context mContext; 996 private final WifiManager mWifiManager; 997 private final WifiStatusTracker mWifiTracker; 998 private final SummaryLoader mSummaryLoader; 999 1000 public SummaryProvider(Context context, SummaryLoader summaryLoader) { 1001 mContext = context; 1002 mSummaryLoader = summaryLoader; 1003 mWifiManager = context.getSystemService(WifiManager.class); 1004 mWifiTracker = new WifiStatusTracker(mWifiManager); 1005 } 1006 1007 private CharSequence getSummary() { 1008 if (!mWifiTracker.enabled) { 1009 return mContext.getString(R.string.wifi_disabled_generic); 1010 } 1011 if (!mWifiTracker.connected) { 1012 return mContext.getString(R.string.disconnected); 1013 } 1014 return mWifiTracker.ssid; 1015 } 1016 1017 @Override 1018 public void setListening(boolean listening) { 1019 if (listening) { 1020 IntentFilter filter = new IntentFilter(); 1021 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); 1022 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); 1023 filter.addAction(WifiManager.RSSI_CHANGED_ACTION); 1024 mSummaryLoader.registerReceiver(this, filter); 1025 } 1026 } 1027 1028 @Override 1029 public void onReceive(Context context, Intent intent) { 1030 mWifiTracker.handleBroadcast(intent); 1031 mSummaryLoader.setSummary(this, getSummary()); 1032 } 1033 } 1034 1035 public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY 1036 = new SummaryLoader.SummaryProviderFactory() { 1037 @Override 1038 public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity, 1039 SummaryLoader summaryLoader) { 1040 return new SummaryProvider(activity, summaryLoader); 1041 } 1042 }; 1043} 1044