WifiSettings.java revision fc86669031e9c11efa688cbf95e53c77dbc0a03d
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; 20 21import android.app.ActionBar; 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.pm.PackageManager; 30import android.content.res.Resources; 31import android.net.ConnectivityManager; 32import android.net.NetworkInfo; 33import android.net.NetworkInfo.DetailedState; 34import android.net.wifi.ScanResult; 35import android.net.wifi.SupplicantState; 36import android.net.wifi.WifiConfiguration; 37import android.net.wifi.WifiInfo; 38import android.net.wifi.WifiManager; 39import android.net.wifi.WpsInfo; 40import android.os.Bundle; 41import android.os.Handler; 42import android.os.Message; 43import android.preference.Preference; 44import android.preference.PreferenceActivity; 45import android.preference.PreferenceScreen; 46import android.security.Credentials; 47import android.security.KeyStore; 48import android.util.AttributeSet; 49import android.util.Log; 50import android.view.ContextMenu; 51import android.view.ContextMenu.ContextMenuInfo; 52import android.view.Gravity; 53import android.view.LayoutInflater; 54import android.view.Menu; 55import android.view.MenuInflater; 56import android.view.MenuItem; 57import android.view.View; 58import android.view.View.OnClickListener; 59import android.view.ViewGroup; 60import android.widget.AdapterView.AdapterContextMenuInfo; 61import android.widget.ImageButton; 62import android.widget.RelativeLayout; 63import android.widget.Switch; 64import android.widget.TextView; 65import android.widget.Toast; 66 67import com.android.settings.R; 68import com.android.settings.SettingsPreferenceFragment; 69import com.android.settings.wifi.p2p.WifiP2pSettings; 70 71import java.util.ArrayList; 72import java.util.Collection; 73import java.util.Collections; 74import java.util.HashMap; 75import java.util.List; 76import java.util.concurrent.atomic.AtomicBoolean; 77 78/** 79 * Two types of UI are provided here. 80 * 81 * The first is for "usual Settings", appearing as any other Setup fragment. 82 * 83 * The second is for Setup Wizard, with a simplified interface that hides the action bar 84 * and menus. 85 */ 86public class WifiSettings extends SettingsPreferenceFragment 87 implements DialogInterface.OnClickListener { 88 private static final String TAG = "WifiSettings"; 89 private static final int MENU_ID_WPS_PBC = Menu.FIRST; 90 private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1; 91 private static final int MENU_ID_P2P = Menu.FIRST + 2; 92 private static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3; 93 private static final int MENU_ID_ADVANCED = Menu.FIRST + 4; 94 private static final int MENU_ID_SCAN = Menu.FIRST + 5; 95 private static final int MENU_ID_CONNECT = Menu.FIRST + 6; 96 private static final int MENU_ID_FORGET = Menu.FIRST + 7; 97 private static final int MENU_ID_MODIFY = Menu.FIRST + 8; 98 99 private static final int WIFI_DIALOG_ID = 1; 100 private static final int WPS_PBC_DIALOG_ID = 2; 101 private static final int WPS_PIN_DIALOG_ID = 3; 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 final IntentFilter mFilter; 111 private final BroadcastReceiver mReceiver; 112 private final Scanner mScanner; 113 114 private WifiManager mWifiManager; 115 private WifiManager.Channel mChannel; 116 private WifiManager.ActionListener mConnectListener; 117 private WifiManager.ActionListener mSaveListener; 118 private WifiManager.ActionListener mForgetListener; 119 private boolean mP2pSupported; 120 121 122 private WifiEnabler mWifiEnabler; 123 // An access point being editted is stored here. 124 private AccessPoint mSelectedAccessPoint; 125 126 private DetailedState mLastState; 127 private WifiInfo mLastInfo; 128 129 private AtomicBoolean mConnected = new AtomicBoolean(false); 130 131 private int mKeyStoreNetworkId = INVALID_NETWORK_ID; 132 133 private WifiDialog mDialog; 134 135 private TextView mEmptyView; 136 137 /* Used in Wifi Setup context */ 138 139 // this boolean extra specifies whether to disable the Next button when not connected 140 private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect"; 141 142 // this boolean extra specifies whether to auto finish when connection is established 143 private static final String EXTRA_AUTO_FINISH_ON_CONNECT = "wifi_auto_finish_on_connect"; 144 145 // this boolean extra is set if we are being invoked by the Setup Wizard 146 private static final String EXTRA_IS_FIRST_RUN = "firstRun"; 147 148 private static final String EXTRA_WIFI_DISABLE_BACK = "wifi_disable_back"; 149 150 // should Next button only be enabled when we have a connection? 151 private boolean mEnableNextOnConnection; 152 153 // should activity finish once we have a connection? 154 private boolean mAutoFinishOnConnection; 155 156 // Save the dialog details 157 private boolean mDlgEdit; 158 private AccessPoint mDlgAccessPoint; 159 private Bundle mAccessPointSavedState; 160 161 // the action bar uses a different set of controls for Setup Wizard 162 private boolean mSetupWizardMode; 163 164 /* End of "used in Wifi Setup context" */ 165 166 public WifiSettings() { 167 mFilter = new IntentFilter(); 168 mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); 169 mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 170 mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION); 171 mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); 172 mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION); 173 mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION); 174 mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); 175 mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); 176 177 mReceiver = new BroadcastReceiver() { 178 @Override 179 public void onReceive(Context context, Intent intent) { 180 handleEvent(context, intent); 181 } 182 }; 183 184 mScanner = new Scanner(); 185 } 186 187 @Override 188 public void onCreate(Bundle icicle) { 189 // Set this flag early, as it's needed by getHelpResource(), which is called by super 190 mSetupWizardMode = getActivity().getIntent().getBooleanExtra(EXTRA_IS_FIRST_RUN, false); 191 192 super.onCreate(icicle); 193 } 194 195 @Override 196 public View onCreateView(LayoutInflater inflater, ViewGroup container, 197 Bundle savedInstanceState) { 198 if (mSetupWizardMode) { 199 View view = inflater.inflate(R.layout.setup_preference, container, false); 200 ImageButton b1 = (ImageButton) view.findViewById(R.id.wps_push); 201 if (b1 != null) { 202 b1.setOnClickListener(new OnClickListener() { 203 @Override 204 public void onClick(View v) { 205 showDialog(WPS_PBC_DIALOG_ID); 206 } 207 }); 208 } 209 ImageButton b2 = (ImageButton) view.findViewById(R.id.add_network); 210 if (b2 != null) { 211 b2.setOnClickListener(new OnClickListener() { 212 @Override 213 public void onClick(View v) { 214 if (mWifiManager.isWifiEnabled()) { 215 onAddNetworkPressed(); 216 } 217 } 218 }); 219 } 220 return view; 221 } else { 222 return super.onCreateView(inflater, container, savedInstanceState); 223 } 224 } 225 226 @Override 227 public void onActivityCreated(Bundle savedInstanceState) { 228 // We don't call super.onActivityCreated() here, since it assumes we already set up 229 // Preference (probably in onCreate()), while WifiSettings exceptionally set it up in 230 // this method. 231 232 mP2pSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT); 233 mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 234 mChannel = mWifiManager.initialize(getActivity(), getActivity().getMainLooper(), null); 235 236 mConnectListener = new WifiManager.ActionListener() { 237 public void onSuccess() { 238 } 239 public void onFailure(int reason) { 240 Toast.makeText(getActivity(), 241 R.string.wifi_failed_connect_message, 242 Toast.LENGTH_SHORT).show(); 243 } 244 }; 245 246 mSaveListener = new WifiManager.ActionListener() { 247 public void onSuccess() { 248 } 249 public void onFailure(int reason) { 250 Toast.makeText(getActivity(), 251 R.string.wifi_failed_save_message, 252 Toast.LENGTH_SHORT).show(); 253 } 254 }; 255 256 mForgetListener = new WifiManager.ActionListener() { 257 public void onSuccess() { 258 } 259 public void onFailure(int reason) { 260 Toast.makeText(getActivity(), 261 R.string.wifi_failed_forget_message, 262 Toast.LENGTH_SHORT).show(); 263 } 264 }; 265 266 if (savedInstanceState != null 267 && savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) { 268 mDlgEdit = savedInstanceState.getBoolean(SAVE_DIALOG_EDIT_MODE); 269 mAccessPointSavedState = savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE); 270 } 271 272 final Activity activity = getActivity(); 273 final Intent intent = activity.getIntent(); 274 275 // first if we're supposed to finish once we have a connection 276 mAutoFinishOnConnection = intent.getBooleanExtra(EXTRA_AUTO_FINISH_ON_CONNECT, false); 277 278 if (mAutoFinishOnConnection) { 279 // Hide the next button 280 if (hasNextButton()) { 281 getNextButton().setVisibility(View.GONE); 282 } 283 284 final ConnectivityManager connectivity = (ConnectivityManager) 285 getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 286 if (connectivity != null 287 && connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) { 288 activity.finish(); 289 return; 290 } 291 } 292 293 // if we're supposed to enable/disable the Next button based on our current connection 294 // state, start it off in the right state 295 mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false); 296 297 if (mEnableNextOnConnection) { 298 if (hasNextButton()) { 299 final ConnectivityManager connectivity = (ConnectivityManager) 300 getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 301 if (connectivity != null) { 302 NetworkInfo info = connectivity.getNetworkInfo( 303 ConnectivityManager.TYPE_WIFI); 304 changeNextButtonState(info.isConnected()); 305 } 306 } 307 } 308 309 addPreferencesFromResource(R.xml.wifi_settings); 310 311 // Back key is disabled if requested 312 if (intent.getBooleanExtra(EXTRA_WIFI_DISABLE_BACK, false)) { 313 getView().setSystemUiVisibility(View.STATUS_BAR_DISABLE_BACK); 314 } 315 316 // On/off switch is hidden for Setup Wizard 317 if (!mSetupWizardMode) { 318 Switch actionBarSwitch = new Switch(activity); 319 320 if (activity instanceof PreferenceActivity) { 321 PreferenceActivity preferenceActivity = (PreferenceActivity) activity; 322 if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) { 323 final int padding = activity.getResources().getDimensionPixelSize( 324 R.dimen.action_bar_switch_padding); 325 actionBarSwitch.setPadding(0, 0, padding, 0); 326 activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, 327 ActionBar.DISPLAY_SHOW_CUSTOM); 328 activity.getActionBar().setCustomView(actionBarSwitch, new ActionBar.LayoutParams( 329 ActionBar.LayoutParams.WRAP_CONTENT, 330 ActionBar.LayoutParams.WRAP_CONTENT, 331 Gravity.CENTER_VERTICAL | Gravity.RIGHT)); 332 } 333 } 334 335 mWifiEnabler = new WifiEnabler(activity, actionBarSwitch); 336 } 337 338 mEmptyView = (TextView) getView().findViewById(android.R.id.empty); 339 getListView().setEmptyView(mEmptyView); 340 341 if (!mSetupWizardMode) { 342 registerForContextMenu(getListView()); 343 } 344 setHasOptionsMenu(true); 345 346 // After confirming PreferenceScreen is available, we call super. 347 super.onActivityCreated(savedInstanceState); 348 } 349 350 @Override 351 public void onResume() { 352 super.onResume(); 353 if (mWifiEnabler != null) { 354 mWifiEnabler.resume(); 355 } 356 357 getActivity().registerReceiver(mReceiver, mFilter); 358 if (mKeyStoreNetworkId != INVALID_NETWORK_ID && 359 KeyStore.getInstance().state() == KeyStore.State.UNLOCKED) { 360 mWifiManager.connect(mChannel, mKeyStoreNetworkId, mConnectListener); 361 } 362 mKeyStoreNetworkId = INVALID_NETWORK_ID; 363 364 updateAccessPoints(); 365 } 366 367 @Override 368 public void onPause() { 369 super.onPause(); 370 if (mWifiEnabler != null) { 371 mWifiEnabler.pause(); 372 } 373 getActivity().unregisterReceiver(mReceiver); 374 mScanner.pause(); 375 } 376 377 @Override 378 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 379 final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); 380 if (mSetupWizardMode) { 381 // FIXME: add setIcon() when graphics are available 382 menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc) 383 .setIcon(R.drawable.ic_wps) 384 .setEnabled(wifiIsEnabled) 385 .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 386 menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network) 387 .setEnabled(wifiIsEnabled) 388 .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 389 } else { 390 menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc) 391 .setEnabled(wifiIsEnabled) 392 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 393 menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network) 394 .setEnabled(wifiIsEnabled) 395 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 396 menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan) 397 //.setIcon(R.drawable.ic_menu_scan_network) 398 .setEnabled(wifiIsEnabled) 399 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 400 menu.add(Menu.NONE, MENU_ID_WPS_PIN, 0, R.string.wifi_menu_wps_pin) 401 .setEnabled(wifiIsEnabled) 402 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 403 if (mP2pSupported) { 404 menu.add(Menu.NONE, MENU_ID_P2P, 0, R.string.wifi_menu_p2p) 405 .setEnabled(wifiIsEnabled) 406 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 407 } 408 menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced) 409 //.setIcon(android.R.drawable.ic_menu_manage) 410 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 411 } 412 super.onCreateOptionsMenu(menu, inflater); 413 } 414 415 @Override 416 public void onSaveInstanceState(Bundle outState) { 417 super.onSaveInstanceState(outState); 418 419 // If the dialog is showing, save its state. 420 if (mDialog != null && mDialog.isShowing()) { 421 outState.putBoolean(SAVE_DIALOG_EDIT_MODE, mDlgEdit); 422 if (mDlgAccessPoint != null) { 423 mAccessPointSavedState = new Bundle(); 424 mDlgAccessPoint.saveWifiState(mAccessPointSavedState); 425 outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState); 426 } 427 } 428 } 429 430 @Override 431 public boolean onOptionsItemSelected(MenuItem item) { 432 switch (item.getItemId()) { 433 case MENU_ID_WPS_PBC: 434 showDialog(WPS_PBC_DIALOG_ID); 435 return true; 436 case MENU_ID_P2P: 437 if (getActivity() instanceof PreferenceActivity) { 438 ((PreferenceActivity) getActivity()).startPreferencePanel( 439 WifiP2pSettings.class.getCanonicalName(), 440 null, 441 R.string.wifi_p2p_settings_title, null, 442 this, 0); 443 } else { 444 startFragment(this, WifiP2pSettings.class.getCanonicalName(), -1, null); 445 } 446 return true; 447 case MENU_ID_WPS_PIN: 448 showDialog(WPS_PIN_DIALOG_ID); 449 return true; 450 case MENU_ID_SCAN: 451 if (mWifiManager.isWifiEnabled()) { 452 mScanner.forceScan(); 453 } 454 return true; 455 case MENU_ID_ADD_NETWORK: 456 if (mWifiManager.isWifiEnabled()) { 457 onAddNetworkPressed(); 458 } 459 return true; 460 case MENU_ID_ADVANCED: 461 if (getActivity() instanceof PreferenceActivity) { 462 ((PreferenceActivity) getActivity()).startPreferencePanel( 463 AdvancedWifiSettings.class.getCanonicalName(), 464 null, 465 R.string.wifi_advanced_titlebar, null, 466 this, 0); 467 } else { 468 startFragment(this, AdvancedWifiSettings.class.getCanonicalName(), -1, null); 469 } 470 return true; 471 } 472 return super.onOptionsItemSelected(item); 473 } 474 475 @Override 476 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) { 477 if (info instanceof AdapterContextMenuInfo) { 478 Preference preference = (Preference) getListView().getItemAtPosition( 479 ((AdapterContextMenuInfo) info).position); 480 481 if (preference instanceof AccessPoint) { 482 mSelectedAccessPoint = (AccessPoint) preference; 483 menu.setHeaderTitle(mSelectedAccessPoint.ssid); 484 if (mSelectedAccessPoint.getLevel() != -1 485 && mSelectedAccessPoint.getState() == null) { 486 menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect); 487 } 488 if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 489 menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget); 490 menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify); 491 } 492 } 493 } 494 } 495 496 @Override 497 public boolean onContextItemSelected(MenuItem item) { 498 if (mSelectedAccessPoint == null) { 499 return super.onContextItemSelected(item); 500 } 501 switch (item.getItemId()) { 502 case MENU_ID_CONNECT: { 503 if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 504 if (!requireKeyStore(mSelectedAccessPoint.getConfig())) { 505 mWifiManager.connect(mChannel, mSelectedAccessPoint.networkId, 506 mConnectListener); 507 } 508 } else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) { 509 /** Bypass dialog for unsecured networks */ 510 mSelectedAccessPoint.generateOpenNetworkConfig(); 511 mWifiManager.connect(mChannel, mSelectedAccessPoint.getConfig(), 512 mConnectListener); 513 } else { 514 showDialog(mSelectedAccessPoint, true); 515 } 516 return true; 517 } 518 case MENU_ID_FORGET: { 519 mWifiManager.forget(mChannel, mSelectedAccessPoint.networkId, mForgetListener); 520 return true; 521 } 522 case MENU_ID_MODIFY: { 523 showDialog(mSelectedAccessPoint, true); 524 return true; 525 } 526 } 527 return super.onContextItemSelected(item); 528 } 529 530 @Override 531 public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) { 532 if (preference instanceof AccessPoint) { 533 mSelectedAccessPoint = (AccessPoint) preference; 534 /** Bypass dialog for unsecured, unsaved networks */ 535 if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE && 536 mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) { 537 mSelectedAccessPoint.generateOpenNetworkConfig(); 538 mWifiManager.connect(mChannel, mSelectedAccessPoint.getConfig(), mConnectListener); 539 } else { 540 showDialog(mSelectedAccessPoint, false); 541 } 542 } else { 543 return super.onPreferenceTreeClick(screen, preference); 544 } 545 return true; 546 } 547 548 private void showDialog(AccessPoint accessPoint, boolean edit) { 549 if (mDialog != null) { 550 removeDialog(WIFI_DIALOG_ID); 551 mDialog = null; 552 } 553 554 // Save the access point and edit mode 555 mDlgAccessPoint = accessPoint; 556 mDlgEdit = edit; 557 558 showDialog(WIFI_DIALOG_ID); 559 } 560 561 @Override 562 public Dialog onCreateDialog(int dialogId) { 563 switch (dialogId) { 564 case WIFI_DIALOG_ID: 565 AccessPoint ap = mDlgAccessPoint; // For manual launch 566 if (ap == null) { // For re-launch from saved state 567 if (mAccessPointSavedState != null) { 568 ap = new AccessPoint(getActivity(), mAccessPointSavedState); 569 // For repeated orientation changes 570 mDlgAccessPoint = ap; 571 } 572 } 573 // If it's still null, fine, it's for Add Network 574 mSelectedAccessPoint = ap; 575 mDialog = new WifiDialog(getActivity(), this, ap, mDlgEdit); 576 return mDialog; 577 case WPS_PBC_DIALOG_ID: 578 return new WpsDialog(getActivity(), WpsInfo.PBC); 579 case WPS_PIN_DIALOG_ID: 580 return new WpsDialog(getActivity(), WpsInfo.DISPLAY); 581 } 582 return super.onCreateDialog(dialogId); 583 } 584 585 private boolean requireKeyStore(WifiConfiguration config) { 586 if (WifiConfigController.requireKeyStore(config) && 587 KeyStore.getInstance().state() != KeyStore.State.UNLOCKED) { 588 mKeyStoreNetworkId = config.networkId; 589 Credentials.getInstance().unlock(getActivity()); 590 return true; 591 } 592 return false; 593 } 594 595 /** 596 * Shows the latest access points available with supplimental information like 597 * the strength of network and the security for it. 598 */ 599 private void updateAccessPoints() { 600 // Safeguard from some delayed event handling 601 if (getActivity() == null) return; 602 603 final int wifiState = mWifiManager.getWifiState(); 604 605 switch (wifiState) { 606 case WifiManager.WIFI_STATE_ENABLED: 607 // AccessPoints are automatically sorted with TreeSet. 608 final Collection<AccessPoint> accessPoints = constructAccessPoints(); 609 getPreferenceScreen().removeAll(); 610 if(accessPoints.size() == 0) { 611 addMessagePreference(R.string.wifi_empty_list_wifi_on); 612 } 613 for (AccessPoint accessPoint : accessPoints) { 614 getPreferenceScreen().addPreference(accessPoint); 615 } 616 break; 617 618 case WifiManager.WIFI_STATE_ENABLING: 619 getPreferenceScreen().removeAll(); 620 break; 621 622 case WifiManager.WIFI_STATE_DISABLING: 623 addMessagePreference(R.string.wifi_stopping); 624 break; 625 626 case WifiManager.WIFI_STATE_DISABLED: 627 addMessagePreference(R.string.wifi_empty_list_wifi_off); 628 break; 629 } 630 } 631 632 private void addMessagePreference(int messageId) { 633 if (mEmptyView != null) mEmptyView.setText(messageId); 634 getPreferenceScreen().removeAll(); 635 } 636 637 /** Returns sorted list of access points */ 638 private List<AccessPoint> constructAccessPoints() { 639 ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>(); 640 /** Lookup table to more quickly update AccessPoints by only considering objects with the 641 * correct SSID. Maps SSID -> List of AccessPoints with the given SSID. */ 642 Multimap<String, AccessPoint> apMap = new Multimap<String, AccessPoint>(); 643 644 final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks(); 645 if (configs != null) { 646 for (WifiConfiguration config : configs) { 647 AccessPoint accessPoint = new AccessPoint(getActivity(), config); 648 accessPoint.update(mLastInfo, mLastState); 649 accessPoints.add(accessPoint); 650 apMap.put(accessPoint.ssid, accessPoint); 651 } 652 } 653 654 final List<ScanResult> results = mWifiManager.getScanResults(); 655 if (results != null) { 656 for (ScanResult result : results) { 657 // Ignore hidden and ad-hoc networks. 658 if (result.SSID == null || result.SSID.length() == 0 || 659 result.capabilities.contains("[IBSS]")) { 660 continue; 661 } 662 663 boolean found = false; 664 for (AccessPoint accessPoint : apMap.getAll(result.SSID)) { 665 if (accessPoint.update(result)) 666 found = true; 667 } 668 if (!found) { 669 AccessPoint accessPoint = new AccessPoint(getActivity(), result); 670 accessPoints.add(accessPoint); 671 apMap.put(accessPoint.ssid, accessPoint); 672 } 673 } 674 } 675 676 // Pre-sort accessPoints to speed preference insertion 677 Collections.sort(accessPoints); 678 return accessPoints; 679 } 680 681 /** A restricted multimap for use in constructAccessPoints */ 682 private class Multimap<K,V> { 683 private HashMap<K,List<V>> store = new HashMap<K,List<V>>(); 684 /** retrieve a non-null list of values with key K */ 685 List<V> getAll(K key) { 686 List<V> values = store.get(key); 687 return values != null ? values : Collections.<V>emptyList(); 688 } 689 690 void put(K key, V val) { 691 List<V> curVals = store.get(key); 692 if (curVals == null) { 693 curVals = new ArrayList<V>(3); 694 store.put(key, curVals); 695 } 696 curVals.add(val); 697 } 698 } 699 700 private void handleEvent(Context context, Intent intent) { 701 String action = intent.getAction(); 702 if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) { 703 updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 704 WifiManager.WIFI_STATE_UNKNOWN)); 705 } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) || 706 WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) || 707 WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) { 708 updateAccessPoints(); 709 } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) { 710 //Ignore supplicant state changes when network is connected 711 //TODO: we should deprecate SUPPLICANT_STATE_CHANGED_ACTION and 712 //introduce a broadcast that combines the supplicant and network 713 //network state change events so the apps dont have to worry about 714 //ignoring supplicant state change when network is connected 715 //to get more fine grained information. 716 SupplicantState state = (SupplicantState) intent.getParcelableExtra( 717 WifiManager.EXTRA_NEW_STATE); 718 if (!mConnected.get() && SupplicantState.isHandshakeState(state)) { 719 updateConnectionState(WifiInfo.getDetailedStateOf(state)); 720 } 721 } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) { 722 NetworkInfo info = (NetworkInfo) intent.getParcelableExtra( 723 WifiManager.EXTRA_NETWORK_INFO); 724 mConnected.set(info.isConnected()); 725 changeNextButtonState(info.isConnected()); 726 updateAccessPoints(); 727 updateConnectionState(info.getDetailedState()); 728 if (mAutoFinishOnConnection && info.isConnected()) { 729 getActivity().finish(); 730 return; 731 } 732 } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) { 733 updateConnectionState(null); 734 } 735 } 736 737 private void updateConnectionState(DetailedState state) { 738 /* sticky broadcasts can call this when wifi is disabled */ 739 if (!mWifiManager.isWifiEnabled()) { 740 mScanner.pause(); 741 return; 742 } 743 744 if (state == DetailedState.OBTAINING_IPADDR) { 745 mScanner.pause(); 746 } else { 747 mScanner.resume(); 748 } 749 750 mLastInfo = mWifiManager.getConnectionInfo(); 751 if (state != null) { 752 mLastState = state; 753 } 754 755 for (int i = getPreferenceScreen().getPreferenceCount() - 1; i >= 0; --i) { 756 // Maybe there's a WifiConfigPreference 757 Preference preference = getPreferenceScreen().getPreference(i); 758 if (preference instanceof AccessPoint) { 759 final AccessPoint accessPoint = (AccessPoint) preference; 760 accessPoint.update(mLastInfo, mLastState); 761 } 762 } 763 } 764 765 private void updateWifiState(int state) { 766 getActivity().invalidateOptionsMenu(); 767 768 switch (state) { 769 case WifiManager.WIFI_STATE_ENABLED: 770 mScanner.resume(); 771 return; // not break, to avoid the call to pause() below 772 773 case WifiManager.WIFI_STATE_ENABLING: 774 addMessagePreference(R.string.wifi_starting); 775 break; 776 777 case WifiManager.WIFI_STATE_DISABLED: 778 addMessagePreference(R.string.wifi_empty_list_wifi_off); 779 break; 780 } 781 782 mLastInfo = null; 783 mLastState = null; 784 mScanner.pause(); 785 } 786 787 private class Scanner extends Handler { 788 private int mRetry = 0; 789 790 void resume() { 791 if (!hasMessages(0)) { 792 sendEmptyMessage(0); 793 } 794 } 795 796 void forceScan() { 797 removeMessages(0); 798 sendEmptyMessage(0); 799 } 800 801 void pause() { 802 mRetry = 0; 803 removeMessages(0); 804 } 805 806 @Override 807 public void handleMessage(Message message) { 808 if (mWifiManager.startScanActive()) { 809 mRetry = 0; 810 } else if (++mRetry >= 3) { 811 mRetry = 0; 812 Toast.makeText(getActivity(), R.string.wifi_fail_to_scan, 813 Toast.LENGTH_LONG).show(); 814 return; 815 } 816 sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS); 817 } 818 } 819 820 /** 821 * Renames/replaces "Next" button when appropriate. "Next" button usually exists in 822 * Wifi setup screens, not in usual wifi settings screen. 823 * 824 * @param connected true when the device is connected to a wifi network. 825 */ 826 private void changeNextButtonState(boolean connected) { 827 if (mEnableNextOnConnection && hasNextButton()) { 828 getNextButton().setEnabled(connected); 829 } 830 } 831 832 public void onClick(DialogInterface dialogInterface, int button) { 833 if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) { 834 forget(); 835 } else if (button == WifiDialog.BUTTON_SUBMIT) { 836 submit(mDialog.getController()); 837 } 838 } 839 840 /* package */ void submit(WifiConfigController configController) { 841 842 final WifiConfiguration config = configController.getConfig(); 843 844 if (config == null) { 845 if (mSelectedAccessPoint != null 846 && !requireKeyStore(mSelectedAccessPoint.getConfig()) 847 && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 848 mWifiManager.connect(mChannel, mSelectedAccessPoint.networkId, 849 mConnectListener); 850 } 851 } else if (config.networkId != INVALID_NETWORK_ID) { 852 if (mSelectedAccessPoint != null) { 853 mWifiManager.save(mChannel, config, mSaveListener); 854 } 855 } else { 856 if (configController.isEdit() || requireKeyStore(config)) { 857 mWifiManager.save(mChannel, config, mSaveListener); 858 } else { 859 mWifiManager.connect(mChannel, config, mConnectListener); 860 } 861 } 862 863 if (mWifiManager.isWifiEnabled()) { 864 mScanner.resume(); 865 } 866 updateAccessPoints(); 867 } 868 869 /* package */ void forget() { 870 if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) { 871 // Should not happen, but a monkey seems to triger it 872 Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig()); 873 return; 874 } 875 876 mWifiManager.forget(mChannel, mSelectedAccessPoint.networkId, mForgetListener); 877 878 if (mWifiManager.isWifiEnabled()) { 879 mScanner.resume(); 880 } 881 updateAccessPoints(); 882 883 // We need to rename/replace "Next" button in wifi setup context. 884 changeNextButtonState(false); 885 } 886 887 /** 888 * Refreshes acccess points and ask Wifi module to scan networks again. 889 */ 890 /* package */ void refreshAccessPoints() { 891 if (mWifiManager.isWifiEnabled()) { 892 mScanner.resume(); 893 } 894 895 getPreferenceScreen().removeAll(); 896 } 897 898 /** 899 * Called when "add network" button is pressed. 900 */ 901 /* package */ void onAddNetworkPressed() { 902 // No exact access point is selected. 903 mSelectedAccessPoint = null; 904 showDialog(null, true); 905 } 906 907 /* package */ int getAccessPointsCount() { 908 final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); 909 if (wifiIsEnabled) { 910 return getPreferenceScreen().getPreferenceCount(); 911 } else { 912 return 0; 913 } 914 } 915 916 /** 917 * Requests wifi module to pause wifi scan. May be ignored when the module is disabled. 918 */ 919 /* package */ void pauseWifiScan() { 920 if (mWifiManager.isWifiEnabled()) { 921 mScanner.pause(); 922 } 923 } 924 925 /** 926 * Requests wifi module to resume wifi scan. May be ignored when the module is disabled. 927 */ 928 /* package */ void resumeWifiScan() { 929 if (mWifiManager.isWifiEnabled()) { 930 mScanner.resume(); 931 } 932 } 933 934 @Override 935 protected int getHelpResource() { 936 if (mSetupWizardMode) { 937 return 0; 938 } 939 return R.string.help_url_wifi; 940 } 941 942 /** 943 * Used as the outer frame of all setup wizard pages that need to adjust their margins based 944 * on the total size of the available display. (e.g. side margins set to 10% of total width.) 945 */ 946 public static class ProportionalOuterFrame extends RelativeLayout { 947 public ProportionalOuterFrame(Context context) { 948 super(context); 949 } 950 public ProportionalOuterFrame(Context context, AttributeSet attrs) { 951 super(context, attrs); 952 } 953 public ProportionalOuterFrame(Context context, AttributeSet attrs, int defStyle) { 954 super(context, attrs, defStyle); 955 } 956 957 /** 958 * Set our margins and title area height proportionally to the available display size 959 */ 960 @Override 961 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 962 int parentWidth = MeasureSpec.getSize(widthMeasureSpec); 963 int parentHeight = MeasureSpec.getSize(heightMeasureSpec); 964 final Resources resources = getContext().getResources(); 965 float titleHeight = resources.getFraction(R.dimen.setup_title_height, 1, 1); 966 float sideMargin = resources.getFraction(R.dimen.setup_border_width, 1, 1); 967 int bottom = resources.getDimensionPixelSize(R.dimen.setup_margin_bottom); 968 setPadding( 969 (int) (parentWidth * sideMargin), 970 0, 971 (int) (parentWidth * sideMargin), 972 bottom); 973 View title = findViewById(R.id.title_area); 974 if (title != null) { 975 title.setMinimumHeight((int) (parentHeight * titleHeight)); 976 } 977 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 978 } 979 } 980 981} 982