WifiSettings.java revision 1dc3715e3ac5100b1531fb2bdc7232d2c3508846
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 com.android.settings.ProgressCategoryBase;
22import com.android.settings.R;
23import com.android.settings.SettingsPreferenceFragment;
24
25import android.app.Activity;
26import android.app.AlertDialog;
27import android.content.BroadcastReceiver;
28import android.content.Context;
29import android.content.DialogInterface;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.net.ConnectivityManager;
33import android.net.NetworkInfo;
34import android.net.NetworkInfo.DetailedState;
35import android.net.wifi.ScanResult;
36import android.net.wifi.SupplicantState;
37import android.net.wifi.WifiConfiguration;
38import android.net.wifi.WifiConfiguration.KeyMgmt;
39import android.net.wifi.WifiInfo;
40import android.net.wifi.WifiManager;
41import android.os.Bundle;
42import android.os.Handler;
43import android.os.Message;
44import android.preference.CheckBoxPreference;
45import android.preference.Preference;
46import android.preference.PreferenceScreen;
47import android.provider.Settings.Secure;
48import android.security.Credentials;
49import android.security.KeyStore;
50import android.util.Log;
51import android.view.ContextMenu;
52import android.view.ContextMenu.ContextMenuInfo;
53import android.view.Menu;
54import android.view.MenuInflater;
55import android.view.MenuItem;
56import android.view.View;
57import android.widget.AdapterView.AdapterContextMenuInfo;
58import android.widget.Button;
59import android.widget.Toast;
60
61import java.util.Collection;
62import java.util.List;
63import java.util.TreeSet;
64
65/**
66 * This currently provides three types of UI.
67 *
68 * Two are for phones with relatively small screens: "for SetupWizard" and "for usual Settings".
69 * Users just need to launch WifiSettings Activity as usual. The request will be appropriately
70 * handled by ActivityManager, and they will have appropriate look-and-feel with this fragment.
71 *
72 * Third type is for Setup Wizard with X-Large, landscape UI. Users need to launch
73 * {@link WifiSettingsForSetupWizardXL} Activity, which contains this fragment but also has
74 * other decorations specific to that screen.
75 */
76public class WifiSettings extends SettingsPreferenceFragment
77        implements DialogInterface.OnClickListener {
78    private static final int MENU_ID_SCAN = Menu.FIRST;
79    private static final int MENU_ID_ADVANCED = Menu.FIRST + 1;
80    private static final int MENU_ID_CONNECT = Menu.FIRST + 2;
81    private static final int MENU_ID_FORGET = Menu.FIRST + 3;
82    private static final int MENU_ID_MODIFY = Menu.FIRST + 4;
83
84    // Indicates that this fragment is used as a part of Setup Wizard with XL screen settings.
85    // This fragment should show information which has been shown as Dialog in combined UI
86    // inside this fragment.
87    /* package */ static final String IN_XL_SETUP_WIZARD = "in_setup_wizard";
88
89    // this boolean extra specifies whether to disable the Next button when not connected
90    // Note: this is only effective in Setup Wizard with XL screen size.
91    private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
92
93    // In SetupWizard XL, We limit the number of showable access points so that the
94    // ListView won't become larger than the screen.
95    //
96    // This constant doesn't affect other contexts other than SetupWizard XL.
97    private static int MAX_MENU_COUNT_IN_XL = 8;
98
99    private final IntentFilter mFilter;
100    private final BroadcastReceiver mReceiver;
101    private final Scanner mScanner;
102
103    private WifiManager mWifiManager;
104    private WifiEnabler mWifiEnabler;
105    private CheckBoxPreference mNotifyOpenNetworks;
106    private ProgressCategoryBase mAccessPoints;
107    private Preference mAddNetwork;
108    // An access point being editted is stored here.
109    private AccessPoint mSelectedAccessPoint;
110    private boolean mEdit;
111
112    private DetailedState mLastState;
113    private WifiInfo mLastInfo;
114
115    private int mKeyStoreNetworkId = INVALID_NETWORK_ID;
116
117    // should Next button only be enabled when we have a connection?
118    private boolean mEnableNextOnConnection;
119    private boolean mInXlSetupWizard;
120
121
122    // TODO: merge into one
123    private WifiConfigPreference mConfigPreference;
124    private WifiDialog mDialog;
125
126    // Used only in SetupWizard XL, which remembers the network a user selected and
127    // refrain other available networks when trying to connect it.
128    private AccessPoint mConnectingAccessPoint;
129
130    private boolean mRefrainListUpdate;
131
132    public WifiSettings() {
133        mFilter = new IntentFilter();
134        mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
135        mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
136        mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
137        mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
138        mFilter.addAction(WifiManager.SUPPLICANT_CONFIG_CHANGED_ACTION);
139        mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
140        mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
141
142        mReceiver = new BroadcastReceiver() {
143            @Override
144            public void onReceive(Context context, Intent intent) {
145                handleEvent(intent);
146            }
147        };
148
149        mScanner = new Scanner();
150    }
151
152    @Override
153    public void onActivityCreated(Bundle savedInstanceState) {
154        // We don't call super.onActivityCreated() here, since it assumes we already set up
155        // Preference (probably in onCreate()), while WifiSettings exceptionally set it up in
156        // this method.
157
158        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
159
160        final Activity activity = getActivity();
161        final Intent intent = activity.getIntent();
162
163        mInXlSetupWizard = intent.getBooleanExtra(IN_XL_SETUP_WIZARD, false);
164
165        // if we're supposed to enable/disable the Next button based on our current connection
166        // state, start it off in the right state
167        mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
168
169        if (mEnableNextOnConnection) {
170            if (mEnableNextOnConnection && hasNextButton()) {
171                final ConnectivityManager connectivity = (ConnectivityManager)
172                        getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
173                if (connectivity != null) {
174                    NetworkInfo info = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
175                    changeNextButtonState(info.isConnected());
176                }
177            }
178        }
179
180        if (mInXlSetupWizard) {
181            addPreferencesFromResource(R.xml.wifi_access_points_for_wifi_setup_xl);
182        } else if (intent.getBooleanExtra("only_access_points", false)) {
183            addPreferencesFromResource(R.xml.wifi_access_points);
184        } else {
185            addPreferencesFromResource(R.xml.wifi_settings);
186            mWifiEnabler = new WifiEnabler(activity,
187                    (CheckBoxPreference) findPreference("enable_wifi"));
188            mNotifyOpenNetworks =
189                    (CheckBoxPreference) findPreference("notify_open_networks");
190            mNotifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(),
191                    Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
192        }
193
194        // After confirming PreferenceScreen is available, we call super.
195        super.onActivityCreated(savedInstanceState);
196
197        // This may be either ProgressCategory or AccessPointCategoryForXL.
198        final ProgressCategoryBase preference =
199                (ProgressCategoryBase) findPreference("access_points");
200        mAccessPoints = preference;
201        mAccessPoints.setOrderingAsAdded(true);
202        mAddNetwork = findPreference("add_network");
203
204        registerForContextMenu(getListView());
205        setHasOptionsMenu(true);
206    }
207
208    @Override
209    public void onResume() {
210        super.onResume();
211        if (mWifiEnabler != null) {
212            mWifiEnabler.resume();
213        }
214        getActivity().registerReceiver(mReceiver, mFilter);
215        if (mKeyStoreNetworkId != INVALID_NETWORK_ID &&
216                KeyStore.getInstance().test() == KeyStore.NO_ERROR) {
217            mWifiManager.connectNetwork(mKeyStoreNetworkId);
218        }
219        mKeyStoreNetworkId = INVALID_NETWORK_ID;
220        if (mInXlSetupWizard) {
221            // We show "Now scanning"
222            final int wifiState = mWifiManager.getWifiState();
223            switch (wifiState) {
224            case WifiManager.WIFI_STATE_ENABLED: {
225                updateAccessPoints();
226                break;
227            }
228            case WifiManager.WIFI_STATE_DISABLED:
229            case WifiManager.WIFI_STATE_DISABLING:
230            case WifiManager.WIFI_STATE_UNKNOWN: {
231                mWifiManager.setWifiEnabled(true);
232            } // $FALL-THROUGH$
233            default: {
234                mAccessPoints.removeAll();
235                Preference preference = new Preference(getActivity());
236                preference.setLayoutResource(R.layout.preference_widget_shortcut);
237                preference.setSelectable(false);
238                preference.setTitle("Connecting");
239                preference.setSummary("COONNECTING");
240                mAccessPoints.addPreference(preference);
241                break;
242            }
243            }
244        } else {
245            updateAccessPoints();
246        }
247    }
248
249    @Override
250    public void onPause() {
251        super.onPause();
252        if (mWifiEnabler != null) {
253            mWifiEnabler.pause();
254        }
255        getActivity().unregisterReceiver(mReceiver);
256        mScanner.pause();
257        if (mDialog != null) {
258            mDialog.dismiss();
259            mDialog = null;
260        }
261    }
262
263    @Override
264    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
265        // We don't want menus in Setup Wizard XL.
266        if (!mInXlSetupWizard) {
267            menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan)
268                    .setIcon(R.drawable.ic_menu_scan_network);
269            menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced)
270                    .setIcon(android.R.drawable.ic_menu_manage);
271        }
272        super.onCreateOptionsMenu(menu, inflater);
273    }
274
275    @Override
276    public boolean onOptionsItemSelected(MenuItem item) {
277        switch (item.getItemId()) {
278            case MENU_ID_SCAN:
279                if (mWifiManager.isWifiEnabled()) {
280                    mScanner.resume();
281                }
282                return true;
283            case MENU_ID_ADVANCED:
284                startFragment(this, AdvancedSettings.class.getCanonicalName(), -1, null);
285                return true;
286        }
287        return super.onOptionsItemSelected(item);
288    }
289
290    @Override
291    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
292        if (info instanceof AdapterContextMenuInfo) {
293            Preference preference = (Preference) getListView().getItemAtPosition(
294                    ((AdapterContextMenuInfo) info).position);
295
296            if (preference instanceof AccessPoint) {
297                mSelectedAccessPoint = (AccessPoint) preference;
298                menu.setHeaderTitle(mSelectedAccessPoint.ssid);
299                if (mSelectedAccessPoint.getLevel() != -1
300                        && mSelectedAccessPoint.getState() == null) {
301                    menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect);
302                }
303                if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
304                    menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget);
305                    menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify);
306                }
307            }
308        }
309    }
310
311    @Override
312    public boolean onContextItemSelected(MenuItem item) {
313        if (mSelectedAccessPoint == null) {
314            return super.onContextItemSelected(item);
315        }
316        switch (item.getItemId()) {
317            case MENU_ID_CONNECT: {
318                if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
319                    if (!requireKeyStore(mSelectedAccessPoint.getConfig())) {
320                        mWifiManager.connectNetwork(mSelectedAccessPoint.networkId);
321                    }
322                } else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) {
323                    // Shortcut for open networks.
324                    WifiConfiguration config = new WifiConfiguration();
325                    config.SSID = AccessPoint.convertToQuotedString(mSelectedAccessPoint.ssid);
326                    config.allowedKeyManagement.set(KeyMgmt.NONE);
327                    mWifiManager.connectNetwork(config);
328                } else {
329                    showConfigUi(mSelectedAccessPoint, true);
330                }
331                return true;
332            }
333            case MENU_ID_FORGET: {
334                mWifiManager.forgetNetwork(mSelectedAccessPoint.networkId);
335                return true;
336            }
337            case MENU_ID_MODIFY: {
338                showConfigUi(mSelectedAccessPoint, true);
339                return true;
340            }
341        }
342        return super.onContextItemSelected(item);
343    }
344
345    @Override
346    public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
347        if (preference instanceof AccessPoint) {
348            mSelectedAccessPoint = (AccessPoint) preference;
349            showConfigUi(mSelectedAccessPoint, false);
350        } else if (preference == mAddNetwork) {
351            onAddNetworkPressed();
352        } else if (preference == mNotifyOpenNetworks) {
353            Secure.putInt(getContentResolver(),
354                    Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
355                    mNotifyOpenNetworks.isChecked() ? 1 : 0);
356        } else {
357            return super.onPreferenceTreeClick(screen, preference);
358        }
359        return true;
360    }
361
362    /**
363     * Called when a user clicks "Add network" preference or relevant button.
364     */
365    private void showConfigUi(AccessPoint accessPoint, boolean edit) {
366        synchronized (this) {
367            mRefrainListUpdate = false;
368        }
369        mEdit = edit;
370        if (mInXlSetupWizard) {
371            final Activity activity = getActivity();
372            activity.findViewById(R.id.wifi_setup_connect).setVisibility(View.VISIBLE);
373            activity.findViewById(R.id.wifi_setup_cancel).setVisibility(View.VISIBLE);
374            activity.findViewById(R.id.wifi_setup_detail).setVisibility(View.VISIBLE);
375            showConfigPreference(accessPoint, edit);
376        } else {
377            showDialog(accessPoint, edit);
378        }
379    }
380
381    private void showConfigPreference(AccessPoint accessPoint, boolean edit) {
382        // We don't want to show more than one WifiConfigPreference
383        if (mConfigPreference != null) {
384            mAccessPoints.removePreference(mConfigPreference);
385        }
386
387        mConfigPreference = new WifiConfigPreference(this, this, accessPoint, edit);
388        toggleButtonsVisibility(false);
389        final Activity activity = getActivity();
390        if (activity instanceof WifiSettingsForSetupWizardXL) {
391            ((WifiSettingsForSetupWizardXL)activity).onWifiConfigPreferenceAttached(edit);
392        }
393        updateAccessPoints();
394        mScanner.pause();
395    }
396
397    private void toggleButtonsVisibility(boolean firstLayout) {
398        final Activity activity = getActivity();
399        if (firstLayout) {
400            activity.findViewById(R.id.wifi_setup_add_network).setVisibility(View.VISIBLE);
401            activity.findViewById(R.id.wifi_setup_refresh_list).setVisibility(View.VISIBLE);
402            activity.findViewById(R.id.wifi_setup_skip_or_next).setVisibility(View.VISIBLE);
403            activity.findViewById(R.id.wifi_setup_connect).setVisibility(View.GONE);
404            activity.findViewById(R.id.wifi_setup_forget).setVisibility(View.GONE);
405            activity.findViewById(R.id.wifi_setup_cancel).setVisibility(View.GONE);
406            activity.findViewById(R.id.wifi_setup_detail).setVisibility(View.GONE);
407        } else {
408            activity.findViewById(R.id.wifi_setup_add_network).setVisibility(View.GONE);
409            activity.findViewById(R.id.wifi_setup_refresh_list).setVisibility(View.GONE);
410            activity.findViewById(R.id.wifi_setup_skip_or_next).setVisibility(View.GONE);
411
412            // made visible from controller.
413        }
414    }
415
416    private void showDialog(AccessPoint accessPoint, boolean edit) {
417        if (mDialog != null) {
418            mDialog.dismiss();
419        }
420        mDialog = new WifiDialog(getActivity(), this, accessPoint, edit);
421        mDialog.show();
422    }
423
424    /* package */ void showDialogForSelectedPreference() {
425        showDialog(mSelectedAccessPoint, mEdit);
426    }
427
428    private boolean requireKeyStore(WifiConfiguration config) {
429        if (WifiConfigController.requireKeyStore(config) &&
430                KeyStore.getInstance().test() != KeyStore.NO_ERROR) {
431            mKeyStoreNetworkId = config.networkId;
432            Credentials.getInstance().unlock(getActivity());
433            return true;
434        }
435        return false;
436    }
437
438    /**
439     * Shows the latest access points available with supplimental information like
440     * the strength of network and the security for it.
441     */
442    private void updateAccessPoints() {
443        synchronized (this) {
444            if (mRefrainListUpdate) {
445                return;
446            }
447        }
448
449        mAccessPoints.removeAll();
450        if (mConnectingAccessPoint != null) {
451            mAccessPoints.addPreference(mConnectingAccessPoint);
452        } else if (mConfigPreference != null) {
453            final AccessPoint parent = mConfigPreference.getAccessPoint();
454            if (parent != null) {
455                parent.setSelectable(false);
456                mAccessPoints.addPreference(parent);
457            }
458            mAccessPoints.addPreference(mConfigPreference);
459        } else {
460            // AccessPoints are automatically sorted with TreeSet.
461            final Collection<AccessPoint> accessPoints = constructAccessPoints();
462
463            if (mInXlSetupWizard) {
464                //limit access points on set up wizard
465                int count = MAX_MENU_COUNT_IN_XL;
466                for (AccessPoint accessPoint : accessPoints) {
467                    mAccessPoints.addPreference(accessPoint);
468                    count--;
469                    if (count <= 0) {
470                        break;
471                    }
472                }
473            } else {
474                for (AccessPoint accessPoint : accessPoints) {
475                    mAccessPoints.addPreference(accessPoint);
476                }
477            }
478        }
479    }
480
481    private Collection<AccessPoint> constructAccessPoints() {
482        Collection<AccessPoint> accessPoints =
483                new TreeSet<AccessPoint>(new AccessPoint.Comparater());
484
485        final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
486        if (configs != null) {
487            for (WifiConfiguration config : configs) {
488                AccessPoint accessPoint = new AccessPoint(getActivity(), config);
489                accessPoint.update(mLastInfo, mLastState);
490                accessPoints.add(accessPoint);
491            }
492        }
493
494        final List<ScanResult> results = mWifiManager.getScanResults();
495        if (results != null) {
496            for (ScanResult result : results) {
497                // Ignore hidden and ad-hoc networks.
498                if (result.SSID == null || result.SSID.length() == 0 ||
499                        result.capabilities.contains("[IBSS]")) {
500                    continue;
501                }
502
503                boolean found = false;
504                for (AccessPoint accessPoint : accessPoints) {
505                    if (accessPoint.update(result)) {
506                        found = true;
507                    }
508                }
509                if (!found) {
510                    accessPoints.add(new AccessPoint(getActivity(), result));
511                }
512            }
513        }
514
515        return accessPoints;
516    }
517
518    private void handleEvent(Intent intent) {
519        String action = intent.getAction();
520        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
521            updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
522                    WifiManager.WIFI_STATE_UNKNOWN));
523        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) ||
524                WifiManager.SUPPLICANT_CONFIG_CHANGED_ACTION.equals(action)) {
525                updateAccessPoints();
526        } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
527            updateConnectionState(WifiInfo.getDetailedStateOf((SupplicantState)
528                    intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE)));
529        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
530            NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
531                    WifiManager.EXTRA_NETWORK_INFO);
532            changeNextButtonState(info.isConnected());
533            updateConnectionState(info.getDetailedState());
534        } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
535            updateConnectionState(null);
536        }
537    }
538
539    private void updateConnectionState(DetailedState state) {
540        /* sticky broadcasts can call this when wifi is disabled */
541        if (!mWifiManager.isWifiEnabled()) {
542            mScanner.pause();
543            return;
544        }
545
546        if (state == DetailedState.OBTAINING_IPADDR) {
547            mScanner.pause();
548        } else {
549            mScanner.resume();
550        }
551
552        mLastInfo = mWifiManager.getConnectionInfo();
553        if (state != null) {
554            mLastState = state;
555        }
556
557        for (int i = mAccessPoints.getPreferenceCount() - 1; i >= 0; --i) {
558            // Maybe there's a WifiConfigPreference
559            Preference preference = mAccessPoints.getPreference(i);
560            if (preference instanceof AccessPoint) {
561                final AccessPoint accessPoint = (AccessPoint) preference;
562                accessPoint.update(mLastInfo, mLastState);
563            }
564        }
565
566        final Activity activity = getActivity();
567        if (activity instanceof WifiSettingsForSetupWizardXL) {
568            if (mLastState == DetailedState.FAILED) {
569                // We clean up the status and let users select another network if they want.
570                refreshAccessPoints();
571            }
572            ((WifiSettingsForSetupWizardXL)activity).updateConnectionState(mLastState);
573        }
574    }
575
576    private void updateWifiState(int state) {
577        if (state == WifiManager.WIFI_STATE_ENABLED) {
578            mScanner.resume();
579        } else {
580            mScanner.pause();
581            mAccessPoints.removeAll();
582        }
583    }
584
585    private class Scanner extends Handler {
586        private int mRetry = 0;
587
588        void resume() {
589            synchronized (WifiSettings.this) {
590                mRefrainListUpdate = false;
591            }
592            if (!hasMessages(0)) {
593                sendEmptyMessage(0);
594            }
595        }
596
597        void pause() {
598            mRetry = 0;
599            mAccessPoints.setProgress(false);
600            synchronized (WifiSettings.this) {
601                mRefrainListUpdate = true;
602            }
603            removeMessages(0);
604        }
605
606        @Override
607        public void handleMessage(Message message) {
608            if (mWifiManager.startScanActive()) {
609                mRetry = 0;
610            } else if (++mRetry >= 3) {
611                mRetry = 0;
612                Toast.makeText(getActivity(), R.string.wifi_fail_to_scan,
613                        Toast.LENGTH_LONG).show();
614                return;
615            }
616            mAccessPoints.setProgress(mRetry != 0);
617            // Combo scans can take 5-6s to complete. Increase interval to 10s.
618            sendEmptyMessageDelayed(0, 10000);
619        }
620    }
621
622    private void changeNextButtonState(boolean wifiAvailable) {
623        if (mInXlSetupWizard) {
624            final Button button =
625                    (Button)getActivity().findViewById(R.id.wifi_setup_skip_or_next);
626            if (wifiAvailable) {
627                button.setText(R.string.wifi_setup_next);
628            } else {
629                button.setText(R.string.wifi_setup_skip);
630            }
631        } else if (mEnableNextOnConnection && hasNextButton()) {
632            // Assumes layout for phones has next button inside it.
633            getNextButton().setEnabled(wifiAvailable);
634        }
635    }
636
637    public void onClick(DialogInterface dialogInterface, int button) {
638        if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
639            forget();
640        } else if (button == WifiDialog.BUTTON_SUBMIT) {
641            submit();
642        }
643    }
644
645    /* package */ void submit() {
646        final WifiConfigUiBase uiBase = (mDialog != null ? mDialog : mConfigPreference);
647        final WifiConfigController configController = uiBase.getController();
648
649        boolean successful = true;
650        switch(configController.chosenNetworkSetupMethod()) {
651            case WifiConfigController.WPS_PBC:
652                mWifiManager.startWpsPbc(mSelectedAccessPoint.bssid);
653                break;
654            case WifiConfigController.WPS_PIN_FROM_ACCESS_POINT:
655                int apPin = configController.getWpsPin();
656                mWifiManager.startWpsWithPinFromAccessPoint(mSelectedAccessPoint.bssid, apPin);
657                break;
658            case WifiConfigController.WPS_PIN_FROM_DEVICE:
659                int pin = mWifiManager.startWpsWithPinFromDevice(mSelectedAccessPoint.bssid);
660                new AlertDialog.Builder(getActivity())
661                .setTitle(R.string.wifi_wps_pin_method_configuration)
662                .setMessage(getResources().getString(R.string.wifi_wps_pin_output, pin))
663                .setPositiveButton(android.R.string.ok, null)
664                .show();
665                break;
666            case WifiConfigController.MANUAL:
667                final WifiConfiguration config = configController.getConfig();
668
669                if (config == null) {
670                    if (mSelectedAccessPoint != null
671                            && !requireKeyStore(mSelectedAccessPoint.getConfig())
672                            && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
673                        mWifiManager.connectNetwork(mSelectedAccessPoint.networkId);
674                    } else {
675                        successful = false;
676                    }
677                } else if (config.networkId != INVALID_NETWORK_ID) {
678                    if (mSelectedAccessPoint != null) {
679                        mWifiManager.saveNetwork(config);
680                    }
681                } else {
682                    if (uiBase.isEdit() || requireKeyStore(config)) {
683                        mWifiManager.saveNetwork(config);
684                    } else {
685                        mWifiManager.connectNetwork(config);
686                    }
687                }
688                break;
689        }
690
691        if (mInXlSetupWizard && successful && mConfigPreference != null) {
692            // Now connecting to the AccessPoint.
693            mConnectingAccessPoint = mSelectedAccessPoint;
694            mConnectingAccessPoint.setSelectable(false);
695        }
696
697        detachConfigPreference();
698    }
699
700    /* package */ void forget() {
701        mWifiManager.forgetNetwork(mSelectedAccessPoint.networkId);
702
703        detachConfigPreference();
704
705        changeNextButtonState(false);
706
707        final Activity activity = getActivity();
708        if (activity instanceof WifiSettingsForSetupWizardXL) {
709            ((WifiSettingsForSetupWizardXL)activity).onForget();
710        }
711    }
712
713    /* package */ void refreshAccessPoints() {
714        mWifiManager.disconnect();
715        if (mWifiManager.isWifiEnabled()) {
716            mScanner.resume();
717        }
718
719        mConfigPreference = null;
720        mConnectingAccessPoint = null;
721        mAccessPoints.removeAll();
722
723        if (mInXlSetupWizard) {
724            ((WifiSettingsForSetupWizardXL)getActivity()).onRefreshAccessPoints();
725        }
726    }
727
728    /* package */ void detachConfigPreference() {
729        if (mConfigPreference != null) {
730            if (mWifiManager.isWifiEnabled()) {
731                mScanner.resume();
732            }
733            mAccessPoints.removePreference(mConfigPreference);
734            mConfigPreference = null;
735            updateAccessPoints();
736            toggleButtonsVisibility(true);
737        }
738    }
739
740    /* package */ void onAddNetworkPressed() {
741        mSelectedAccessPoint = null;
742        showConfigUi(null, true);
743    }
744
745    /* package */ int getAccessPointsCount() {
746        if (mAccessPoints != null) {
747            return mAccessPoints.getPreferenceCount();
748        } else {
749            return 0;
750        }
751    }
752
753    /* package */ void disableWifi() {
754        mWifiManager.setWifiEnabled(false);
755    }
756}
757