WifiSettings.java revision 86ea97f4524fe96abeffcba3386753741989cd71
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.preference.PreferenceActivity; 23import android.provider.SearchIndexableResource; 24import com.android.settings.R; 25import com.android.settings.RestrictedSettingsFragment; 26import com.android.settings.SettingsActivity; 27import com.android.settings.search.Indexable; 28import com.android.settings.search.SearchIndexableRaw; 29import com.android.settings.wifi.p2p.WifiP2pSettings; 30 31import android.app.ActionBar; 32import android.app.Activity; 33import android.app.AlertDialog; 34import android.app.Dialog; 35import android.content.BroadcastReceiver; 36import android.content.Context; 37import android.content.DialogInterface; 38import android.content.Intent; 39import android.content.IntentFilter; 40import android.content.pm.PackageManager; 41import android.content.res.Resources; 42import android.content.res.TypedArray; 43import android.location.LocationManager; 44import android.net.ConnectivityManager; 45import android.net.NetworkInfo; 46import android.net.NetworkInfo.DetailedState; 47import android.net.wifi.ScanResult; 48import android.net.wifi.SupplicantState; 49import android.net.wifi.WifiConfiguration; 50import android.net.wifi.WifiInfo; 51import android.net.wifi.WifiManager; 52import android.net.wifi.WpsInfo; 53import android.os.Bundle; 54import android.os.Handler; 55import android.os.Message; 56import android.preference.Preference; 57import android.preference.PreferenceScreen; 58import android.util.AttributeSet; 59import android.util.Log; 60import android.view.ContextMenu; 61import android.view.ContextMenu.ContextMenuInfo; 62import android.view.Gravity; 63import android.view.LayoutInflater; 64import android.view.Menu; 65import android.view.MenuInflater; 66import android.view.MenuItem; 67import android.view.View; 68import android.view.View.OnClickListener; 69import android.view.ViewGroup; 70import android.widget.AdapterView.AdapterContextMenuInfo; 71import android.widget.Button; 72import android.widget.ImageButton; 73import android.widget.PopupMenu; 74import android.widget.PopupMenu.OnMenuItemClickListener; 75import android.widget.RelativeLayout; 76import android.widget.Switch; 77import android.widget.TextView; 78import android.widget.Toast; 79 80import java.util.ArrayList; 81import java.util.Collection; 82import java.util.Collections; 83import java.util.HashMap; 84import java.util.List; 85import java.util.concurrent.atomic.AtomicBoolean; 86 87/** 88 * Two types of UI are provided here. 89 * 90 * The first is for "usual Settings", appearing as any other Setup fragment. 91 * 92 * The second is for Setup Wizard, with a simplified interface that hides the action bar 93 * and menus. 94 */ 95public class WifiSettings extends RestrictedSettingsFragment 96 implements DialogInterface.OnClickListener, Indexable { 97 private static final String TAG = "WifiSettings"; 98 private static final int MENU_ID_WPS_PBC = Menu.FIRST; 99 private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1; 100 private static final int MENU_ID_P2P = Menu.FIRST + 2; 101 private static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3; 102 private static final int MENU_ID_ADVANCED = Menu.FIRST + 4; 103 private static final int MENU_ID_SCAN = Menu.FIRST + 5; 104 private static final int MENU_ID_CONNECT = Menu.FIRST + 6; 105 private static final int MENU_ID_FORGET = Menu.FIRST + 7; 106 private static final int MENU_ID_MODIFY = Menu.FIRST + 8; 107 108 private static final int WIFI_DIALOG_ID = 1; 109 private static final int WPS_PBC_DIALOG_ID = 2; 110 private static final int WPS_PIN_DIALOG_ID = 3; 111 private static final int WIFI_SKIPPED_DIALOG_ID = 4; 112 private static final int WIFI_AND_MOBILE_SKIPPED_DIALOG_ID = 5; 113 114 // Combo scans can take 5-6s to complete - set to 10s. 115 private static final int WIFI_RESCAN_INTERVAL_MS = 10 * 1000; 116 117 // Instance state keys 118 private static final String SAVE_DIALOG_EDIT_MODE = "edit_mode"; 119 private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state"; 120 121 // Activity result when pressing the Skip button 122 private static final int RESULT_SKIP = Activity.RESULT_FIRST_USER; 123 124 private final IntentFilter mFilter; 125 private final BroadcastReceiver mReceiver; 126 private final Scanner mScanner; 127 128 private WifiManager mWifiManager; 129 private WifiManager.ActionListener mConnectListener; 130 private WifiManager.ActionListener mSaveListener; 131 private WifiManager.ActionListener mForgetListener; 132 private boolean mP2pSupported; 133 134 private WifiEnabler mWifiEnabler; 135 // An access point being editted is stored here. 136 private AccessPoint mSelectedAccessPoint; 137 138 private DetailedState mLastState; 139 private WifiInfo mLastInfo; 140 141 private final AtomicBoolean mConnected = new AtomicBoolean(false); 142 143 private WifiDialog mDialog; 144 145 private TextView mEmptyView; 146 147 /* Used in Wifi Setup context */ 148 149 // this boolean extra specifies whether to disable the Next button when not connected 150 private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect"; 151 152 // this boolean extra specifies whether to auto finish when connection is established 153 private static final String EXTRA_AUTO_FINISH_ON_CONNECT = "wifi_auto_finish_on_connect"; 154 155 // this boolean extra shows a custom button that we can control 156 protected static final String EXTRA_SHOW_CUSTOM_BUTTON = "wifi_show_custom_button"; 157 158 // show a text regarding data charges when wifi connection is required during setup wizard 159 protected static final String EXTRA_SHOW_WIFI_REQUIRED_INFO = "wifi_show_wifi_required_info"; 160 161 // this boolean extra is set if we are being invoked by the Setup Wizard 162 private static final String EXTRA_IS_FIRST_RUN = "firstRun"; 163 164 // should Next button only be enabled when we have a connection? 165 private boolean mEnableNextOnConnection; 166 167 // should activity finish once we have a connection? 168 private boolean mAutoFinishOnConnection; 169 170 // Save the dialog details 171 private boolean mDlgEdit; 172 private AccessPoint mDlgAccessPoint; 173 private Bundle mAccessPointSavedState; 174 175 // the action bar uses a different set of controls for Setup Wizard 176 private boolean mSetupWizardMode; 177 178 private Switch mSwitch; 179 180 /* End of "used in Wifi Setup context" */ 181 182 public WifiSettings() { 183 super(DISALLOW_CONFIG_WIFI); 184 mFilter = new IntentFilter(); 185 mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); 186 mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 187 mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION); 188 mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); 189 mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION); 190 mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION); 191 mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); 192 mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); 193 194 mReceiver = new BroadcastReceiver() { 195 @Override 196 public void onReceive(Context context, Intent intent) { 197 handleEvent(context, intent); 198 } 199 }; 200 201 mScanner = new Scanner(); 202 } 203 204 @Override 205 public void onCreate(Bundle icicle) { 206 // Set this flag early, as it's needed by getHelpResource(), which is called by super 207 mSetupWizardMode = getActivity().getIntent().getBooleanExtra(EXTRA_IS_FIRST_RUN, false); 208 209 super.onCreate(icicle); 210 } 211 212 @Override 213 public View onCreateView(final LayoutInflater inflater, ViewGroup container, 214 Bundle savedInstanceState) { 215 if (mSetupWizardMode) { 216 View view = inflater.inflate(R.layout.setup_preference, container, false); 217 View other = view.findViewById(R.id.other_network); 218 other.setOnClickListener(new OnClickListener() { 219 @Override 220 public void onClick(View v) { 221 if (mWifiManager.isWifiEnabled()) { 222 onAddNetworkPressed(); 223 } 224 } 225 }); 226 final ImageButton b = (ImageButton) view.findViewById(R.id.more); 227 if (b != null) { 228 b.setOnClickListener(new OnClickListener() { 229 @Override 230 public void onClick(View v) { 231 if (mWifiManager.isWifiEnabled()) { 232 PopupMenu pm = new PopupMenu(inflater.getContext(), b); 233 pm.inflate(R.menu.wifi_setup); 234 pm.setOnMenuItemClickListener(new OnMenuItemClickListener() { 235 @Override 236 public boolean onMenuItemClick(MenuItem item) { 237 if (R.id.wifi_wps == item.getItemId()) { 238 showDialog(WPS_PBC_DIALOG_ID); 239 return true; 240 } 241 return false; 242 } 243 }); 244 pm.show(); 245 } 246 } 247 }); 248 } 249 250 Intent intent = getActivity().getIntent(); 251 if (intent.getBooleanExtra(EXTRA_SHOW_CUSTOM_BUTTON, false)) { 252 view.findViewById(R.id.button_bar).setVisibility(View.VISIBLE); 253 view.findViewById(R.id.back_button).setVisibility(View.INVISIBLE); 254 view.findViewById(R.id.skip_button).setVisibility(View.INVISIBLE); 255 view.findViewById(R.id.next_button).setVisibility(View.INVISIBLE); 256 257 Button customButton = (Button) view.findViewById(R.id.custom_button); 258 customButton.setVisibility(View.VISIBLE); 259 customButton.setOnClickListener(new OnClickListener() { 260 @Override 261 public void onClick(View v) { 262 boolean isConnected = false; 263 Activity activity = getActivity(); 264 final ConnectivityManager connectivity = (ConnectivityManager) 265 activity.getSystemService(Context.CONNECTIVITY_SERVICE); 266 if (connectivity != null) { 267 final NetworkInfo info = connectivity.getActiveNetworkInfo(); 268 isConnected = (info != null) && info.isConnected(); 269 } 270 if (isConnected) { 271 // Warn of possible data charges 272 showDialog(WIFI_SKIPPED_DIALOG_ID); 273 } else { 274 // Warn of lack of updates 275 showDialog(WIFI_AND_MOBILE_SKIPPED_DIALOG_ID); 276 } 277 } 278 }); 279 } 280 281 if (intent.getBooleanExtra(EXTRA_SHOW_WIFI_REQUIRED_INFO, false)) { 282 view.findViewById(R.id.wifi_required_info).setVisibility(View.VISIBLE); 283 } 284 285 return view; 286 } else { 287 return super.onCreateView(inflater, container, savedInstanceState); 288 } 289 } 290 291 @Override 292 public void onActivityCreated(Bundle savedInstanceState) { 293 super.onActivityCreated(savedInstanceState); 294 295 mP2pSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT); 296 mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 297 298 mConnectListener = new WifiManager.ActionListener() { 299 @Override 300 public void onSuccess() { 301 } 302 @Override 303 public void onFailure(int reason) { 304 Activity activity = getActivity(); 305 if (activity != null) { 306 Toast.makeText(activity, 307 R.string.wifi_failed_connect_message, 308 Toast.LENGTH_SHORT).show(); 309 } 310 } 311 }; 312 313 mSaveListener = new WifiManager.ActionListener() { 314 @Override 315 public void onSuccess() { 316 } 317 @Override 318 public void onFailure(int reason) { 319 Activity activity = getActivity(); 320 if (activity != null) { 321 Toast.makeText(activity, 322 R.string.wifi_failed_save_message, 323 Toast.LENGTH_SHORT).show(); 324 } 325 } 326 }; 327 328 mForgetListener = new WifiManager.ActionListener() { 329 @Override 330 public void onSuccess() { 331 } 332 @Override 333 public void onFailure(int reason) { 334 Activity activity = getActivity(); 335 if (activity != null) { 336 Toast.makeText(activity, 337 R.string.wifi_failed_forget_message, 338 Toast.LENGTH_SHORT).show(); 339 } 340 } 341 }; 342 343 if (savedInstanceState != null 344 && savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) { 345 mDlgEdit = savedInstanceState.getBoolean(SAVE_DIALOG_EDIT_MODE); 346 mAccessPointSavedState = savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE); 347 } 348 349 final Activity activity = getActivity(); 350 final Intent intent = activity.getIntent(); 351 352 // first if we're supposed to finish once we have a connection 353 mAutoFinishOnConnection = intent.getBooleanExtra(EXTRA_AUTO_FINISH_ON_CONNECT, false); 354 355 if (mAutoFinishOnConnection) { 356 // Hide the next button 357 if (hasNextButton()) { 358 getNextButton().setVisibility(View.GONE); 359 } 360 361 final ConnectivityManager connectivity = (ConnectivityManager) 362 activity.getSystemService(Context.CONNECTIVITY_SERVICE); 363 if (connectivity != null 364 && connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) { 365 activity.setResult(Activity.RESULT_OK); 366 activity.finish(); 367 return; 368 } 369 } 370 371 // if we're supposed to enable/disable the Next button based on our current connection 372 // state, start it off in the right state 373 mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false); 374 375 if (mEnableNextOnConnection) { 376 if (hasNextButton()) { 377 final ConnectivityManager connectivity = (ConnectivityManager) 378 activity.getSystemService(Context.CONNECTIVITY_SERVICE); 379 if (connectivity != null) { 380 NetworkInfo info = connectivity.getNetworkInfo( 381 ConnectivityManager.TYPE_WIFI); 382 changeNextButtonState(info.isConnected()); 383 } 384 } 385 } 386 387 addPreferencesFromResource(R.xml.wifi_settings); 388 389 if (mSetupWizardMode) { 390 getView().setSystemUiVisibility( 391 View.STATUS_BAR_DISABLE_HOME | 392 View.STATUS_BAR_DISABLE_RECENT | 393 View.STATUS_BAR_DISABLE_NOTIFICATION_ALERTS | 394 View.STATUS_BAR_DISABLE_CLOCK); 395 } 396 397 mEmptyView = (TextView) getView().findViewById(android.R.id.empty); 398 getListView().setEmptyView(mEmptyView); 399 400 if (!mSetupWizardMode) { 401 registerForContextMenu(getListView()); 402 } 403 setHasOptionsMenu(true); 404 } 405 406 @Override 407 public void onStart() { 408 super.onStart(); 409 410 // On/off switch is hidden for Setup Wizard 411 if (!mSetupWizardMode) { 412 final Activity activity = getActivity(); 413 414 mSwitch = new Switch(activity); 415 boolean addSwitch = true; 416 417 if (activity instanceof WifiPickerActivity) { 418 PreferenceActivity pa = (PreferenceActivity) activity; 419 addSwitch = pa.onIsHidingHeaders(); 420 } 421 422 if (addSwitch) { 423 final int padding = activity.getResources().getDimensionPixelSize( 424 R.dimen.action_bar_switch_padding); 425 mSwitch.setPaddingRelative(0, 0, padding, 0); 426 activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, 427 ActionBar.DISPLAY_SHOW_CUSTOM); 428 activity.getActionBar().setCustomView(mSwitch, new ActionBar.LayoutParams( 429 ActionBar.LayoutParams.WRAP_CONTENT, 430 ActionBar.LayoutParams.WRAP_CONTENT, 431 Gravity.CENTER_VERTICAL | Gravity.END)); 432 } 433 434 mWifiEnabler = new WifiEnabler(activity, mSwitch); 435 } 436 } 437 438 @Override 439 public void onStop() { 440 super.onStop(); 441 Activity activity = getActivity(); 442 boolean onIsHidingHeaders = true; 443 if (activity instanceof SettingsActivity){ 444 SettingsActivity sa = (SettingsActivity) activity; 445 onIsHidingHeaders = sa.onIsHidingHeaders(); 446 } else if (activity instanceof PreferenceActivity) { 447 PreferenceActivity pa = (PreferenceActivity) activity; 448 onIsHidingHeaders = pa.onIsHidingHeaders(); 449 } 450 if (!onIsHidingHeaders) { 451 activity.getActionBar().setDisplayOptions(0, ActionBar.DISPLAY_SHOW_CUSTOM); 452 activity.getActionBar().setCustomView(null); 453 } 454 } 455 456 @Override 457 public void onResume() { 458 final Activity activity = getActivity(); 459 super.onResume(); 460 if (mWifiEnabler != null) { 461 mWifiEnabler.resume(activity); 462 } 463 464 activity.registerReceiver(mReceiver, mFilter); 465 updateAccessPoints(); 466 } 467 468 @Override 469 public void onPause() { 470 super.onPause(); 471 if (mWifiEnabler != null) { 472 mWifiEnabler.pause(); 473 } 474 getActivity().unregisterReceiver(mReceiver); 475 mScanner.pause(); 476 } 477 478 @Override 479 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 480 // If the user is not allowed to configure wifi, do not show the menu. 481 if (isRestrictedAndNotPinProtected()) return; 482 483 final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); 484 TypedArray ta = getActivity().getTheme().obtainStyledAttributes( 485 new int[] {R.attr.ic_menu_add, R.attr.ic_wps}); 486 if (mSetupWizardMode) { 487 menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc) 488 .setIcon(ta.getDrawable(1)) 489 .setEnabled(wifiIsEnabled) 490 .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 491 menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network) 492 .setEnabled(wifiIsEnabled) 493 .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 494 } else { 495 menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc) 496 .setIcon(ta.getDrawable(1)) 497 .setEnabled(wifiIsEnabled) 498 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 499 menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network) 500 .setIcon(ta.getDrawable(0)) 501 .setEnabled(wifiIsEnabled) 502 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 503 menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan) 504 //.setIcon(R.drawable.ic_menu_scan_network) 505 .setEnabled(wifiIsEnabled) 506 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 507 menu.add(Menu.NONE, MENU_ID_WPS_PIN, 0, R.string.wifi_menu_wps_pin) 508 .setEnabled(wifiIsEnabled) 509 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 510 if (mP2pSupported) { 511 menu.add(Menu.NONE, MENU_ID_P2P, 0, R.string.wifi_menu_p2p) 512 .setEnabled(wifiIsEnabled) 513 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 514 } 515 menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced) 516 //.setIcon(android.R.drawable.ic_menu_manage) 517 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 518 } 519 ta.recycle(); 520 super.onCreateOptionsMenu(menu, inflater); 521 } 522 523 @Override 524 public void onSaveInstanceState(Bundle outState) { 525 super.onSaveInstanceState(outState); 526 527 // If the dialog is showing, save its state. 528 if (mDialog != null && mDialog.isShowing()) { 529 outState.putBoolean(SAVE_DIALOG_EDIT_MODE, mDlgEdit); 530 if (mDlgAccessPoint != null) { 531 mAccessPointSavedState = new Bundle(); 532 mDlgAccessPoint.saveWifiState(mAccessPointSavedState); 533 outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState); 534 } 535 } 536 } 537 538 @Override 539 public boolean onOptionsItemSelected(MenuItem item) { 540 // If the user is not allowed to configure wifi, do not handle menu selections. 541 if (isRestrictedAndNotPinProtected()) return false; 542 543 switch (item.getItemId()) { 544 case MENU_ID_WPS_PBC: 545 showDialog(WPS_PBC_DIALOG_ID); 546 return true; 547 case MENU_ID_P2P: 548 if (getActivity() instanceof SettingsActivity) { 549 ((SettingsActivity) getActivity()).startPreferencePanel( 550 WifiP2pSettings.class.getCanonicalName(), 551 null, 552 R.string.wifi_p2p_settings_title, null, 553 this, 0); 554 } else { 555 startFragment(this, WifiP2pSettings.class.getCanonicalName(), -1, null); 556 } 557 return true; 558 case MENU_ID_WPS_PIN: 559 showDialog(WPS_PIN_DIALOG_ID); 560 return true; 561 case MENU_ID_SCAN: 562 if (mWifiManager.isWifiEnabled()) { 563 mScanner.forceScan(); 564 } 565 return true; 566 case MENU_ID_ADD_NETWORK: 567 if (mWifiManager.isWifiEnabled()) { 568 onAddNetworkPressed(); 569 } 570 return true; 571 case MENU_ID_ADVANCED: 572 if (getActivity() instanceof SettingsActivity) { 573 ((SettingsActivity) getActivity()).startPreferencePanel( 574 AdvancedWifiSettings.class.getCanonicalName(), 575 null, 576 R.string.wifi_advanced_titlebar, null, 577 this, 0); 578 } else { 579 startFragment(this, AdvancedWifiSettings.class.getCanonicalName(), -1, null); 580 } 581 return true; 582 } 583 return super.onOptionsItemSelected(item); 584 } 585 586 @Override 587 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) { 588 if (info instanceof AdapterContextMenuInfo) { 589 Preference preference = (Preference) getListView().getItemAtPosition( 590 ((AdapterContextMenuInfo) info).position); 591 592 if (preference instanceof AccessPoint) { 593 mSelectedAccessPoint = (AccessPoint) preference; 594 menu.setHeaderTitle(mSelectedAccessPoint.ssid); 595 if (mSelectedAccessPoint.getLevel() != -1 596 && mSelectedAccessPoint.getState() == null) { 597 menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect); 598 } 599 if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 600 menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget); 601 menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify); 602 } 603 } 604 } 605 } 606 607 @Override 608 public boolean onContextItemSelected(MenuItem item) { 609 if (mSelectedAccessPoint == null) { 610 return super.onContextItemSelected(item); 611 } 612 switch (item.getItemId()) { 613 case MENU_ID_CONNECT: { 614 if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 615 mWifiManager.connect(mSelectedAccessPoint.networkId, 616 mConnectListener); 617 } else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) { 618 /** Bypass dialog for unsecured networks */ 619 mSelectedAccessPoint.generateOpenNetworkConfig(); 620 mWifiManager.connect(mSelectedAccessPoint.getConfig(), 621 mConnectListener); 622 } else { 623 showDialog(mSelectedAccessPoint, true); 624 } 625 return true; 626 } 627 case MENU_ID_FORGET: { 628 mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener); 629 return true; 630 } 631 case MENU_ID_MODIFY: { 632 showDialog(mSelectedAccessPoint, true); 633 return true; 634 } 635 } 636 return super.onContextItemSelected(item); 637 } 638 639 @Override 640 public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) { 641 if (preference instanceof AccessPoint) { 642 mSelectedAccessPoint = (AccessPoint) preference; 643 /** Bypass dialog for unsecured, unsaved networks */ 644 if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE && 645 mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) { 646 mSelectedAccessPoint.generateOpenNetworkConfig(); 647 mWifiManager.connect(mSelectedAccessPoint.getConfig(), mConnectListener); 648 } else { 649 showDialog(mSelectedAccessPoint, false); 650 } 651 } else { 652 return super.onPreferenceTreeClick(screen, preference); 653 } 654 return true; 655 } 656 657 private void showDialog(AccessPoint accessPoint, boolean edit) { 658 if (mDialog != null) { 659 removeDialog(WIFI_DIALOG_ID); 660 mDialog = null; 661 } 662 663 // Save the access point and edit mode 664 mDlgAccessPoint = accessPoint; 665 mDlgEdit = edit; 666 667 showDialog(WIFI_DIALOG_ID); 668 } 669 670 @Override 671 public Dialog onCreateDialog(int dialogId) { 672 switch (dialogId) { 673 case WIFI_DIALOG_ID: 674 AccessPoint ap = mDlgAccessPoint; // For manual launch 675 if (ap == null) { // For re-launch from saved state 676 if (mAccessPointSavedState != null) { 677 ap = new AccessPoint(getActivity(), mAccessPointSavedState); 678 // For repeated orientation changes 679 mDlgAccessPoint = ap; 680 // Reset the saved access point data 681 mAccessPointSavedState = null; 682 } 683 } 684 // If it's still null, fine, it's for Add Network 685 mSelectedAccessPoint = ap; 686 mDialog = new WifiDialog(getActivity(), this, ap, mDlgEdit); 687 return mDialog; 688 case WPS_PBC_DIALOG_ID: 689 return new WpsDialog(getActivity(), WpsInfo.PBC); 690 case WPS_PIN_DIALOG_ID: 691 return new WpsDialog(getActivity(), WpsInfo.DISPLAY); 692 case WIFI_SKIPPED_DIALOG_ID: 693 return new AlertDialog.Builder(getActivity()) 694 .setMessage(R.string.wifi_skipped_message) 695 .setCancelable(false) 696 .setNegativeButton(R.string.wifi_skip_anyway, 697 new DialogInterface.OnClickListener() { 698 @Override 699 public void onClick(DialogInterface dialog, int id) { 700 getActivity().setResult(RESULT_SKIP); 701 getActivity().finish(); 702 } 703 }) 704 .setPositiveButton(R.string.wifi_dont_skip, 705 new DialogInterface.OnClickListener() { 706 @Override 707 public void onClick(DialogInterface dialog, int id) { 708 } 709 }) 710 .create(); 711 case WIFI_AND_MOBILE_SKIPPED_DIALOG_ID: 712 return new AlertDialog.Builder(getActivity()) 713 .setMessage(R.string.wifi_and_mobile_skipped_message) 714 .setCancelable(false) 715 .setNegativeButton(R.string.wifi_skip_anyway, 716 new DialogInterface.OnClickListener() { 717 @Override 718 public void onClick(DialogInterface dialog, int id) { 719 getActivity().setResult(RESULT_SKIP); 720 getActivity().finish(); 721 } 722 }) 723 .setPositiveButton(R.string.wifi_dont_skip, 724 new DialogInterface.OnClickListener() { 725 @Override 726 public void onClick(DialogInterface dialog, int id) { 727 } 728 }) 729 .create(); 730 731 } 732 return super.onCreateDialog(dialogId); 733 } 734 735 /** 736 * Shows the latest access points available with supplimental information like 737 * the strength of network and the security for it. 738 */ 739 private void updateAccessPoints() { 740 // Safeguard from some delayed event handling 741 if (getActivity() == null) return; 742 743 if (isRestrictedAndNotPinProtected()) { 744 addMessagePreference(R.string.wifi_empty_list_user_restricted); 745 return; 746 } 747 final int wifiState = mWifiManager.getWifiState(); 748 749 switch (wifiState) { 750 case WifiManager.WIFI_STATE_ENABLED: 751 // AccessPoints are automatically sorted with TreeSet. 752 final Collection<AccessPoint> accessPoints = 753 constructAccessPoints(getActivity(), mWifiManager, mLastInfo, mLastState); 754 getPreferenceScreen().removeAll(); 755 if(accessPoints.size() == 0) { 756 addMessagePreference(R.string.wifi_empty_list_wifi_on); 757 } 758 for (AccessPoint accessPoint : accessPoints) { 759 getPreferenceScreen().addPreference(accessPoint); 760 } 761 break; 762 763 case WifiManager.WIFI_STATE_ENABLING: 764 getPreferenceScreen().removeAll(); 765 break; 766 767 case WifiManager.WIFI_STATE_DISABLING: 768 addMessagePreference(R.string.wifi_stopping); 769 break; 770 771 case WifiManager.WIFI_STATE_DISABLED: 772 setOffMessage(); 773 break; 774 } 775 } 776 777 private void setOffMessage() { 778 if (mEmptyView != null) { 779 mEmptyView.setText(R.string.wifi_empty_list_wifi_off); 780 if (android.provider.Settings.Global.getInt(getActivity().getContentResolver(), 781 android.provider.Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1) { 782 mEmptyView.append("\n\n"); 783 int resId; 784 if (android.provider.Settings.Secure.isLocationProviderEnabled( 785 getActivity().getContentResolver(), LocationManager.NETWORK_PROVIDER)) { 786 resId = R.string.wifi_scan_notify_text_location_on; 787 } else { 788 resId = R.string.wifi_scan_notify_text_location_off; 789 } 790 CharSequence charSeq = getText(resId); 791 mEmptyView.append(charSeq); 792 } 793 } 794 getPreferenceScreen().removeAll(); 795 } 796 797 private void addMessagePreference(int messageId) { 798 if (mEmptyView != null) mEmptyView.setText(messageId); 799 getPreferenceScreen().removeAll(); 800 } 801 802 /** Returns sorted list of access points */ 803 private static List<AccessPoint> constructAccessPoints(Context context, 804 WifiManager wifiManager, WifiInfo lastInfo, DetailedState lastState) { 805 ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>(); 806 /** Lookup table to more quickly update AccessPoints by only considering objects with the 807 * correct SSID. Maps SSID -> List of AccessPoints with the given SSID. */ 808 Multimap<String, AccessPoint> apMap = new Multimap<String, AccessPoint>(); 809 810 final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks(); 811 if (configs != null) { 812 for (WifiConfiguration config : configs) { 813 AccessPoint accessPoint = new AccessPoint(context, config); 814 if (lastInfo != null && lastState != null) { 815 accessPoint.update(lastInfo, lastState); 816 } 817 accessPoints.add(accessPoint); 818 apMap.put(accessPoint.ssid, accessPoint); 819 } 820 } 821 822 final List<ScanResult> results = wifiManager.getScanResults(); 823 if (results != null) { 824 for (ScanResult result : results) { 825 // Ignore hidden and ad-hoc networks. 826 if (result.SSID == null || result.SSID.length() == 0 || 827 result.capabilities.contains("[IBSS]")) { 828 continue; 829 } 830 831 boolean found = false; 832 for (AccessPoint accessPoint : apMap.getAll(result.SSID)) { 833 if (accessPoint.update(result)) 834 found = true; 835 } 836 if (!found) { 837 AccessPoint accessPoint = new AccessPoint(context, result); 838 accessPoints.add(accessPoint); 839 apMap.put(accessPoint.ssid, accessPoint); 840 } 841 } 842 } 843 844 // Pre-sort accessPoints to speed preference insertion 845 Collections.sort(accessPoints); 846 return accessPoints; 847 } 848 849 /** A restricted multimap for use in constructAccessPoints */ 850 private static class Multimap<K,V> { 851 private final HashMap<K,List<V>> store = new HashMap<K,List<V>>(); 852 /** retrieve a non-null list of values with key K */ 853 List<V> getAll(K key) { 854 List<V> values = store.get(key); 855 return values != null ? values : Collections.<V>emptyList(); 856 } 857 858 void put(K key, V val) { 859 List<V> curVals = store.get(key); 860 if (curVals == null) { 861 curVals = new ArrayList<V>(3); 862 store.put(key, curVals); 863 } 864 curVals.add(val); 865 } 866 } 867 868 private void handleEvent(Context context, Intent intent) { 869 String action = intent.getAction(); 870 if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) { 871 updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 872 WifiManager.WIFI_STATE_UNKNOWN)); 873 } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) || 874 WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) || 875 WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) { 876 updateAccessPoints(); 877 } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) { 878 //Ignore supplicant state changes when network is connected 879 //TODO: we should deprecate SUPPLICANT_STATE_CHANGED_ACTION and 880 //introduce a broadcast that combines the supplicant and network 881 //network state change events so the apps dont have to worry about 882 //ignoring supplicant state change when network is connected 883 //to get more fine grained information. 884 SupplicantState state = (SupplicantState) intent.getParcelableExtra( 885 WifiManager.EXTRA_NEW_STATE); 886 if (!mConnected.get() && SupplicantState.isHandshakeState(state)) { 887 updateConnectionState(WifiInfo.getDetailedStateOf(state)); 888 } else { 889 // During a connect, we may have the supplicant 890 // state change affect the detailed network state. 891 // Make sure a lost connection is updated as well. 892 updateConnectionState(null); 893 } 894 } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) { 895 NetworkInfo info = (NetworkInfo) intent.getParcelableExtra( 896 WifiManager.EXTRA_NETWORK_INFO); 897 mConnected.set(info.isConnected()); 898 changeNextButtonState(info.isConnected()); 899 updateAccessPoints(); 900 updateConnectionState(info.getDetailedState()); 901 if (mAutoFinishOnConnection && info.isConnected()) { 902 Activity activity = getActivity(); 903 if (activity != null) { 904 activity.setResult(Activity.RESULT_OK); 905 activity.finish(); 906 } 907 return; 908 } 909 } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) { 910 updateConnectionState(null); 911 } 912 } 913 914 private void updateConnectionState(DetailedState state) { 915 /* sticky broadcasts can call this when wifi is disabled */ 916 if (!mWifiManager.isWifiEnabled()) { 917 mScanner.pause(); 918 return; 919 } 920 921 if (state == DetailedState.OBTAINING_IPADDR) { 922 mScanner.pause(); 923 } else { 924 mScanner.resume(); 925 } 926 927 mLastInfo = mWifiManager.getConnectionInfo(); 928 if (state != null) { 929 mLastState = state; 930 } 931 932 for (int i = getPreferenceScreen().getPreferenceCount() - 1; i >= 0; --i) { 933 // Maybe there's a WifiConfigPreference 934 Preference preference = getPreferenceScreen().getPreference(i); 935 if (preference instanceof AccessPoint) { 936 final AccessPoint accessPoint = (AccessPoint) preference; 937 accessPoint.update(mLastInfo, mLastState); 938 } 939 } 940 } 941 942 private void updateWifiState(int state) { 943 Activity activity = getActivity(); 944 if (activity != null) { 945 activity.invalidateOptionsMenu(); 946 } 947 948 switch (state) { 949 case WifiManager.WIFI_STATE_ENABLED: 950 mScanner.resume(); 951 return; // not break, to avoid the call to pause() below 952 953 case WifiManager.WIFI_STATE_ENABLING: 954 addMessagePreference(R.string.wifi_starting); 955 break; 956 957 case WifiManager.WIFI_STATE_DISABLED: 958 setOffMessage(); 959 break; 960 } 961 962 mLastInfo = null; 963 mLastState = null; 964 mScanner.pause(); 965 } 966 967 private class Scanner extends Handler { 968 private int mRetry = 0; 969 970 void resume() { 971 if (!hasMessages(0)) { 972 sendEmptyMessage(0); 973 } 974 } 975 976 void forceScan() { 977 removeMessages(0); 978 sendEmptyMessage(0); 979 } 980 981 void pause() { 982 mRetry = 0; 983 removeMessages(0); 984 } 985 986 @Override 987 public void handleMessage(Message message) { 988 if (mWifiManager.startScan()) { 989 mRetry = 0; 990 } else if (++mRetry >= 3) { 991 mRetry = 0; 992 Activity activity = getActivity(); 993 if (activity != null) { 994 Toast.makeText(activity, R.string.wifi_fail_to_scan, 995 Toast.LENGTH_LONG).show(); 996 } 997 return; 998 } 999 sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS); 1000 } 1001 } 1002 1003 /** 1004 * Renames/replaces "Next" button when appropriate. "Next" button usually exists in 1005 * Wifi setup screens, not in usual wifi settings screen. 1006 * 1007 * @param connected true when the device is connected to a wifi network. 1008 */ 1009 private void changeNextButtonState(boolean connected) { 1010 if (mEnableNextOnConnection && hasNextButton()) { 1011 getNextButton().setEnabled(connected); 1012 } 1013 } 1014 1015 @Override 1016 public void onClick(DialogInterface dialogInterface, int button) { 1017 if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) { 1018 forget(); 1019 } else if (button == WifiDialog.BUTTON_SUBMIT) { 1020 if (mDialog != null) { 1021 submit(mDialog.getController()); 1022 } 1023 } 1024 } 1025 1026 /* package */ void submit(WifiConfigController configController) { 1027 1028 final WifiConfiguration config = configController.getConfig(); 1029 1030 if (config == null) { 1031 if (mSelectedAccessPoint != null 1032 && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 1033 mWifiManager.connect(mSelectedAccessPoint.networkId, 1034 mConnectListener); 1035 } 1036 } else if (config.networkId != INVALID_NETWORK_ID) { 1037 if (mSelectedAccessPoint != null) { 1038 mWifiManager.save(config, mSaveListener); 1039 } 1040 } else { 1041 if (configController.isEdit()) { 1042 mWifiManager.save(config, mSaveListener); 1043 } else { 1044 mWifiManager.connect(config, mConnectListener); 1045 } 1046 } 1047 1048 if (mWifiManager.isWifiEnabled()) { 1049 mScanner.resume(); 1050 } 1051 updateAccessPoints(); 1052 } 1053 1054 /* package */ void forget() { 1055 if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) { 1056 // Should not happen, but a monkey seems to triger it 1057 Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig()); 1058 return; 1059 } 1060 1061 mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener); 1062 1063 if (mWifiManager.isWifiEnabled()) { 1064 mScanner.resume(); 1065 } 1066 updateAccessPoints(); 1067 1068 // We need to rename/replace "Next" button in wifi setup context. 1069 changeNextButtonState(false); 1070 } 1071 1072 /** 1073 * Refreshes acccess points and ask Wifi module to scan networks again. 1074 */ 1075 /* package */ void refreshAccessPoints() { 1076 if (mWifiManager.isWifiEnabled()) { 1077 mScanner.resume(); 1078 } 1079 1080 getPreferenceScreen().removeAll(); 1081 } 1082 1083 /** 1084 * Called when "add network" button is pressed. 1085 */ 1086 /* package */ void onAddNetworkPressed() { 1087 // No exact access point is selected. 1088 mSelectedAccessPoint = null; 1089 showDialog(null, true); 1090 } 1091 1092 /* package */ int getAccessPointsCount() { 1093 final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); 1094 if (wifiIsEnabled) { 1095 return getPreferenceScreen().getPreferenceCount(); 1096 } else { 1097 return 0; 1098 } 1099 } 1100 1101 /** 1102 * Requests wifi module to pause wifi scan. May be ignored when the module is disabled. 1103 */ 1104 /* package */ void pauseWifiScan() { 1105 if (mWifiManager.isWifiEnabled()) { 1106 mScanner.pause(); 1107 } 1108 } 1109 1110 /** 1111 * Requests wifi module to resume wifi scan. May be ignored when the module is disabled. 1112 */ 1113 /* package */ void resumeWifiScan() { 1114 if (mWifiManager.isWifiEnabled()) { 1115 mScanner.resume(); 1116 } 1117 } 1118 1119 @Override 1120 protected int getHelpResource() { 1121 if (mSetupWizardMode) { 1122 return 0; 1123 } 1124 return R.string.help_url_wifi; 1125 } 1126 1127 /** 1128 * Used as the outer frame of all setup wizard pages that need to adjust their margins based 1129 * on the total size of the available display. (e.g. side margins set to 10% of total width.) 1130 */ 1131 public static class ProportionalOuterFrame extends RelativeLayout { 1132 public ProportionalOuterFrame(Context context) { 1133 super(context); 1134 } 1135 public ProportionalOuterFrame(Context context, AttributeSet attrs) { 1136 super(context, attrs); 1137 } 1138 public ProportionalOuterFrame(Context context, AttributeSet attrs, int defStyle) { 1139 super(context, attrs, defStyle); 1140 } 1141 1142 /** 1143 * Set our margins and title area height proportionally to the available display size 1144 */ 1145 @Override 1146 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 1147 int parentWidth = MeasureSpec.getSize(widthMeasureSpec); 1148 int parentHeight = MeasureSpec.getSize(heightMeasureSpec); 1149 final Resources res = getContext().getResources(); 1150 float titleHeight = res.getFraction(R.dimen.setup_title_height, 1, 1); 1151 float sideMargin = res.getFraction(R.dimen.setup_border_width, 1, 1); 1152 int bottom = res.getDimensionPixelSize(R.dimen.setup_margin_bottom); 1153 setPaddingRelative( 1154 (int) (parentWidth * sideMargin), 1155 0, 1156 (int) (parentWidth * sideMargin), 1157 bottom); 1158 View title = findViewById(R.id.title_area); 1159 if (title != null) { 1160 title.setMinimumHeight((int) (parentHeight * titleHeight)); 1161 } 1162 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 1163 } 1164 } 1165 1166 public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER = 1167 new SearchIndexProvider() { 1168 @Override 1169 public List<SearchIndexableResource> getXmlResourcesToIndex( 1170 Context context, boolean enabled) { 1171 return null; 1172 } 1173 1174 @Override 1175 public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) { 1176 final List<SearchIndexableRaw> result = new ArrayList<SearchIndexableRaw>(); 1177 final Resources res = context.getResources(); 1178 1179 // Add fragment title 1180 SearchIndexableRaw data = new SearchIndexableRaw(context); 1181 data.title = res.getString(R.string.wifi_settings); 1182 data.screenTitle = res.getString(R.string.wifi_settings); 1183 result.add(data); 1184 1185 // Add available Wi-Fi access points 1186 WifiManager wifiManager = 1187 (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 1188 final Collection<AccessPoint> accessPoints = 1189 constructAccessPoints(context, wifiManager, null, null); 1190 for (AccessPoint accessPoint : accessPoints) { 1191 // We are indexing only the saved Wi-Fi networks. 1192 if (accessPoint.getConfig() == null) continue; 1193 data = new SearchIndexableRaw(context); 1194 data.title = accessPoint.getTitle().toString(); 1195 data.screenTitle = res.getString(R.string.wifi_settings); 1196 data.enabled = enabled; 1197 result.add(data); 1198 } 1199 1200 return result; 1201 } 1202 }; 1203} 1204