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