WifiSettings.java revision b8dfbf140986a9c0781f268ea40914063f026436
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 com.android.settings.R; 24import com.android.settings.RestrictedSettingsFragment; 25import com.android.settings.SettingsActivity; 26import com.android.settings.indexer.Indexable; 27import com.android.settings.indexer.IndexableData; 28import com.android.settings.indexer.IndexableRef; 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 416 if (activity instanceof SettingsActivity) { 417 SettingsActivity sa = (SettingsActivity) activity; 418 if (!sa.onIsHidingHeaders()) { 419 final int padding = activity.getResources().getDimensionPixelSize( 420 R.dimen.action_bar_switch_padding); 421 mSwitch.setPaddingRelative(0, 0, padding, 0); 422 activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, 423 ActionBar.DISPLAY_SHOW_CUSTOM); 424 activity.getActionBar().setCustomView(mSwitch, new ActionBar.LayoutParams( 425 ActionBar.LayoutParams.WRAP_CONTENT, 426 ActionBar.LayoutParams.WRAP_CONTENT, 427 Gravity.CENTER_VERTICAL | Gravity.END)); 428 } 429 } 430 431 mWifiEnabler = new WifiEnabler(activity, mSwitch); 432 } 433 } 434 435 @Override 436 public void onStop() { 437 super.onStop(); 438 Activity activity = getActivity(); 439 boolean onIsHidingHeaders = true; 440 if (activity instanceof SettingsActivity){ 441 SettingsActivity sa = (SettingsActivity) activity; 442 onIsHidingHeaders = sa.onIsHidingHeaders(); 443 } else if (activity instanceof PreferenceActivity) { 444 PreferenceActivity pa = (PreferenceActivity) activity; 445 onIsHidingHeaders = pa.onIsHidingHeaders(); 446 } 447 if (!onIsHidingHeaders) { 448 activity.getActionBar().setDisplayOptions(0, ActionBar.DISPLAY_SHOW_CUSTOM); 449 activity.getActionBar().setCustomView(null); 450 } 451 } 452 453 @Override 454 public void onResume() { 455 super.onResume(); 456 if (mWifiEnabler != null) { 457 mWifiEnabler.resume(); 458 } 459 460 getActivity().registerReceiver(mReceiver, mFilter); 461 updateAccessPoints(); 462 } 463 464 @Override 465 public void onPause() { 466 super.onPause(); 467 if (mWifiEnabler != null) { 468 mWifiEnabler.pause(); 469 } 470 getActivity().unregisterReceiver(mReceiver); 471 mScanner.pause(); 472 } 473 474 @Override 475 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 476 // If the user is not allowed to configure wifi, do not show the menu. 477 if (isRestrictedAndNotPinProtected()) return; 478 479 final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); 480 TypedArray ta = getActivity().getTheme().obtainStyledAttributes( 481 new int[] {R.attr.ic_menu_add, R.attr.ic_wps}); 482 if (mSetupWizardMode) { 483 menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc) 484 .setIcon(ta.getDrawable(1)) 485 .setEnabled(wifiIsEnabled) 486 .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 487 menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network) 488 .setEnabled(wifiIsEnabled) 489 .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 490 } else { 491 menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc) 492 .setIcon(ta.getDrawable(1)) 493 .setEnabled(wifiIsEnabled) 494 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 495 menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network) 496 .setIcon(ta.getDrawable(0)) 497 .setEnabled(wifiIsEnabled) 498 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); 499 menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan) 500 //.setIcon(R.drawable.ic_menu_scan_network) 501 .setEnabled(wifiIsEnabled) 502 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 503 menu.add(Menu.NONE, MENU_ID_WPS_PIN, 0, R.string.wifi_menu_wps_pin) 504 .setEnabled(wifiIsEnabled) 505 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 506 if (mP2pSupported) { 507 menu.add(Menu.NONE, MENU_ID_P2P, 0, R.string.wifi_menu_p2p) 508 .setEnabled(wifiIsEnabled) 509 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 510 } 511 menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced) 512 //.setIcon(android.R.drawable.ic_menu_manage) 513 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); 514 } 515 ta.recycle(); 516 super.onCreateOptionsMenu(menu, inflater); 517 } 518 519 @Override 520 public void onSaveInstanceState(Bundle outState) { 521 super.onSaveInstanceState(outState); 522 523 // If the dialog is showing, save its state. 524 if (mDialog != null && mDialog.isShowing()) { 525 outState.putBoolean(SAVE_DIALOG_EDIT_MODE, mDlgEdit); 526 if (mDlgAccessPoint != null) { 527 mAccessPointSavedState = new Bundle(); 528 mDlgAccessPoint.saveWifiState(mAccessPointSavedState); 529 outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState); 530 } 531 } 532 } 533 534 @Override 535 public boolean onOptionsItemSelected(MenuItem item) { 536 // If the user is not allowed to configure wifi, do not handle menu selections. 537 if (isRestrictedAndNotPinProtected()) return false; 538 539 switch (item.getItemId()) { 540 case MENU_ID_WPS_PBC: 541 showDialog(WPS_PBC_DIALOG_ID); 542 return true; 543 case MENU_ID_P2P: 544 if (getActivity() instanceof SettingsActivity) { 545 ((SettingsActivity) getActivity()).startPreferencePanel( 546 WifiP2pSettings.class.getCanonicalName(), 547 null, 548 R.string.wifi_p2p_settings_title, null, 549 this, 0); 550 } else { 551 startFragment(this, WifiP2pSettings.class.getCanonicalName(), -1, null); 552 } 553 return true; 554 case MENU_ID_WPS_PIN: 555 showDialog(WPS_PIN_DIALOG_ID); 556 return true; 557 case MENU_ID_SCAN: 558 if (mWifiManager.isWifiEnabled()) { 559 mScanner.forceScan(); 560 } 561 return true; 562 case MENU_ID_ADD_NETWORK: 563 if (mWifiManager.isWifiEnabled()) { 564 onAddNetworkPressed(); 565 } 566 return true; 567 case MENU_ID_ADVANCED: 568 if (getActivity() instanceof SettingsActivity) { 569 ((SettingsActivity) getActivity()).startPreferencePanel( 570 AdvancedWifiSettings.class.getCanonicalName(), 571 null, 572 R.string.wifi_advanced_titlebar, null, 573 this, 0); 574 } else { 575 startFragment(this, AdvancedWifiSettings.class.getCanonicalName(), -1, null); 576 } 577 return true; 578 } 579 return super.onOptionsItemSelected(item); 580 } 581 582 @Override 583 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) { 584 if (info instanceof AdapterContextMenuInfo) { 585 Preference preference = (Preference) getListView().getItemAtPosition( 586 ((AdapterContextMenuInfo) info).position); 587 588 if (preference instanceof AccessPoint) { 589 mSelectedAccessPoint = (AccessPoint) preference; 590 menu.setHeaderTitle(mSelectedAccessPoint.ssid); 591 if (mSelectedAccessPoint.getLevel() != -1 592 && mSelectedAccessPoint.getState() == null) { 593 menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect); 594 } 595 if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 596 menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget); 597 menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify); 598 } 599 } 600 } 601 } 602 603 @Override 604 public boolean onContextItemSelected(MenuItem item) { 605 if (mSelectedAccessPoint == null) { 606 return super.onContextItemSelected(item); 607 } 608 switch (item.getItemId()) { 609 case MENU_ID_CONNECT: { 610 if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 611 mWifiManager.connect(mSelectedAccessPoint.networkId, 612 mConnectListener); 613 } else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) { 614 /** Bypass dialog for unsecured networks */ 615 mSelectedAccessPoint.generateOpenNetworkConfig(); 616 mWifiManager.connect(mSelectedAccessPoint.getConfig(), 617 mConnectListener); 618 } else { 619 showDialog(mSelectedAccessPoint, true); 620 } 621 return true; 622 } 623 case MENU_ID_FORGET: { 624 mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener); 625 return true; 626 } 627 case MENU_ID_MODIFY: { 628 showDialog(mSelectedAccessPoint, true); 629 return true; 630 } 631 } 632 return super.onContextItemSelected(item); 633 } 634 635 @Override 636 public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) { 637 if (preference instanceof AccessPoint) { 638 mSelectedAccessPoint = (AccessPoint) preference; 639 /** Bypass dialog for unsecured, unsaved networks */ 640 if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE && 641 mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) { 642 mSelectedAccessPoint.generateOpenNetworkConfig(); 643 mWifiManager.connect(mSelectedAccessPoint.getConfig(), mConnectListener); 644 } else { 645 showDialog(mSelectedAccessPoint, false); 646 } 647 } else { 648 return super.onPreferenceTreeClick(screen, preference); 649 } 650 return true; 651 } 652 653 private void showDialog(AccessPoint accessPoint, boolean edit) { 654 if (mDialog != null) { 655 removeDialog(WIFI_DIALOG_ID); 656 mDialog = null; 657 } 658 659 // Save the access point and edit mode 660 mDlgAccessPoint = accessPoint; 661 mDlgEdit = edit; 662 663 showDialog(WIFI_DIALOG_ID); 664 } 665 666 @Override 667 public Dialog onCreateDialog(int dialogId) { 668 switch (dialogId) { 669 case WIFI_DIALOG_ID: 670 AccessPoint ap = mDlgAccessPoint; // For manual launch 671 if (ap == null) { // For re-launch from saved state 672 if (mAccessPointSavedState != null) { 673 ap = new AccessPoint(getActivity(), mAccessPointSavedState); 674 // For repeated orientation changes 675 mDlgAccessPoint = ap; 676 // Reset the saved access point data 677 mAccessPointSavedState = null; 678 } 679 } 680 // If it's still null, fine, it's for Add Network 681 mSelectedAccessPoint = ap; 682 mDialog = new WifiDialog(getActivity(), this, ap, mDlgEdit); 683 return mDialog; 684 case WPS_PBC_DIALOG_ID: 685 return new WpsDialog(getActivity(), WpsInfo.PBC); 686 case WPS_PIN_DIALOG_ID: 687 return new WpsDialog(getActivity(), WpsInfo.DISPLAY); 688 case WIFI_SKIPPED_DIALOG_ID: 689 return new AlertDialog.Builder(getActivity()) 690 .setMessage(R.string.wifi_skipped_message) 691 .setCancelable(false) 692 .setNegativeButton(R.string.wifi_skip_anyway, 693 new DialogInterface.OnClickListener() { 694 @Override 695 public void onClick(DialogInterface dialog, int id) { 696 getActivity().setResult(RESULT_SKIP); 697 getActivity().finish(); 698 } 699 }) 700 .setPositiveButton(R.string.wifi_dont_skip, 701 new DialogInterface.OnClickListener() { 702 @Override 703 public void onClick(DialogInterface dialog, int id) { 704 } 705 }) 706 .create(); 707 case WIFI_AND_MOBILE_SKIPPED_DIALOG_ID: 708 return new AlertDialog.Builder(getActivity()) 709 .setMessage(R.string.wifi_and_mobile_skipped_message) 710 .setCancelable(false) 711 .setNegativeButton(R.string.wifi_skip_anyway, 712 new DialogInterface.OnClickListener() { 713 @Override 714 public void onClick(DialogInterface dialog, int id) { 715 getActivity().setResult(RESULT_SKIP); 716 getActivity().finish(); 717 } 718 }) 719 .setPositiveButton(R.string.wifi_dont_skip, 720 new DialogInterface.OnClickListener() { 721 @Override 722 public void onClick(DialogInterface dialog, int id) { 723 } 724 }) 725 .create(); 726 727 } 728 return super.onCreateDialog(dialogId); 729 } 730 731 /** 732 * Shows the latest access points available with supplimental information like 733 * the strength of network and the security for it. 734 */ 735 private void updateAccessPoints() { 736 // Safeguard from some delayed event handling 737 if (getActivity() == null) return; 738 739 if (isRestrictedAndNotPinProtected()) { 740 addMessagePreference(R.string.wifi_empty_list_user_restricted); 741 return; 742 } 743 final int wifiState = mWifiManager.getWifiState(); 744 745 switch (wifiState) { 746 case WifiManager.WIFI_STATE_ENABLED: 747 // AccessPoints are automatically sorted with TreeSet. 748 final Collection<AccessPoint> accessPoints = 749 constructAccessPoints(getActivity(), mWifiManager, mLastInfo, mLastState); 750 getPreferenceScreen().removeAll(); 751 if(accessPoints.size() == 0) { 752 addMessagePreference(R.string.wifi_empty_list_wifi_on); 753 } 754 for (AccessPoint accessPoint : accessPoints) { 755 getPreferenceScreen().addPreference(accessPoint); 756 } 757 break; 758 759 case WifiManager.WIFI_STATE_ENABLING: 760 getPreferenceScreen().removeAll(); 761 break; 762 763 case WifiManager.WIFI_STATE_DISABLING: 764 addMessagePreference(R.string.wifi_stopping); 765 break; 766 767 case WifiManager.WIFI_STATE_DISABLED: 768 setOffMessage(); 769 break; 770 } 771 } 772 773 private void setOffMessage() { 774 if (mEmptyView != null) { 775 mEmptyView.setText(R.string.wifi_empty_list_wifi_off); 776 if (android.provider.Settings.Global.getInt(getActivity().getContentResolver(), 777 android.provider.Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1) { 778 mEmptyView.append("\n\n"); 779 int resId; 780 if (android.provider.Settings.Secure.isLocationProviderEnabled( 781 getActivity().getContentResolver(), LocationManager.NETWORK_PROVIDER)) { 782 resId = R.string.wifi_scan_notify_text_location_on; 783 } else { 784 resId = R.string.wifi_scan_notify_text_location_off; 785 } 786 CharSequence charSeq = getText(resId); 787 mEmptyView.append(charSeq); 788 } 789 } 790 getPreferenceScreen().removeAll(); 791 } 792 793 private void addMessagePreference(int messageId) { 794 if (mEmptyView != null) mEmptyView.setText(messageId); 795 getPreferenceScreen().removeAll(); 796 } 797 798 /** Returns sorted list of access points */ 799 private static List<AccessPoint> constructAccessPoints(Context context, 800 WifiManager wifiManager, WifiInfo lastInfo, DetailedState lastState) { 801 ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>(); 802 /** Lookup table to more quickly update AccessPoints by only considering objects with the 803 * correct SSID. Maps SSID -> List of AccessPoints with the given SSID. */ 804 Multimap<String, AccessPoint> apMap = new Multimap<String, AccessPoint>(); 805 806 final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks(); 807 if (configs != null) { 808 for (WifiConfiguration config : configs) { 809 AccessPoint accessPoint = new AccessPoint(context, config); 810 if (lastInfo != null && lastState != null) { 811 accessPoint.update(lastInfo, lastState); 812 } 813 accessPoints.add(accessPoint); 814 apMap.put(accessPoint.ssid, accessPoint); 815 } 816 } 817 818 final List<ScanResult> results = wifiManager.getScanResults(); 819 if (results != null) { 820 for (ScanResult result : results) { 821 // Ignore hidden and ad-hoc networks. 822 if (result.SSID == null || result.SSID.length() == 0 || 823 result.capabilities.contains("[IBSS]")) { 824 continue; 825 } 826 827 boolean found = false; 828 for (AccessPoint accessPoint : apMap.getAll(result.SSID)) { 829 if (accessPoint.update(result)) 830 found = true; 831 } 832 if (!found) { 833 AccessPoint accessPoint = new AccessPoint(context, result); 834 accessPoints.add(accessPoint); 835 apMap.put(accessPoint.ssid, accessPoint); 836 } 837 } 838 } 839 840 // Pre-sort accessPoints to speed preference insertion 841 Collections.sort(accessPoints); 842 return accessPoints; 843 } 844 845 /** A restricted multimap for use in constructAccessPoints */ 846 private static class Multimap<K,V> { 847 private final HashMap<K,List<V>> store = new HashMap<K,List<V>>(); 848 /** retrieve a non-null list of values with key K */ 849 List<V> getAll(K key) { 850 List<V> values = store.get(key); 851 return values != null ? values : Collections.<V>emptyList(); 852 } 853 854 void put(K key, V val) { 855 List<V> curVals = store.get(key); 856 if (curVals == null) { 857 curVals = new ArrayList<V>(3); 858 store.put(key, curVals); 859 } 860 curVals.add(val); 861 } 862 } 863 864 private void handleEvent(Context context, Intent intent) { 865 String action = intent.getAction(); 866 if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) { 867 updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 868 WifiManager.WIFI_STATE_UNKNOWN)); 869 } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) || 870 WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) || 871 WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) { 872 updateAccessPoints(); 873 } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) { 874 //Ignore supplicant state changes when network is connected 875 //TODO: we should deprecate SUPPLICANT_STATE_CHANGED_ACTION and 876 //introduce a broadcast that combines the supplicant and network 877 //network state change events so the apps dont have to worry about 878 //ignoring supplicant state change when network is connected 879 //to get more fine grained information. 880 SupplicantState state = (SupplicantState) intent.getParcelableExtra( 881 WifiManager.EXTRA_NEW_STATE); 882 if (!mConnected.get() && SupplicantState.isHandshakeState(state)) { 883 updateConnectionState(WifiInfo.getDetailedStateOf(state)); 884 } else { 885 // During a connect, we may have the supplicant 886 // state change affect the detailed network state. 887 // Make sure a lost connection is updated as well. 888 updateConnectionState(null); 889 } 890 } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) { 891 NetworkInfo info = (NetworkInfo) intent.getParcelableExtra( 892 WifiManager.EXTRA_NETWORK_INFO); 893 mConnected.set(info.isConnected()); 894 changeNextButtonState(info.isConnected()); 895 updateAccessPoints(); 896 updateConnectionState(info.getDetailedState()); 897 if (mAutoFinishOnConnection && info.isConnected()) { 898 Activity activity = getActivity(); 899 if (activity != null) { 900 activity.setResult(Activity.RESULT_OK); 901 activity.finish(); 902 } 903 return; 904 } 905 } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) { 906 updateConnectionState(null); 907 } 908 } 909 910 private void updateConnectionState(DetailedState state) { 911 /* sticky broadcasts can call this when wifi is disabled */ 912 if (!mWifiManager.isWifiEnabled()) { 913 mScanner.pause(); 914 return; 915 } 916 917 if (state == DetailedState.OBTAINING_IPADDR) { 918 mScanner.pause(); 919 } else { 920 mScanner.resume(); 921 } 922 923 mLastInfo = mWifiManager.getConnectionInfo(); 924 if (state != null) { 925 mLastState = state; 926 } 927 928 for (int i = getPreferenceScreen().getPreferenceCount() - 1; i >= 0; --i) { 929 // Maybe there's a WifiConfigPreference 930 Preference preference = getPreferenceScreen().getPreference(i); 931 if (preference instanceof AccessPoint) { 932 final AccessPoint accessPoint = (AccessPoint) preference; 933 accessPoint.update(mLastInfo, mLastState); 934 } 935 } 936 } 937 938 private void updateWifiState(int state) { 939 Activity activity = getActivity(); 940 if (activity != null) { 941 activity.invalidateOptionsMenu(); 942 } 943 944 switch (state) { 945 case WifiManager.WIFI_STATE_ENABLED: 946 mScanner.resume(); 947 return; // not break, to avoid the call to pause() below 948 949 case WifiManager.WIFI_STATE_ENABLING: 950 addMessagePreference(R.string.wifi_starting); 951 break; 952 953 case WifiManager.WIFI_STATE_DISABLED: 954 setOffMessage(); 955 break; 956 } 957 958 mLastInfo = null; 959 mLastState = null; 960 mScanner.pause(); 961 } 962 963 private class Scanner extends Handler { 964 private int mRetry = 0; 965 966 void resume() { 967 if (!hasMessages(0)) { 968 sendEmptyMessage(0); 969 } 970 } 971 972 void forceScan() { 973 removeMessages(0); 974 sendEmptyMessage(0); 975 } 976 977 void pause() { 978 mRetry = 0; 979 removeMessages(0); 980 } 981 982 @Override 983 public void handleMessage(Message message) { 984 if (mWifiManager.startScan()) { 985 mRetry = 0; 986 } else if (++mRetry >= 3) { 987 mRetry = 0; 988 Activity activity = getActivity(); 989 if (activity != null) { 990 Toast.makeText(activity, R.string.wifi_fail_to_scan, 991 Toast.LENGTH_LONG).show(); 992 } 993 return; 994 } 995 sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS); 996 } 997 } 998 999 /** 1000 * Renames/replaces "Next" button when appropriate. "Next" button usually exists in 1001 * Wifi setup screens, not in usual wifi settings screen. 1002 * 1003 * @param connected true when the device is connected to a wifi network. 1004 */ 1005 private void changeNextButtonState(boolean connected) { 1006 if (mEnableNextOnConnection && hasNextButton()) { 1007 getNextButton().setEnabled(connected); 1008 } 1009 } 1010 1011 @Override 1012 public void onClick(DialogInterface dialogInterface, int button) { 1013 if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) { 1014 forget(); 1015 } else if (button == WifiDialog.BUTTON_SUBMIT) { 1016 if (mDialog != null) { 1017 submit(mDialog.getController()); 1018 } 1019 } 1020 } 1021 1022 /* package */ void submit(WifiConfigController configController) { 1023 1024 final WifiConfiguration config = configController.getConfig(); 1025 1026 if (config == null) { 1027 if (mSelectedAccessPoint != null 1028 && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) { 1029 mWifiManager.connect(mSelectedAccessPoint.networkId, 1030 mConnectListener); 1031 } 1032 } else if (config.networkId != INVALID_NETWORK_ID) { 1033 if (mSelectedAccessPoint != null) { 1034 mWifiManager.save(config, mSaveListener); 1035 } 1036 } else { 1037 if (configController.isEdit()) { 1038 mWifiManager.save(config, mSaveListener); 1039 } else { 1040 mWifiManager.connect(config, mConnectListener); 1041 } 1042 } 1043 1044 if (mWifiManager.isWifiEnabled()) { 1045 mScanner.resume(); 1046 } 1047 updateAccessPoints(); 1048 } 1049 1050 /* package */ void forget() { 1051 if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) { 1052 // Should not happen, but a monkey seems to triger it 1053 Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig()); 1054 return; 1055 } 1056 1057 mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener); 1058 1059 if (mWifiManager.isWifiEnabled()) { 1060 mScanner.resume(); 1061 } 1062 updateAccessPoints(); 1063 1064 // We need to rename/replace "Next" button in wifi setup context. 1065 changeNextButtonState(false); 1066 } 1067 1068 /** 1069 * Refreshes acccess points and ask Wifi module to scan networks again. 1070 */ 1071 /* package */ void refreshAccessPoints() { 1072 if (mWifiManager.isWifiEnabled()) { 1073 mScanner.resume(); 1074 } 1075 1076 getPreferenceScreen().removeAll(); 1077 } 1078 1079 /** 1080 * Called when "add network" button is pressed. 1081 */ 1082 /* package */ void onAddNetworkPressed() { 1083 // No exact access point is selected. 1084 mSelectedAccessPoint = null; 1085 showDialog(null, true); 1086 } 1087 1088 /* package */ int getAccessPointsCount() { 1089 final boolean wifiIsEnabled = mWifiManager.isWifiEnabled(); 1090 if (wifiIsEnabled) { 1091 return getPreferenceScreen().getPreferenceCount(); 1092 } else { 1093 return 0; 1094 } 1095 } 1096 1097 /** 1098 * Requests wifi module to pause wifi scan. May be ignored when the module is disabled. 1099 */ 1100 /* package */ void pauseWifiScan() { 1101 if (mWifiManager.isWifiEnabled()) { 1102 mScanner.pause(); 1103 } 1104 } 1105 1106 /** 1107 * Requests wifi module to resume wifi scan. May be ignored when the module is disabled. 1108 */ 1109 /* package */ void resumeWifiScan() { 1110 if (mWifiManager.isWifiEnabled()) { 1111 mScanner.resume(); 1112 } 1113 } 1114 1115 @Override 1116 protected int getHelpResource() { 1117 if (mSetupWizardMode) { 1118 return 0; 1119 } 1120 return R.string.help_url_wifi; 1121 } 1122 1123 /** 1124 * Used as the outer frame of all setup wizard pages that need to adjust their margins based 1125 * on the total size of the available display. (e.g. side margins set to 10% of total width.) 1126 */ 1127 public static class ProportionalOuterFrame extends RelativeLayout { 1128 public ProportionalOuterFrame(Context context) { 1129 super(context); 1130 } 1131 public ProportionalOuterFrame(Context context, AttributeSet attrs) { 1132 super(context, attrs); 1133 } 1134 public ProportionalOuterFrame(Context context, AttributeSet attrs, int defStyle) { 1135 super(context, attrs, defStyle); 1136 } 1137 1138 /** 1139 * Set our margins and title area height proportionally to the available display size 1140 */ 1141 @Override 1142 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 1143 int parentWidth = MeasureSpec.getSize(widthMeasureSpec); 1144 int parentHeight = MeasureSpec.getSize(heightMeasureSpec); 1145 final Resources resources = getContext().getResources(); 1146 float titleHeight = resources.getFraction(R.dimen.setup_title_height, 1, 1); 1147 float sideMargin = resources.getFraction(R.dimen.setup_border_width, 1, 1); 1148 int bottom = resources.getDimensionPixelSize(R.dimen.setup_margin_bottom); 1149 setPaddingRelative( 1150 (int) (parentWidth * sideMargin), 1151 0, 1152 (int) (parentWidth * sideMargin), 1153 bottom); 1154 View title = findViewById(R.id.title_area); 1155 if (title != null) { 1156 title.setMinimumHeight((int) (parentHeight * titleHeight)); 1157 } 1158 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 1159 } 1160 } 1161 1162 public static final Indexable.IndexDataProvider INDEX_DATA_PROVIDER = 1163 new Indexable.IndexDataProvider() { 1164 @Override 1165 public List<IndexableRef> getRefsToIndex(Context context) { 1166 return null; 1167 } 1168 1169 @Override 1170 public List<IndexableData> getRawDataToIndex(Context context) { 1171 final List<IndexableData> result = new ArrayList<IndexableData>(); 1172 1173 // Add fragment title 1174 IndexableData data = new IndexableData(); 1175 data.title = context.getResources().getString(R.string.wifi_settings); 1176 data.fragmentTitle = context.getResources().getString(R.string.wifi_settings); 1177 result.add(data); 1178 1179 // Add available Wi-Fi access points 1180 WifiManager wifiManager = 1181 (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 1182 final Collection<AccessPoint> accessPoints = 1183 constructAccessPoints(context, wifiManager, null, null); 1184 for (AccessPoint accessPoint : accessPoints) { 1185 // We are indexing only the saved Wi-Fi networks. 1186 if (accessPoint.getConfig() == null) continue; 1187 data = new IndexableData(); 1188 data.title = accessPoint.getTitle().toString(); 1189 data.fragmentTitle = context.getResources().getString(R.string.wifi_settings); 1190 result.add(data); 1191 } 1192 1193 return result; 1194 } 1195 }; 1196} 1197