WifiSettings.java revision e45e13f47ad5e09aa8291d81a03a136618b383c0
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 = 6;
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
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        if (mInXlSetupWizard) {
369            final Activity activity = getActivity();
370            activity.findViewById(R.id.wifi_setup_connect).setVisibility(View.VISIBLE);
371            activity.findViewById(R.id.wifi_setup_cancel).setVisibility(View.VISIBLE);
372            showConfigPreference(accessPoint, edit);
373        } else {
374            showDialog(accessPoint, edit);
375        }
376    }
377
378    private void showConfigPreference(AccessPoint accessPoint, boolean edit) {
379        // We don't want to show more than one WifiConfigPreference
380        if (mConfigPreference != null) {
381            mAccessPoints.removePreference(mConfigPreference);
382        }
383
384        mConfigPreference = new WifiConfigPreference(this, this, accessPoint, edit);
385        toggleButtonsVisibility(false);
386        final Activity activity = getActivity();
387        if (activity instanceof WifiSettingsForSetupWizardXL) {
388            ((WifiSettingsForSetupWizardXL)activity).onWifiConfigPreferenceAttached(edit);
389        }
390        updateAccessPoints();
391        mScanner.pause();
392    }
393
394    private void toggleButtonsVisibility(boolean firstLayout) {
395        final Activity activity = getActivity();
396        if (firstLayout) {
397            activity.findViewById(R.id.wifi_setup_add_network).setVisibility(View.VISIBLE);
398            activity.findViewById(R.id.wifi_setup_refresh_list).setVisibility(View.VISIBLE);
399            activity.findViewById(R.id.wifi_setup_skip_or_next).setVisibility(View.VISIBLE);
400            activity.findViewById(R.id.wifi_setup_connect).setVisibility(View.GONE);
401            activity.findViewById(R.id.wifi_setup_forget).setVisibility(View.GONE);
402            activity.findViewById(R.id.wifi_setup_cancel).setVisibility(View.GONE);
403        } else {
404            activity.findViewById(R.id.wifi_setup_add_network).setVisibility(View.GONE);
405            activity.findViewById(R.id.wifi_setup_refresh_list).setVisibility(View.GONE);
406            activity.findViewById(R.id.wifi_setup_skip_or_next).setVisibility(View.GONE);
407
408            // made visible from controller.
409        }
410    }
411
412    private void showDialog(AccessPoint accessPoint, boolean edit) {
413        if (mDialog != null) {
414            mDialog.dismiss();
415        }
416        mDialog = new WifiDialog(getActivity(), this, accessPoint, edit);
417        mDialog.show();
418    }
419
420    private boolean requireKeyStore(WifiConfiguration config) {
421        if (WifiConfigController.requireKeyStore(config) &&
422                KeyStore.getInstance().test() != KeyStore.NO_ERROR) {
423            mKeyStoreNetworkId = config.networkId;
424            Credentials.getInstance().unlock(getActivity());
425            return true;
426        }
427        return false;
428    }
429
430    /**
431     * Shows the latest access points available with supplimental information like
432     * the strength of network and the security for it.
433     */
434    private void updateAccessPoints() {
435        synchronized (this) {
436            if (mRefrainListUpdate) {
437                return;
438            }
439        }
440
441        mAccessPoints.removeAll();
442        if (mConnectingAccessPoint != null) {
443            mAccessPoints.addPreference(mConnectingAccessPoint);
444        } else if (mConfigPreference != null) {
445            final AccessPoint parent = mConfigPreference.getAccessPoint();
446            if (parent != null) {
447                parent.setSelectable(false);
448                mAccessPoints.addPreference(parent);
449            }
450            mAccessPoints.addPreference(mConfigPreference);
451        } else {
452            // AccessPoints are automatically sorted with TreeSet.
453            final Collection<AccessPoint> accessPoints = constructAccessPoints();
454
455            if (mInXlSetupWizard) {
456                //limit access points on set up wizard
457                int count = MAX_MENU_COUNT_IN_XL;
458                for (AccessPoint accessPoint : accessPoints) {
459                    mAccessPoints.addPreference(accessPoint);
460                    count--;
461                    if (count <= 0) {
462                        break;
463                    }
464                }
465            } else {
466                for (AccessPoint accessPoint : accessPoints) {
467                    mAccessPoints.addPreference(accessPoint);
468                }
469            }
470        }
471    }
472
473    private Collection<AccessPoint> constructAccessPoints() {
474        Collection<AccessPoint> accessPoints =
475                new TreeSet<AccessPoint>(new AccessPoint.Comparater());
476
477        final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
478        if (configs != null) {
479            for (WifiConfiguration config : configs) {
480                AccessPoint accessPoint = new AccessPoint(getActivity(), config);
481                accessPoint.update(mLastInfo, mLastState);
482                accessPoints.add(accessPoint);
483            }
484        }
485
486        final List<ScanResult> results = mWifiManager.getScanResults();
487        if (results != null) {
488            for (ScanResult result : results) {
489                // Ignore hidden and ad-hoc networks.
490                if (result.SSID == null || result.SSID.length() == 0 ||
491                        result.capabilities.contains("[IBSS]")) {
492                    continue;
493                }
494
495                boolean found = false;
496                for (AccessPoint accessPoint : accessPoints) {
497                    if (accessPoint.update(result)) {
498                        found = true;
499                    }
500                }
501                if (!found) {
502                    accessPoints.add(new AccessPoint(getActivity(), result));
503                }
504            }
505        }
506
507        return accessPoints;
508    }
509
510    private void handleEvent(Intent intent) {
511        String action = intent.getAction();
512        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
513            updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
514                    WifiManager.WIFI_STATE_UNKNOWN));
515        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) ||
516                WifiManager.SUPPLICANT_CONFIG_CHANGED_ACTION.equals(action)) {
517                updateAccessPoints();
518        } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
519            updateConnectionState(WifiInfo.getDetailedStateOf((SupplicantState)
520                    intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE)));
521        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
522            NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
523                    WifiManager.EXTRA_NETWORK_INFO);
524            changeNextButtonState(info.isConnected());
525            updateConnectionState(info.getDetailedState());
526        } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
527            updateConnectionState(null);
528        }
529    }
530
531    private void updateConnectionState(DetailedState state) {
532        /* sticky broadcasts can call this when wifi is disabled */
533        if (!mWifiManager.isWifiEnabled()) {
534            mScanner.pause();
535            return;
536        }
537
538        if (state == DetailedState.OBTAINING_IPADDR) {
539            mScanner.pause();
540        } else {
541            mScanner.resume();
542        }
543
544        mLastInfo = mWifiManager.getConnectionInfo();
545        if (state != null) {
546            mLastState = state;
547        }
548
549        for (int i = mAccessPoints.getPreferenceCount() - 1; i >= 0; --i) {
550            // Maybe there's a WifiConfigPreference
551            Preference preference = mAccessPoints.getPreference(i);
552            if (preference instanceof AccessPoint) {
553                final AccessPoint accessPoint = (AccessPoint) preference;
554                accessPoint.update(mLastInfo, mLastState);
555            }
556        }
557
558        final Activity activity = getActivity();
559        if (activity instanceof WifiSettingsForSetupWizardXL) {
560            if (mLastState == DetailedState.FAILED) {
561                // We clean up the status and let users select another network if they want.
562                refreshAccessPoints();
563            }
564            ((WifiSettingsForSetupWizardXL)activity).updateConnectionState(mLastState);
565        }
566    }
567
568    private void updateWifiState(int state) {
569        if (state == WifiManager.WIFI_STATE_ENABLED) {
570            mScanner.resume();
571        } else {
572            mScanner.pause();
573            mAccessPoints.removeAll();
574        }
575    }
576
577    private class Scanner extends Handler {
578        private int mRetry = 0;
579
580        void resume() {
581            synchronized (WifiSettings.this) {
582                mRefrainListUpdate = false;
583            }
584            if (!hasMessages(0)) {
585                sendEmptyMessage(0);
586            }
587        }
588
589        void pause() {
590            mRetry = 0;
591            mAccessPoints.setProgress(false);
592            synchronized (WifiSettings.this) {
593                mRefrainListUpdate = true;
594            }
595            removeMessages(0);
596        }
597
598        @Override
599        public void handleMessage(Message message) {
600            if (mWifiManager.startScanActive()) {
601                mRetry = 0;
602            } else if (++mRetry >= 3) {
603                mRetry = 0;
604                Toast.makeText(getActivity(), R.string.wifi_fail_to_scan,
605                        Toast.LENGTH_LONG).show();
606                return;
607            }
608            mAccessPoints.setProgress(mRetry != 0);
609            // Combo scans can take 5-6s to complete. Increase interval to 10s.
610            sendEmptyMessageDelayed(0, 10000);
611        }
612    }
613
614    private void changeNextButtonState(boolean wifiAvailable) {
615        if (mInXlSetupWizard) {
616            final Button button =
617                    (Button)getActivity().findViewById(R.id.wifi_setup_skip_or_next);
618            if (wifiAvailable) {
619                button.setText(R.string.wifi_setup_next);
620            } else {
621                button.setText(R.string.wifi_setup_skip);
622            }
623        } else if (mEnableNextOnConnection && hasNextButton()) {
624            // Assumes layout for phones has next button inside it.
625            getNextButton().setEnabled(wifiAvailable);
626        }
627    }
628
629    public void onClick(DialogInterface dialogInterface, int button) {
630        if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
631            forget();
632        } else if (button == WifiDialog.BUTTON_SUBMIT) {
633            submit();
634        }
635    }
636
637    /* package */ void submit() {
638        final WifiConfigUiBase uiBase = (mDialog != null ? mDialog : mConfigPreference);
639        final WifiConfigController configController = uiBase.getController();
640
641        boolean successful = true;
642        switch(configController.chosenNetworkSetupMethod()) {
643            case WifiConfigController.WPS_PBC:
644                mWifiManager.startWpsPbc(mSelectedAccessPoint.bssid);
645                break;
646            case WifiConfigController.WPS_PIN_FROM_ACCESS_POINT:
647                int apPin = configController.getWpsPin();
648                mWifiManager.startWpsWithPinFromAccessPoint(mSelectedAccessPoint.bssid, apPin);
649                break;
650            case WifiConfigController.WPS_PIN_FROM_DEVICE:
651                int pin = mWifiManager.startWpsWithPinFromDevice(mSelectedAccessPoint.bssid);
652                new AlertDialog.Builder(getActivity())
653                .setTitle(R.string.wifi_wps_pin_method_configuration)
654                .setMessage(getResources().getString(R.string.wifi_wps_pin_output, pin))
655                .setPositiveButton(android.R.string.ok, null)
656                .show();
657                break;
658            case WifiConfigController.MANUAL:
659                final WifiConfiguration config = configController.getConfig();
660
661                if (config == null) {
662                    if (mSelectedAccessPoint != null
663                            && !requireKeyStore(mSelectedAccessPoint.getConfig())
664                            && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
665                        mWifiManager.connectNetwork(mSelectedAccessPoint.networkId);
666                    } else {
667                        successful = false;
668                    }
669                } else if (config.networkId != INVALID_NETWORK_ID) {
670                    if (mSelectedAccessPoint != null) {
671                        mWifiManager.saveNetwork(config);
672                    }
673                } else {
674                    if (uiBase.isEdit() || requireKeyStore(config)) {
675                        mWifiManager.saveNetwork(config);
676                    } else {
677                        mWifiManager.connectNetwork(config);
678                    }
679                }
680                break;
681        }
682
683        if (mInXlSetupWizard && successful && mConfigPreference != null) {
684            // Now connecting to the AccessPoint.
685            mConnectingAccessPoint = mSelectedAccessPoint;
686            mConnectingAccessPoint.setSelectable(false);
687        }
688
689        detachConfigPreference();
690    }
691
692    /* package */ void forget() {
693        mWifiManager.forgetNetwork(mSelectedAccessPoint.networkId);
694
695        detachConfigPreference();
696
697        changeNextButtonState(false);
698
699        final Activity activity = getActivity();
700        if (activity instanceof WifiSettingsForSetupWizardXL) {
701            ((WifiSettingsForSetupWizardXL)activity).onForget();
702        }
703    }
704
705    /* package */ void refreshAccessPoints() {
706        mWifiManager.disconnect();
707        if (mWifiManager.isWifiEnabled()) {
708            mScanner.resume();
709        }
710
711        mConfigPreference = null;
712        mConnectingAccessPoint = null;
713        mAccessPoints.removeAll();
714
715        if (mInXlSetupWizard) {
716            ((WifiSettingsForSetupWizardXL)getActivity()).onRefreshAccessPoints();
717        }
718    }
719
720    /* package */ void detachConfigPreference() {
721        if (mConfigPreference != null) {
722            if (mWifiManager.isWifiEnabled()) {
723                mScanner.resume();
724            }
725            mAccessPoints.removePreference(mConfigPreference);
726            mConfigPreference = null;
727            updateAccessPoints();
728            toggleButtonsVisibility(true);
729        }
730    }
731
732    /* package */ void onAddNetworkPressed() {
733        mSelectedAccessPoint = null;
734        showConfigUi(null, true);
735    }
736
737    /* package */ int getAccessPointsCount() {
738        if (mAccessPoints != null) {
739            return mAccessPoints.getPreferenceCount();
740        } else {
741            return 0;
742        }
743    }
744
745    /* package */ void disableWifi() {
746        mWifiManager.setWifiEnabled(false);
747    }
748}
749