WifiSettings.java revision c2fb78627fa6c715b06a731edf36a4efcf294592
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.net.wifi.WifiConfiguration.INVALID_NETWORK_ID; 20import static android.os.UserManager.DISALLOW_CONFIG_WIFI; 21 22import android.app.Activity; 23import android.app.Dialog; 24import android.content.BroadcastReceiver; 25import android.content.Context; 26import android.content.DialogInterface; 27import android.content.Intent; 28import android.content.IntentFilter; 29import android.content.res.Resources; 30import android.content.res.TypedArray; 31import android.location.LocationManager; 32import android.net.ConnectivityManager; 33import android.net.NetworkInfo; 34import android.net.NetworkInfo.DetailedState; 35import android.net.NetworkInfo.State; 36import android.net.wifi.ScanResult; 37import android.net.wifi.WifiConfiguration; 38import android.net.wifi.WifiInfo; 39import android.net.wifi.WifiManager; 40import android.net.wifi.WpsInfo; 41import android.nfc.NfcAdapter; 42import android.os.Bundle; 43import android.os.Handler; 44import android.os.Message; 45import android.os.UserHandle; 46import android.preference.Preference; 47import android.preference.PreferenceScreen; 48import android.util.Log; 49import android.view.ContextMenu; 50import android.view.ContextMenu.ContextMenuInfo; 51import android.view.Menu; 52import android.view.MenuInflater; 53import android.view.MenuItem; 54import android.view.View; 55import android.widget.AdapterView.AdapterContextMenuInfo; 56import android.widget.TextView; 57import android.widget.Toast; 58 59import com.android.settings.R; 60import com.android.settings.RestrictedSettingsFragment; 61import com.android.settings.SettingsActivity; 62import com.android.settings.search.BaseSearchIndexProvider; 63import com.android.settings.search.Indexable; 64import com.android.settings.search.SearchIndexableRaw; 65 66import java.util.ArrayList; 67import java.util.Collection; 68import java.util.Collections; 69import java.util.HashMap; 70import java.util.List; 71import java.util.concurrent.atomic.AtomicBoolean; 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 DialogInterface.OnClickListener, Indexable { 83 84 private static final String TAG = "WifiSettings"; 85 86 /* package */ static final int MENU_ID_WPS_PBC = Menu.FIRST; 87 private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1; 88 private static final int MENU_ID_SAVED_NETWORK = Menu.FIRST + 2; 89 /* package */ static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3; 90 private static final int MENU_ID_ADVANCED = Menu.FIRST + 4; 91 private static final int MENU_ID_SCAN = Menu.FIRST + 5; 92 private static final int MENU_ID_CONNECT = Menu.FIRST + 6; 93 private static final int MENU_ID_FORGET = Menu.FIRST + 7; 94 private static final int MENU_ID_MODIFY = Menu.FIRST + 8; 95 private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9; 96 private static final int MENU_ID_APPS = Menu.FIRST + 10; 97 98 public static final int WIFI_DIALOG_ID = 1; 99 /* package */ static final int WPS_PBC_DIALOG_ID = 2; 100 private static final int WPS_PIN_DIALOG_ID = 3; 101 private static final int WRITE_NFC_DIALOG_ID = 6; 102 103 // Combo scans can take 5-6s to complete - set to 10s. 104 private static final int WIFI_RESCAN_INTERVAL_MS = 10 * 1000; 105 106 // Instance state keys 107 private static final String SAVE_DIALOG_EDIT_MODE = "edit_mode"; 108 private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state"; 109 110 private static boolean savedNetworksExist; 111 112 private final IntentFilter mFilter; 113 private final BroadcastReceiver mReceiver; 114 private final Scanner mScanner; 115 116 /* package */ WifiManager mWifiManager; 117 private WifiManager.ActionListener mConnectListener; 118 private WifiManager.ActionListener mSaveListener; 119 private WifiManager.ActionListener mForgetListener; 120 121 private WifiEnabler mWifiEnabler; 122 // An access point being editted is stored here. 123 private AccessPoint mSelectedAccessPoint; 124 125 private NetworkInfo mLastNetworkInfo; 126 private WifiInfo mLastInfo; 127 128 private final AtomicBoolean mConnected = new AtomicBoolean(false); 129 130 private WifiDialog mDialog; 131 private WriteWifiConfigToNfcDialog mWifiToNfcDialog; 132 133 private TextView mEmptyView; 134 135 private boolean showAppIcons = false; 136 private MenuItem showAppMenuItem = null; 137 138 // this boolean extra specifies whether to disable the Next button when not connected. Used by 139 // account creation outside of setup wizard. 140 private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect"; 141 // This string extra specifies a network to open the connect dialog on, so the user can enter 142 // network credentials. This is used by quick settings for secured networks. 143 private static final String EXTRA_START_CONNECT_SSID = "wifi_start_connect_ssid"; 144 145 // should Next button only be enabled when we have a connection? 146 private boolean mEnableNextOnConnection; 147 148 // Save the dialog details 149 private boolean mDlgEdit; 150 private AccessPoint mDlgAccessPoint; 151 private Bundle mAccessPointSavedState; 152 153 /** verbose logging flag. this flag is set thru developer debugging options 154 * and used so as to assist with in-the-field WiFi connectivity debugging */ 155 public static int mVerboseLogging = 0; 156 157 /* End of "used in Wifi Setup context" */ 158 159 /** A restricted multimap for use in constructAccessPoints */ 160 private static class Multimap<K,V> { 161 private final HashMap<K,List<V>> store = new HashMap<K,List<V>>(); 162 /** retrieve a non-null list of values with key K */ 163 List<V> getAll(K key) { 164 List<V> values = store.get(key); 165 return values != null ? values : Collections.<V>emptyList(); 166 } 167 168 void put(K key, V val) { 169 List<V> curVals = store.get(key); 170 if (curVals == null) { 171 curVals = new ArrayList<V>(3); 172 store.put(key, curVals); 173 } 174 curVals.add(val); 175 } 176 } 177 178 private static class Scanner extends Handler { 179 private int mRetry = 0; 180 private WifiSettings mWifiSettings = null; 181 182 Scanner(WifiSettings wifiSettings) { 183 mWifiSettings = wifiSettings; 184 } 185 186 void resume() { 187 if (!hasMessages(0)) { 188 sendEmptyMessage(0); 189 } 190 } 191 192 void forceScan() { 193 removeMessages(0); 194 sendEmptyMessage(0); 195 } 196 197 void pause() { 198 mRetry = 0; 199 removeMessages(0); 200 } 201 202 @Override 203 public void handleMessage(Message message) { 204 if (mWifiSettings.mWifiManager.startScan()) { 205 mRetry = 0; 206 } else if (++mRetry >= 3) { 207 mRetry = 0; 208 Activity activity = mWifiSettings.getActivity(); 209 if (activity != null) { 210 Toast.makeText(activity, R.string.wifi_fail_to_scan, Toast.LENGTH_LONG).show(); 211 } 212 return; 213 } 214 sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS); 215 } 216 } 217 218 public WifiSettings() { 219 super(DISALLOW_CONFIG_WIFI); 220 mFilter = new IntentFilter(); 221 mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); 222 mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 223 mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION); 224 mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); 225 mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION); 226 mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION); 227 mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); 228 mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); 229 230 mReceiver = new BroadcastReceiver() { 231 @Override 232 public void onReceive(Context context, Intent intent) { 233 handleEvent(intent); 234 } 235 }; 236 237 mScanner = new Scanner(this); 238 } 239 240 @Override 241 public void onActivityCreated(Bundle savedInstanceState) { 242 super.onActivityCreated(savedInstanceState); 243 244 mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 245 246 mConnectListener = new WifiManager.ActionListener() { 247 @Override 248 public void onSuccess() { 249 } 250 @Override 251 public void onFailure(int reason) { 252 Activity activity = getActivity(); 253 if (activity != null) { 254 Toast.makeText(activity, 255 R.string.wifi_failed_connect_message, 256 Toast.LENGTH_SHORT).show(); 257 } 258 } 259 }; 260 261 mSaveListener = new WifiManager.ActionListener() { 262 @Override 263 public void onSuccess() { 264 } 265 @Override 266 public void onFailure(int reason) { 267 Activity activity = getActivity(); 268 if (activity != null) { 269 Toast.makeText(activity, 270 R.string.wifi_failed_save_message, 271 Toast.LENGTH_SHORT).show(); 272 } 273 } 274 }; 275 276 mForgetListener = new WifiManager.ActionListener() { 277 @Override 278 public void onSuccess() { 279 } 280 @Override 281 public void onFailure(int reason) { 282 Activity activity = getActivity(); 283 if (activity != null) { 284 Toast.makeText(activity, 285 R.string.wifi_failed_forget_message, 286 Toast.LENGTH_SHORT).show(); 287 } 288 } 289 }; 290 291 if (savedInstanceState != null) { 292 mDlgEdit = savedInstanceState.getBoolean(SAVE_DIALOG_EDIT_MODE); 293 if (savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) { 294 mAccessPointSavedState = 295 savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE); 296 } 297 } 298 299 // if we're supposed to enable/disable the Next button based on our current connection 300 // state, start it off in the right state 301 Intent intent = getActivity().getIntent(); 302 mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false); 303 304 if (mEnableNextOnConnection) { 305 if (hasNextButton()) { 306 final ConnectivityManager connectivity = (ConnectivityManager) 307 getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 308 if (connectivity != null) { 309 NetworkInfo info = connectivity.getNetworkInfo( 310 ConnectivityManager.TYPE_WIFI); 311 changeNextButtonState(info.isConnected()); 312 } 313 } 314 } 315 316 addPreferencesFromResource(R.xml.wifi_settings); 317 318 mEmptyView = initEmptyView(); 319 registerForContextMenu(getListView()); 320 setHasOptionsMenu(true); 321 322 if (intent.hasExtra(EXTRA_START_CONNECT_SSID)) { 323 String ssid = intent.getStringExtra(EXTRA_START_CONNECT_SSID); 324 updateAccessPoints(); 325 PreferenceScreen preferenceScreen = getPreferenceScreen(); 326 for (int i = 0; i < preferenceScreen.getPreferenceCount(); i++) { 327 Preference preference = preferenceScreen.getPreference(i); 328 if (preference instanceof AccessPoint) { 329 AccessPoint accessPoint = (AccessPoint) preference; 330 if (ssid.equals(accessPoint.ssid) && accessPoint.networkId == -1 331 && accessPoint.security != AccessPoint.SECURITY_NONE) { 332 onPreferenceTreeClick(preferenceScreen, preference); 333 break; 334 } 335 } 336 } 337 } 338 } 339 340 @Override 341 public void onDestroyView() { 342 super.onDestroyView(); 343 344 if (mWifiEnabler != null) { 345 mWifiEnabler.teardownSwitchBar(); 346 } 347 } 348 349 @Override 350 public void onStart() { 351 super.onStart(); 352 353 // On/off switch is hidden for Setup Wizard (returns null) 354 mWifiEnabler = createWifiEnabler(); 355 } 356 357 /** 358 * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard) 359 */ 360 /* package */ WifiEnabler createWifiEnabler() { 361 final SettingsActivity activity = (SettingsActivity) getActivity(); 362 return new WifiEnabler(activity, activity.getSwitchBar()); 363 } 364 365 @Override 366 public void onResume() { 367 final Activity activity = getActivity(); 368 super.onResume(); 369 if (mWifiEnabler != null) { 370 mWifiEnabler.resume(activity); 371 } 372 373 activity.registerReceiver(mReceiver, mFilter); 374 updateAccessPoints(); 375 } 376 377 @Override 378 public void onPause() { 379 super.onPause(); 380 if (mWifiEnabler != null) { 381 mWifiEnabler.pause(); 382 } 383 384 getActivity().unregisterReceiver(mReceiver); 385 mScanner.pause(); 386 } 387 388 @Override 389 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 390 // If the user is not allowed to configure wifi, do not show the menu. 391 if (isUiRestricted()) return; 392 393 addOptionsMenuItems(menu); 394 super.onCreateOptionsMenu(menu, inflater); 395 } 396 397 /** 398 * @param menu 399 */ 400 void addOptionsMenuItems(Menu menu) { 401 final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); 402 TypedArray ta = getActivity().getTheme().obtainStyledAttributes( 403 new int[] {R.attr.ic_menu_add, R.attr.ic_wps}); 404 menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network) 405 .setIcon(ta.getDrawable(0)) 406 .setEnabled(wifiIsEnabled) 407 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 408 if (savedNetworksExist) { 409 menu.add(Menu.NONE, MENU_ID_SAVED_NETWORK, 0, R.string.wifi_saved_access_points_label) 410 .setIcon(ta.getDrawable(0)) 411 .setEnabled(wifiIsEnabled) 412 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 413 } 414 menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.menu_stats_refresh) 415 .setEnabled(wifiIsEnabled) 416 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 417 menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced) 418 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 419 showAppMenuItem = menu.add(Menu.NONE, MENU_ID_APPS, 0, R.string.wifi_menu_apps); 420 showAppMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 421 ta.recycle(); 422 } 423 424 @Override 425 public void onSaveInstanceState(Bundle outState) { 426 super.onSaveInstanceState(outState); 427 428 // If the dialog is showing, save its state. 429 if (mDialog != null && mDialog.isShowing()) { 430 outState.putBoolean(SAVE_DIALOG_EDIT_MODE, mDlgEdit); 431 if (mDlgAccessPoint != null) { 432 mAccessPointSavedState = new Bundle(); 433 mDlgAccessPoint.saveWifiState(mAccessPointSavedState); 434 outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState); 435 } 436 } 437 } 438 439 @Override 440 public boolean onOptionsItemSelected(MenuItem item) { 441 // If the user is not allowed to configure wifi, do not handle menu selections. 442 if (isUiRestricted()) return false; 443 444 switch (item.getItemId()) { 445 case MENU_ID_WPS_PBC: 446 showDialog(WPS_PBC_DIALOG_ID); 447 return true; 448 /* 449 case MENU_ID_P2P: 450 if (getActivity() instanceof SettingsActivity) { 451 ((SettingsActivity) getActivity()).startPreferencePanel( 452 WifiP2pSettings.class.getCanonicalName(), 453 null, 454 R.string.wifi_p2p_settings_title, null, 455 this, 0); 456 } else { 457 startFragment(this, WifiP2pSettings.class.getCanonicalName(), 458 R.string.wifi_p2p_settings_title, -1, null); 459 } 460 return true; 461 */ 462 case MENU_ID_WPS_PIN: 463 showDialog(WPS_PIN_DIALOG_ID); 464 return true; 465 case MENU_ID_SCAN: 466 if (mWifiManager.isWifiEnabled()) { 467 mScanner.forceScan(); 468 } 469 return true; 470 case MENU_ID_ADD_NETWORK: 471 if (mWifiManager.isWifiEnabled()) { 472 onAddNetworkPressed(); 473 } 474 return true; 475 case MENU_ID_SAVED_NETWORK: 476 if (getActivity() instanceof SettingsActivity) { 477 ((SettingsActivity) getActivity()).startPreferencePanel( 478 SavedAccessPointsWifiSettings.class.getCanonicalName(), null, 479 R.string.wifi_saved_access_points_titlebar, null, this, 0); 480 } else { 481 startFragment(this, SavedAccessPointsWifiSettings.class.getCanonicalName(), 482 R.string.wifi_saved_access_points_titlebar, 483 -1 /* Do not request a result */, null); 484 } 485 return true; 486 case MENU_ID_ADVANCED: 487 if (getActivity() instanceof SettingsActivity) { 488 ((SettingsActivity) getActivity()).startPreferencePanel( 489 AdvancedWifiSettings.class.getCanonicalName(), null, 490 R.string.wifi_advanced_titlebar, null, this, 0); 491 } else { 492 startFragment(this, AdvancedWifiSettings.class.getCanonicalName(), 493 R.string.wifi_advanced_titlebar, -1 /* Do not request a results */, 494 null); 495 } 496 return true; 497 case MENU_ID_APPS: 498 showAppIcons = !showAppIcons; 499 500 if (showAppIcons) { 501 showAppMenuItem.setTitle(R.string.wifi_menu_apps_strength); 502 } else { 503 showAppMenuItem.setTitle(R.string.wifi_menu_apps); 504 } 505 updateAccessPoints(); 506 return true; 507 } 508 return super.onOptionsItemSelected(item); 509 } 510 511 @Override 512 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) { 513 if (info instanceof AdapterContextMenuInfo) { 514 Preference preference = (Preference) getListView().getItemAtPosition( 515 ((AdapterContextMenuInfo) info).position); 516 517 if (preference instanceof AccessPoint) { 518 mSelectedAccessPoint = (AccessPoint) preference; 519 menu.setHeaderTitle(mSelectedAccessPoint.ssid); 520 if (mSelectedAccessPoint.getLevel() != -1) { 521 if (mSelectedAccessPoint.getState() == null) { 522 menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect); 523 } 524 } 525 526 if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID || 527 (mSelectedAccessPoint.getNetworkInfo() != null && 528 mSelectedAccessPoint.getNetworkInfo().getState() != State.DISCONNECTED)) { 529 // Allow forgetting a network if either the network is saved or ephemerally 530 // connected. (In the latter case, "forget" blacklists the network so it won't 531 // be used again, ephemerally). 532 menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget); 533 } 534 if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 535 menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify); 536 537 NfcAdapter nfcAdapter = NfcAdapter.getNfcAdapter(getActivity()); 538 if (nfcAdapter != null && nfcAdapter.isEnabled() && 539 mSelectedAccessPoint.security != AccessPoint.SECURITY_NONE) { 540 // Only allow writing of NFC tags for password-protected networks. 541 menu.add(Menu.NONE, MENU_ID_WRITE_NFC, 0, R.string.wifi_menu_write_to_nfc); 542 } 543 } 544 } 545 } 546 } 547 548 @Override 549 public boolean onContextItemSelected(MenuItem item) { 550 if (mSelectedAccessPoint == null) { 551 return super.onContextItemSelected(item); 552 } 553 switch (item.getItemId()) { 554 case MENU_ID_CONNECT: { 555 if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 556 connect(mSelectedAccessPoint.networkId); 557 } else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) { 558 /** Bypass dialog for unsecured networks */ 559 mSelectedAccessPoint.generateOpenNetworkConfig(); 560 connect(mSelectedAccessPoint.getConfig()); 561 } else { 562 showDialog(mSelectedAccessPoint, true); 563 } 564 return true; 565 } 566 case MENU_ID_FORGET: { 567 forget(); 568 return true; 569 } 570 case MENU_ID_MODIFY: { 571 showDialog(mSelectedAccessPoint, true); 572 return true; 573 } 574 case MENU_ID_WRITE_NFC: 575 showDialog(WRITE_NFC_DIALOG_ID); 576 return true; 577 578 } 579 return super.onContextItemSelected(item); 580 } 581 582 @Override 583 public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) { 584 if (preference instanceof AccessPoint) { 585 mSelectedAccessPoint = (AccessPoint) preference; 586 /** Bypass dialog for unsecured, unsaved, and inactive networks */ 587 if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE && 588 mSelectedAccessPoint.networkId == INVALID_NETWORK_ID && 589 !mSelectedAccessPoint.isActive()) { 590 mSelectedAccessPoint.generateOpenNetworkConfig(); 591 if (!savedNetworksExist) { 592 savedNetworksExist = true; 593 getActivity().invalidateOptionsMenu(); 594 } 595 connect(mSelectedAccessPoint.getConfig()); 596 } else { 597 showDialog(mSelectedAccessPoint, false); 598 } 599 } else { 600 return super.onPreferenceTreeClick(screen, preference); 601 } 602 return true; 603 } 604 605 private void showDialog(AccessPoint accessPoint, boolean edit) { 606 if (mDialog != null) { 607 removeDialog(WIFI_DIALOG_ID); 608 mDialog = null; 609 } 610 611 // Save the access point and edit mode 612 mDlgAccessPoint = accessPoint; 613 mDlgEdit = edit; 614 615 showDialog(WIFI_DIALOG_ID); 616 } 617 618 @Override 619 public Dialog onCreateDialog(int dialogId) { 620 switch (dialogId) { 621 case WIFI_DIALOG_ID: 622 AccessPoint ap = mDlgAccessPoint; // For manual launch 623 if (ap == null) { // For re-launch from saved state 624 if (mAccessPointSavedState != null) { 625 ap = new AccessPoint(getActivity(), mAccessPointSavedState); 626 // For repeated orientation changes 627 mDlgAccessPoint = ap; 628 // Reset the saved access point data 629 mAccessPointSavedState = null; 630 } 631 } 632 // If it's null, fine, it's for Add Network 633 mSelectedAccessPoint = ap; 634 mDialog = new WifiDialog(getActivity(), this, ap, mDlgEdit); 635 return mDialog; 636 case WPS_PBC_DIALOG_ID: 637 return new WpsDialog(getActivity(), WpsInfo.PBC); 638 case WPS_PIN_DIALOG_ID: 639 return new WpsDialog(getActivity(), WpsInfo.DISPLAY); 640 case WRITE_NFC_DIALOG_ID: 641 if (mSelectedAccessPoint != null) { 642 mWifiToNfcDialog = new WriteWifiConfigToNfcDialog( 643 getActivity(), mSelectedAccessPoint, mWifiManager); 644 return mWifiToNfcDialog; 645 } 646 647 } 648 return super.onCreateDialog(dialogId); 649 } 650 651 /** 652 * Shows the latest access points available with supplemental information like 653 * the strength of network and the security for it. 654 */ 655 private void updateAccessPoints() { 656 // Safeguard from some delayed event handling 657 if (getActivity() == null) return; 658 659 if (isUiRestricted()) { 660 addMessagePreference(R.string.wifi_empty_list_user_restricted); 661 return; 662 } 663 final int wifiState = mWifiManager.getWifiState(); 664 665 //when we update the screen, check if verbose logging has been turned on or off 666 mVerboseLogging = mWifiManager.getVerboseLoggingLevel(); 667 668 switch (wifiState) { 669 case WifiManager.WIFI_STATE_ENABLED: 670 // AccessPoints are automatically sorted with TreeSet. 671 final Collection<AccessPoint> accessPoints = 672 constructAccessPoints(getActivity(), mWifiManager, mLastInfo, 673 mLastNetworkInfo); 674 getPreferenceScreen().removeAll(); 675 if (accessPoints.size() == 0) { 676 addMessagePreference(R.string.wifi_empty_list_wifi_on); 677 } 678 679 for (AccessPoint accessPoint : accessPoints) { 680 if (showAppIcons) { 681 accessPoint.showAppIcon(); 682 } 683 684 // Ignore access points that are out of range. 685 if (accessPoint.getLevel() != -1) { 686 getPreferenceScreen().addPreference(accessPoint); 687 } 688 } 689 break; 690 691 case WifiManager.WIFI_STATE_ENABLING: 692 getPreferenceScreen().removeAll(); 693 break; 694 695 case WifiManager.WIFI_STATE_DISABLING: 696 addMessagePreference(R.string.wifi_stopping); 697 break; 698 699 case WifiManager.WIFI_STATE_DISABLED: 700 setOffMessage(); 701 break; 702 } 703 } 704 705 protected TextView initEmptyView() { 706 TextView emptyView = (TextView) getActivity().findViewById(android.R.id.empty); 707 getListView().setEmptyView(emptyView); 708 return emptyView; 709 } 710 711 private void setOffMessage() { 712 if (mEmptyView != null) { 713 mEmptyView.setText(R.string.wifi_empty_list_wifi_off); 714 if (android.provider.Settings.Global.getInt(getActivity().getContentResolver(), 715 android.provider.Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1) { 716 mEmptyView.append("\n\n"); 717 int resId; 718 if (android.provider.Settings.Secure.isLocationProviderEnabled( 719 getActivity().getContentResolver(), LocationManager.NETWORK_PROVIDER)) { 720 resId = R.string.wifi_scan_notify_text_location_on; 721 } else { 722 resId = R.string.wifi_scan_notify_text_location_off; 723 } 724 CharSequence charSeq = getText(resId); 725 mEmptyView.append(charSeq); 726 } 727 } 728 getPreferenceScreen().removeAll(); 729 } 730 731 private void addMessagePreference(int messageId) { 732 if (mEmptyView != null) mEmptyView.setText(messageId); 733 getPreferenceScreen().removeAll(); 734 } 735 736 /** Returns sorted list of access points */ 737 private static List<AccessPoint> constructAccessPoints(Context context, 738 WifiManager wifiManager, WifiInfo lastInfo, NetworkInfo lastNetworkInfo) { 739 ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>(); 740 /** Lookup table to more quickly update AccessPoints by only considering objects with the 741 * correct SSID. Maps SSID -> List of AccessPoints with the given SSID. */ 742 Multimap<String, AccessPoint> apMap = new Multimap<String, AccessPoint>(); 743 744 final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks(); 745 if (configs != null) { 746 // Update "Saved Networks" menu option. 747 if (savedNetworksExist != (configs.size() > 0)) { 748 savedNetworksExist = !savedNetworksExist; 749 if (context instanceof Activity) { 750 ((Activity) context).invalidateOptionsMenu(); 751 } 752 } 753 for (WifiConfiguration config : configs) { 754 if (config.selfAdded && config.numAssociation == 0) { 755 continue; 756 } 757 AccessPoint accessPoint = new AccessPoint(context, config); 758 if (lastInfo != null && lastNetworkInfo != null) { 759 accessPoint.update(lastInfo, lastNetworkInfo); 760 } 761 accessPoints.add(accessPoint); 762 apMap.put(accessPoint.ssid, accessPoint); 763 } 764 } 765 766 final List<ScanResult> results = wifiManager.getScanResults(); 767 if (results != null) { 768 for (ScanResult result : results) { 769 // Ignore hidden and ad-hoc networks. 770 if (result.SSID == null || result.SSID.length() == 0 || 771 result.capabilities.contains("[IBSS]")) { 772 continue; 773 } 774 775 boolean found = false; 776 for (AccessPoint accessPoint : apMap.getAll(result.SSID)) { 777 if (accessPoint.update(result)) 778 found = true; 779 } 780 if (!found) { 781 AccessPoint accessPoint = new AccessPoint(context, result); 782 if (lastInfo != null && lastNetworkInfo != null) { 783 accessPoint.update(lastInfo, lastNetworkInfo); 784 } 785 accessPoints.add(accessPoint); 786 apMap.put(accessPoint.ssid, accessPoint); 787 } 788 } 789 } 790 791 // Pre-sort accessPoints to speed preference insertion 792 Collections.sort(accessPoints); 793 return accessPoints; 794 } 795 796 private void handleEvent(Intent intent) { 797 String action = intent.getAction(); 798 if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) { 799 updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 800 WifiManager.WIFI_STATE_UNKNOWN)); 801 } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) || 802 WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) || 803 WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) { 804 updateAccessPoints(); 805 } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) { 806 NetworkInfo info = (NetworkInfo) intent.getParcelableExtra( 807 WifiManager.EXTRA_NETWORK_INFO); 808 mConnected.set(info.isConnected()); 809 changeNextButtonState(info.isConnected()); 810 updateAccessPoints(); 811 updateNetworkInfo(info); 812 } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) { 813 updateNetworkInfo(null); 814 } 815 } 816 817 private void updateNetworkInfo(NetworkInfo networkInfo) { 818 /* sticky broadcasts can call this when wifi is disabled */ 819 if (!mWifiManager.isWifiEnabled()) { 820 mScanner.pause(); 821 return; 822 } 823 824 if (networkInfo != null && 825 networkInfo.getDetailedState() == DetailedState.OBTAINING_IPADDR) { 826 mScanner.pause(); 827 } else { 828 mScanner.resume(); 829 } 830 831 mLastInfo = mWifiManager.getConnectionInfo(); 832 if (networkInfo != null) { 833 mLastNetworkInfo = networkInfo; 834 } 835 836 for (int i = getPreferenceScreen().getPreferenceCount() - 1; i >= 0; --i) { 837 // Maybe there's a WifiConfigPreference 838 Preference preference = getPreferenceScreen().getPreference(i); 839 if (preference instanceof AccessPoint) { 840 final AccessPoint accessPoint = (AccessPoint) preference; 841 accessPoint.update(mLastInfo, mLastNetworkInfo); 842 } 843 } 844 } 845 846 private void updateWifiState(int state) { 847 Activity activity = getActivity(); 848 if (activity != null) { 849 activity.invalidateOptionsMenu(); 850 } 851 852 switch (state) { 853 case WifiManager.WIFI_STATE_ENABLED: 854 mScanner.resume(); 855 return; // not break, to avoid the call to pause() below 856 857 case WifiManager.WIFI_STATE_ENABLING: 858 addMessagePreference(R.string.wifi_starting); 859 break; 860 861 case WifiManager.WIFI_STATE_DISABLED: 862 setOffMessage(); 863 break; 864 } 865 866 mLastInfo = null; 867 mLastNetworkInfo = null; 868 mScanner.pause(); 869 } 870 871 /** 872 * Renames/replaces "Next" button when appropriate. "Next" button usually exists in 873 * Wifi setup screens, not in usual wifi settings screen. 874 * 875 * @param enabled true when the device is connected to a wifi network. 876 */ 877 private void changeNextButtonState(boolean enabled) { 878 if (mEnableNextOnConnection && hasNextButton()) { 879 getNextButton().setEnabled(enabled); 880 } 881 } 882 883 @Override 884 public void onClick(DialogInterface dialogInterface, int button) { 885 if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) { 886 forget(); 887 } else if (button == WifiDialog.BUTTON_SUBMIT) { 888 if (mDialog != null) { 889 submit(mDialog.getController()); 890 } 891 } 892 } 893 894 /* package */ void submit(WifiConfigController configController) { 895 896 final WifiConfiguration config = configController.getConfig(); 897 898 if (config == null) { 899 if (mSelectedAccessPoint != null 900 && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 901 connect(mSelectedAccessPoint.networkId); 902 } 903 } else if (config.networkId != INVALID_NETWORK_ID) { 904 if (mSelectedAccessPoint != null) { 905 mWifiManager.save(config, mSaveListener); 906 } 907 } else { 908 if (configController.isEdit()) { 909 mWifiManager.save(config, mSaveListener); 910 } else { 911 connect(config); 912 } 913 } 914 915 if (mWifiManager.isWifiEnabled()) { 916 mScanner.resume(); 917 } 918 updateAccessPoints(); 919 } 920 921 /* package */ void forget() { 922 if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) { 923 if (mSelectedAccessPoint.getNetworkInfo().getState() != State.DISCONNECTED) { 924 // Network is active but has no network ID - must be ephemeral. 925 mWifiManager.disableEphemeralNetwork( 926 AccessPoint.convertToQuotedString(mSelectedAccessPoint.ssid)); 927 } else { 928 // Should not happen, but a monkey seems to trigger it 929 Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig()); 930 return; 931 } 932 } else { 933 mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener); 934 } 935 936 937 if (mWifiManager.isWifiEnabled()) { 938 mScanner.resume(); 939 } 940 updateAccessPoints(); 941 942 // We need to rename/replace "Next" button in wifi setup context. 943 changeNextButtonState(false); 944 } 945 946 protected void connect(final WifiConfiguration config) { 947 mWifiManager.connect(config, mConnectListener); 948 } 949 950 protected void connect(final int networkId) { 951 mWifiManager.connect(networkId, mConnectListener); 952 } 953 954 /** 955 * Refreshes acccess points and ask Wifi module to scan networks again. 956 */ 957 /* package */ void refreshAccessPoints() { 958 if (mWifiManager.isWifiEnabled()) { 959 mScanner.resume(); 960 } 961 962 getPreferenceScreen().removeAll(); 963 } 964 965 /** 966 * Called when "add network" button is pressed. 967 */ 968 /* package */ void onAddNetworkPressed() { 969 // No exact access point is selected. 970 mSelectedAccessPoint = null; 971 showDialog(null, true); 972 } 973 974 /* package */ int getAccessPointsCount() { 975 final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); 976 if (wifiIsEnabled) { 977 return getPreferenceScreen().getPreferenceCount(); 978 } else { 979 return 0; 980 } 981 } 982 983 /** 984 * Requests wifi module to pause wifi scan. May be ignored when the module is disabled. 985 */ 986 /* package */ void pauseWifiScan() { 987 if (mWifiManager.isWifiEnabled()) { 988 mScanner.pause(); 989 } 990 } 991 992 /** 993 * Requests wifi module to resume wifi scan. May be ignored when the module is disabled. 994 */ 995 /* package */ void resumeWifiScan() { 996 if (mWifiManager.isWifiEnabled()) { 997 mScanner.resume(); 998 } 999 } 1000 1001 @Override 1002 protected int getHelpResource() { 1003 return R.string.help_url_wifi; 1004 } 1005 1006 public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER = 1007 new BaseSearchIndexProvider() { 1008 @Override 1009 public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) { 1010 final List<SearchIndexableRaw> result = new ArrayList<SearchIndexableRaw>(); 1011 final Resources res = context.getResources(); 1012 1013 // Add fragment title 1014 SearchIndexableRaw data = new SearchIndexableRaw(context); 1015 data.title = res.getString(R.string.wifi_settings); 1016 data.screenTitle = res.getString(R.string.wifi_settings); 1017 data.keywords = res.getString(R.string.keywords_wifi); 1018 result.add(data); 1019 1020 // Add available Wi-Fi access points 1021 WifiManager wifiManager = 1022 (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 1023 final Collection<AccessPoint> accessPoints = 1024 constructAccessPoints(context, wifiManager, null, null); 1025 for (AccessPoint accessPoint : accessPoints) { 1026 // We are indexing only the saved Wi-Fi networks. 1027 if (accessPoint.getConfig() == null) continue; 1028 data = new SearchIndexableRaw(context); 1029 data.title = accessPoint.getTitle().toString(); 1030 data.screenTitle = res.getString(R.string.wifi_settings); 1031 data.enabled = enabled; 1032 result.add(data); 1033 } 1034 1035 return result; 1036 } 1037 }; 1038} 1039