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