WifiSettings.java revision 53fa78fcb237e52733d00a93a29485c4b3d7d290
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 android.app.ActionBar;
22import android.app.Activity;
23import android.app.AlertDialog;
24import android.app.Dialog;
25import android.content.BroadcastReceiver;
26import android.content.Context;
27import android.content.DialogInterface;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
31import android.net.ConnectivityManager;
32import android.net.NetworkInfo;
33import android.net.NetworkInfo.DetailedState;
34import android.net.wifi.ScanResult;
35import android.net.wifi.SupplicantState;
36import android.net.wifi.WifiConfiguration;
37import android.net.wifi.WifiConfiguration.KeyMgmt;
38import android.net.wifi.WifiInfo;
39import android.net.wifi.WifiManager;
40import android.net.wifi.WpsInfo;
41import android.os.Bundle;
42import android.os.Handler;
43import android.os.Message;
44import android.preference.Preference;
45import android.preference.PreferenceActivity;
46import android.preference.PreferenceScreen;
47import android.security.Credentials;
48import android.security.KeyStore;
49import android.util.Log;
50import android.view.ContextMenu;
51import android.view.ContextMenu.ContextMenuInfo;
52import android.view.Gravity;
53import android.view.Menu;
54import android.view.MenuInflater;
55import android.view.MenuItem;
56import android.view.View;
57import android.widget.AdapterView.AdapterContextMenuInfo;
58import android.widget.Switch;
59import android.widget.TextView;
60import android.widget.Toast;
61
62import com.android.settings.R;
63import com.android.settings.SettingsPreferenceFragment;
64import com.android.settings.wifi.p2p.WifiP2pSettings;
65
66import java.util.ArrayList;
67import java.util.Collection;
68import java.util.Collections;
69import java.util.HashMap;
70import java.util.List;
71import java.util.concurrent.atomic.AtomicBoolean;
72
73/**
74 * Two types of UI are provided here.
75 *
76 * The first is for "usual Settings", appearing as any other Setup fragment.
77 *
78 * The second is for Setup Wizard, with a simplified interface that hides the action bar
79 * and menus.
80 */
81public class WifiSettings extends SettingsPreferenceFragment
82        implements DialogInterface.OnClickListener  {
83    private static final String TAG = "WifiSettings";
84    private static final int MENU_ID_WPS_PBC = Menu.FIRST;
85    private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1;
86    private static final int MENU_ID_P2P = Menu.FIRST + 2;
87    private static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3;
88    private static final int MENU_ID_ADVANCED = Menu.FIRST + 4;
89    private static final int MENU_ID_SCAN = Menu.FIRST + 5;
90    private static final int MENU_ID_CONNECT = Menu.FIRST + 6;
91    private static final int MENU_ID_FORGET = Menu.FIRST + 7;
92    private static final int MENU_ID_MODIFY = Menu.FIRST + 8;
93
94    private static final int WIFI_DIALOG_ID = 1;
95    private static final int WPS_PBC_DIALOG_ID = 2;
96    private static final int WPS_PIN_DIALOG_ID = 3;
97
98    // Combo scans can take 5-6s to complete - set to 10s.
99    private static final int WIFI_RESCAN_INTERVAL_MS = 10 * 1000;
100
101    // Instance state keys
102    private static final String SAVE_DIALOG_EDIT_MODE = "edit_mode";
103    private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state";
104
105    private final IntentFilter mFilter;
106    private final BroadcastReceiver mReceiver;
107    private final Scanner mScanner;
108
109    private WifiManager mWifiManager;
110    private WifiManager.Channel mChannel;
111    private WifiManager.ActionListener mConnectListener;
112    private WifiManager.ActionListener mSaveListener;
113    private WifiManager.ActionListener mForgetListener;
114    private boolean mP2pSupported;
115
116
117    private WifiEnabler mWifiEnabler;
118    // An access point being editted is stored here.
119    private AccessPoint mSelectedAccessPoint;
120
121    private DetailedState mLastState;
122    private WifiInfo mLastInfo;
123
124    private AtomicBoolean mConnected = new AtomicBoolean(false);
125
126    private int mKeyStoreNetworkId = INVALID_NETWORK_ID;
127
128    private WifiDialog mDialog;
129
130    private TextView mEmptyView;
131
132    /* Used in Wifi Setup context */
133
134    // this boolean extra specifies whether to disable the Next button when not connected
135    private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
136
137    // this boolean extra specifies whether to auto finish when connection is established
138    private static final String EXTRA_AUTO_FINISH_ON_CONNECT = "wifi_auto_finish_on_connect";
139
140    // this boolean extra is set if we are being invoked by the Setup Wizard
141    private static final String EXTRA_IS_FIRST_RUN = "firstRun";
142
143    private static final String EXTRA_WIFI_DISABLE_BACK = "wifi_disable_back";
144
145    // should Next button only be enabled when we have a connection?
146    private boolean mEnableNextOnConnection;
147
148    // should activity finish once we have a connection?
149    private boolean mAutoFinishOnConnection;
150
151    // Save the dialog details
152    private boolean mDlgEdit;
153    private AccessPoint mDlgAccessPoint;
154    private Bundle mAccessPointSavedState;
155
156    // the action bar uses a different set of controls for Setup Wizard
157    private boolean mSetupWizardMode;
158
159    /* End of "used in Wifi Setup context" */
160
161    public WifiSettings() {
162        mFilter = new IntentFilter();
163        mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
164        mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
165        mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
166        mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
167        mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
168        mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
169        mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
170        mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
171
172        mReceiver = new BroadcastReceiver() {
173            @Override
174            public void onReceive(Context context, Intent intent) {
175                handleEvent(context, intent);
176            }
177        };
178
179        mScanner = new Scanner();
180    }
181
182    @Override
183    public void onCreate(Bundle icicle) {
184        // Set this flag early, as it's needed by getHelpResource(), which is called by super
185        mSetupWizardMode = getActivity().getIntent().getBooleanExtra(EXTRA_IS_FIRST_RUN, false);
186
187        super.onCreate(icicle);
188    }
189
190    @Override
191    public void onActivityCreated(Bundle savedInstanceState) {
192        // We don't call super.onActivityCreated() here, since it assumes we already set up
193        // Preference (probably in onCreate()), while WifiSettings exceptionally set it up in
194        // this method.
195
196        mP2pSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT);
197        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
198        mChannel = mWifiManager.initialize(getActivity(), getActivity().getMainLooper(), null);
199
200        mConnectListener = new WifiManager.ActionListener() {
201                                   public void onSuccess() {
202                                   }
203                                   public void onFailure(int reason) {
204                                        Toast.makeText(getActivity(),
205                                            R.string.wifi_failed_connect_message,
206                                            Toast.LENGTH_SHORT).show();
207                                   }
208                               };
209
210        mSaveListener = new WifiManager.ActionListener() {
211                                public void onSuccess() {
212                                }
213                                public void onFailure(int reason) {
214                                    Toast.makeText(getActivity(),
215                                        R.string.wifi_failed_save_message,
216                                        Toast.LENGTH_SHORT).show();
217                                }
218                            };
219
220        mForgetListener = new WifiManager.ActionListener() {
221                                   public void onSuccess() {
222                                   }
223                                   public void onFailure(int reason) {
224                                        Toast.makeText(getActivity(),
225                                            R.string.wifi_failed_forget_message,
226                                            Toast.LENGTH_SHORT).show();
227                                   }
228                               };
229
230        if (savedInstanceState != null
231                && savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) {
232            mDlgEdit = savedInstanceState.getBoolean(SAVE_DIALOG_EDIT_MODE);
233            mAccessPointSavedState = savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
234        }
235
236        final Activity activity = getActivity();
237        final Intent intent = activity.getIntent();
238
239        // first if we're supposed to finish once we have a connection
240        mAutoFinishOnConnection = intent.getBooleanExtra(EXTRA_AUTO_FINISH_ON_CONNECT, false);
241
242        if (mAutoFinishOnConnection) {
243            // Hide the next button
244            if (hasNextButton()) {
245                getNextButton().setVisibility(View.GONE);
246            }
247
248            final ConnectivityManager connectivity = (ConnectivityManager)
249                    getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
250            if (connectivity != null
251                    && connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
252                activity.finish();
253                return;
254            }
255        }
256
257        // if we're supposed to enable/disable the Next button based on our current connection
258        // state, start it off in the right state
259        mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
260
261        if (mEnableNextOnConnection) {
262            if (hasNextButton()) {
263                final ConnectivityManager connectivity = (ConnectivityManager)
264                        getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
265                if (connectivity != null) {
266                    NetworkInfo info = connectivity.getNetworkInfo(
267                            ConnectivityManager.TYPE_WIFI);
268                    changeNextButtonState(info.isConnected());
269                }
270            }
271        }
272
273        addPreferencesFromResource(R.xml.wifi_settings);
274
275        // Back key is disabled if requested
276        if (intent.getBooleanExtra(EXTRA_WIFI_DISABLE_BACK, false)) {
277            getView().setSystemUiVisibility(View.STATUS_BAR_DISABLE_BACK);
278        }
279
280        // On/off switch is hidden for Setup Wizard
281        if (!mSetupWizardMode) {
282            Switch actionBarSwitch = new Switch(activity);
283
284            if (activity instanceof PreferenceActivity) {
285                PreferenceActivity preferenceActivity = (PreferenceActivity) activity;
286                if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) {
287                    final int padding = activity.getResources().getDimensionPixelSize(
288                            R.dimen.action_bar_switch_padding);
289                    actionBarSwitch.setPadding(0, 0, padding, 0);
290                    activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
291                            ActionBar.DISPLAY_SHOW_CUSTOM);
292                    activity.getActionBar().setCustomView(actionBarSwitch, new ActionBar.LayoutParams(
293                            ActionBar.LayoutParams.WRAP_CONTENT,
294                            ActionBar.LayoutParams.WRAP_CONTENT,
295                            Gravity.CENTER_VERTICAL | Gravity.RIGHT));
296                }
297            }
298
299            mWifiEnabler = new WifiEnabler(activity, actionBarSwitch);
300        }
301
302        mEmptyView = (TextView) getView().findViewById(android.R.id.empty);
303        getListView().setEmptyView(mEmptyView);
304
305        if (!mSetupWizardMode) {
306            registerForContextMenu(getListView());
307        }
308        setHasOptionsMenu(true);
309
310        // After confirming PreferenceScreen is available, we call super.
311        super.onActivityCreated(savedInstanceState);
312    }
313
314    @Override
315    public void onResume() {
316        super.onResume();
317        if (mWifiEnabler != null) {
318            mWifiEnabler.resume();
319        }
320
321        getActivity().registerReceiver(mReceiver, mFilter);
322        if (mKeyStoreNetworkId != INVALID_NETWORK_ID &&
323                KeyStore.getInstance().state() == KeyStore.State.UNLOCKED) {
324            mWifiManager.connect(mChannel, mKeyStoreNetworkId, mConnectListener);
325        }
326        mKeyStoreNetworkId = INVALID_NETWORK_ID;
327
328        updateAccessPoints();
329    }
330
331    @Override
332    public void onPause() {
333        super.onPause();
334        if (mWifiEnabler != null) {
335            mWifiEnabler.pause();
336        }
337        getActivity().unregisterReceiver(mReceiver);
338        mScanner.pause();
339    }
340
341    @Override
342    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
343        final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
344        if (mSetupWizardMode) {
345            // FIXME: add setIcon() when graphics are available
346            menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc)
347                    .setEnabled(wifiIsEnabled)
348                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
349            menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
350                    .setEnabled(wifiIsEnabled)
351                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
352        } else {
353            menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc)
354                    .setEnabled(wifiIsEnabled)
355                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
356            menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
357                    .setEnabled(wifiIsEnabled)
358                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
359            menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan)
360                    //.setIcon(R.drawable.ic_menu_scan_network)
361                    .setEnabled(wifiIsEnabled)
362                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
363            menu.add(Menu.NONE, MENU_ID_WPS_PIN, 0, R.string.wifi_menu_wps_pin)
364                    .setEnabled(wifiIsEnabled)
365                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
366            if (mP2pSupported) {
367                menu.add(Menu.NONE, MENU_ID_P2P, 0, R.string.wifi_menu_p2p)
368                        .setEnabled(wifiIsEnabled)
369                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
370            }
371            menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced)
372                    //.setIcon(android.R.drawable.ic_menu_manage)
373                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
374        }
375        super.onCreateOptionsMenu(menu, inflater);
376    }
377
378    @Override
379    public void onSaveInstanceState(Bundle outState) {
380        super.onSaveInstanceState(outState);
381
382        // If the dialog is showing, save its state.
383        if (mDialog != null && mDialog.isShowing()) {
384            outState.putBoolean(SAVE_DIALOG_EDIT_MODE, mDlgEdit);
385            if (mDlgAccessPoint != null) {
386                mAccessPointSavedState = new Bundle();
387                mDlgAccessPoint.saveWifiState(mAccessPointSavedState);
388                outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState);
389            }
390        }
391    }
392
393    @Override
394    public boolean onOptionsItemSelected(MenuItem item) {
395        switch (item.getItemId()) {
396            case MENU_ID_WPS_PBC:
397                showDialog(WPS_PBC_DIALOG_ID);
398                return true;
399            case MENU_ID_P2P:
400                if (getActivity() instanceof PreferenceActivity) {
401                    ((PreferenceActivity) getActivity()).startPreferencePanel(
402                            WifiP2pSettings.class.getCanonicalName(),
403                            null,
404                            R.string.wifi_p2p_settings_title, null,
405                            this, 0);
406                } else {
407                    startFragment(this, WifiP2pSettings.class.getCanonicalName(), -1, null);
408                }
409                return true;
410            case MENU_ID_WPS_PIN:
411                showDialog(WPS_PIN_DIALOG_ID);
412                return true;
413            case MENU_ID_SCAN:
414                if (mWifiManager.isWifiEnabled()) {
415                    mScanner.forceScan();
416                }
417                return true;
418            case MENU_ID_ADD_NETWORK:
419                if (mWifiManager.isWifiEnabled()) {
420                    onAddNetworkPressed();
421                }
422                return true;
423            case MENU_ID_ADVANCED:
424                if (getActivity() instanceof PreferenceActivity) {
425                    ((PreferenceActivity) getActivity()).startPreferencePanel(
426                            AdvancedWifiSettings.class.getCanonicalName(),
427                            null,
428                            R.string.wifi_advanced_titlebar, null,
429                            this, 0);
430                } else {
431                    startFragment(this, AdvancedWifiSettings.class.getCanonicalName(), -1, null);
432                }
433                return true;
434        }
435        return super.onOptionsItemSelected(item);
436    }
437
438    @Override
439    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
440        if (info instanceof AdapterContextMenuInfo) {
441            Preference preference = (Preference) getListView().getItemAtPosition(
442                    ((AdapterContextMenuInfo) info).position);
443
444            if (preference instanceof AccessPoint) {
445                mSelectedAccessPoint = (AccessPoint) preference;
446                menu.setHeaderTitle(mSelectedAccessPoint.ssid);
447                if (mSelectedAccessPoint.getLevel() != -1
448                        && mSelectedAccessPoint.getState() == null) {
449                    menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect);
450                }
451                if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
452                    menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget);
453                    menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify);
454                }
455            }
456        }
457    }
458
459    @Override
460    public boolean onContextItemSelected(MenuItem item) {
461        if (mSelectedAccessPoint == null) {
462            return super.onContextItemSelected(item);
463        }
464        switch (item.getItemId()) {
465            case MENU_ID_CONNECT: {
466                if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
467                    if (!requireKeyStore(mSelectedAccessPoint.getConfig())) {
468                        mWifiManager.connect(mChannel, mSelectedAccessPoint.networkId,
469                                mConnectListener);
470                    }
471                } else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) {
472                    /** Bypass dialog for unsecured networks */
473                    mSelectedAccessPoint.generateOpenNetworkConfig();
474                    mWifiManager.connect(mChannel, mSelectedAccessPoint.getConfig(),
475                            mConnectListener);
476                } else {
477                    showDialog(mSelectedAccessPoint, true);
478                }
479                return true;
480            }
481            case MENU_ID_FORGET: {
482                mWifiManager.forget(mChannel, mSelectedAccessPoint.networkId, mForgetListener);
483                return true;
484            }
485            case MENU_ID_MODIFY: {
486                showDialog(mSelectedAccessPoint, true);
487                return true;
488            }
489        }
490        return super.onContextItemSelected(item);
491    }
492
493    @Override
494    public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
495        if (preference instanceof AccessPoint) {
496            mSelectedAccessPoint = (AccessPoint) preference;
497            /** Bypass dialog for unsecured, unsaved networks */
498            if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE &&
499                    mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) {
500                mSelectedAccessPoint.generateOpenNetworkConfig();
501                mWifiManager.connect(mChannel, mSelectedAccessPoint.getConfig(), mConnectListener);
502            } else {
503                showDialog(mSelectedAccessPoint, false);
504            }
505        } else {
506            return super.onPreferenceTreeClick(screen, preference);
507        }
508        return true;
509    }
510
511    private void showDialog(AccessPoint accessPoint, boolean edit) {
512        if (mDialog != null) {
513            removeDialog(WIFI_DIALOG_ID);
514            mDialog = null;
515        }
516
517        // Save the access point and edit mode
518        mDlgAccessPoint = accessPoint;
519        mDlgEdit = edit;
520
521        showDialog(WIFI_DIALOG_ID);
522    }
523
524    @Override
525    public Dialog onCreateDialog(int dialogId) {
526        switch (dialogId) {
527            case WIFI_DIALOG_ID:
528                AccessPoint ap = mDlgAccessPoint; // For manual launch
529                if (ap == null) { // For re-launch from saved state
530                    if (mAccessPointSavedState != null) {
531                        ap = new AccessPoint(getActivity(), mAccessPointSavedState);
532                        // For repeated orientation changes
533                        mDlgAccessPoint = ap;
534                    }
535                }
536                // If it's still null, fine, it's for Add Network
537                mSelectedAccessPoint = ap;
538                mDialog = new WifiDialog(getActivity(), this, ap, mDlgEdit);
539                return mDialog;
540            case WPS_PBC_DIALOG_ID:
541                return new WpsDialog(getActivity(), WpsInfo.PBC);
542            case WPS_PIN_DIALOG_ID:
543                return new WpsDialog(getActivity(), WpsInfo.DISPLAY);
544        }
545        return super.onCreateDialog(dialogId);
546    }
547
548    private boolean requireKeyStore(WifiConfiguration config) {
549        if (WifiConfigController.requireKeyStore(config) &&
550                KeyStore.getInstance().state() != KeyStore.State.UNLOCKED) {
551            mKeyStoreNetworkId = config.networkId;
552            Credentials.getInstance().unlock(getActivity());
553            return true;
554        }
555        return false;
556    }
557
558    /**
559     * Shows the latest access points available with supplimental information like
560     * the strength of network and the security for it.
561     */
562    private void updateAccessPoints() {
563        // Safeguard from some delayed event handling
564        if (getActivity() == null) return;
565
566        final int wifiState = mWifiManager.getWifiState();
567
568        switch (wifiState) {
569            case WifiManager.WIFI_STATE_ENABLED:
570                // AccessPoints are automatically sorted with TreeSet.
571                final Collection<AccessPoint> accessPoints = constructAccessPoints();
572                getPreferenceScreen().removeAll();
573                if(accessPoints.size() == 0) {
574                    addMessagePreference(R.string.wifi_empty_list_wifi_on);
575                }
576                for (AccessPoint accessPoint : accessPoints) {
577                    getPreferenceScreen().addPreference(accessPoint);
578                }
579                break;
580
581            case WifiManager.WIFI_STATE_ENABLING:
582                getPreferenceScreen().removeAll();
583                break;
584
585            case WifiManager.WIFI_STATE_DISABLING:
586                addMessagePreference(R.string.wifi_stopping);
587                break;
588
589            case WifiManager.WIFI_STATE_DISABLED:
590                addMessagePreference(R.string.wifi_empty_list_wifi_off);
591                break;
592        }
593    }
594
595    private void addMessagePreference(int messageId) {
596        if (mEmptyView != null) mEmptyView.setText(messageId);
597        getPreferenceScreen().removeAll();
598    }
599
600    /** Returns sorted list of access points */
601    private List<AccessPoint> constructAccessPoints() {
602        ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>();
603        /** Lookup table to more quickly update AccessPoints by only considering objects with the
604         * correct SSID.  Maps SSID -> List of AccessPoints with the given SSID.  */
605        Multimap<String, AccessPoint> apMap = new Multimap<String, AccessPoint>();
606
607        final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
608        if (configs != null) {
609            for (WifiConfiguration config : configs) {
610                AccessPoint accessPoint = new AccessPoint(getActivity(), config);
611                accessPoint.update(mLastInfo, mLastState);
612                accessPoints.add(accessPoint);
613                apMap.put(accessPoint.ssid, accessPoint);
614            }
615        }
616
617        final List<ScanResult> results = mWifiManager.getScanResults();
618        if (results != null) {
619            for (ScanResult result : results) {
620                // Ignore hidden and ad-hoc networks.
621                if (result.SSID == null || result.SSID.length() == 0 ||
622                        result.capabilities.contains("[IBSS]")) {
623                    continue;
624                }
625
626                boolean found = false;
627                for (AccessPoint accessPoint : apMap.getAll(result.SSID)) {
628                    if (accessPoint.update(result))
629                        found = true;
630                }
631                if (!found) {
632                    AccessPoint accessPoint = new AccessPoint(getActivity(), result);
633                    accessPoints.add(accessPoint);
634                    apMap.put(accessPoint.ssid, accessPoint);
635                }
636            }
637        }
638
639        // Pre-sort accessPoints to speed preference insertion
640        Collections.sort(accessPoints);
641        return accessPoints;
642    }
643
644    /** A restricted multimap for use in constructAccessPoints */
645    private class Multimap<K,V> {
646        private HashMap<K,List<V>> store = new HashMap<K,List<V>>();
647        /** retrieve a non-null list of values with key K */
648        List<V> getAll(K key) {
649            List<V> values = store.get(key);
650            return values != null ? values : Collections.<V>emptyList();
651        }
652
653        void put(K key, V val) {
654            List<V> curVals = store.get(key);
655            if (curVals == null) {
656                curVals = new ArrayList<V>(3);
657                store.put(key, curVals);
658            }
659            curVals.add(val);
660        }
661    }
662
663    private void handleEvent(Context context, Intent intent) {
664        String action = intent.getAction();
665        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
666            updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
667                    WifiManager.WIFI_STATE_UNKNOWN));
668        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) ||
669                WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) ||
670                WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) {
671                updateAccessPoints();
672        } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
673            //Ignore supplicant state changes when network is connected
674            //TODO: we should deprecate SUPPLICANT_STATE_CHANGED_ACTION and
675            //introduce a broadcast that combines the supplicant and network
676            //network state change events so the apps dont have to worry about
677            //ignoring supplicant state change when network is connected
678            //to get more fine grained information.
679            SupplicantState state = (SupplicantState) intent.getParcelableExtra(
680                    WifiManager.EXTRA_NEW_STATE);
681            if (!mConnected.get() && SupplicantState.isHandshakeState(state)) {
682                updateConnectionState(WifiInfo.getDetailedStateOf(state));
683            }
684        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
685            NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
686                    WifiManager.EXTRA_NETWORK_INFO);
687            mConnected.set(info.isConnected());
688            changeNextButtonState(info.isConnected());
689            updateAccessPoints();
690            updateConnectionState(info.getDetailedState());
691            if (mAutoFinishOnConnection && info.isConnected()) {
692                getActivity().finish();
693                return;
694            }
695        } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
696            updateConnectionState(null);
697        }
698    }
699
700    private void updateConnectionState(DetailedState state) {
701        /* sticky broadcasts can call this when wifi is disabled */
702        if (!mWifiManager.isWifiEnabled()) {
703            mScanner.pause();
704            return;
705        }
706
707        if (state == DetailedState.OBTAINING_IPADDR) {
708            mScanner.pause();
709        } else {
710            mScanner.resume();
711        }
712
713        mLastInfo = mWifiManager.getConnectionInfo();
714        if (state != null) {
715            mLastState = state;
716        }
717
718        for (int i = getPreferenceScreen().getPreferenceCount() - 1; i >= 0; --i) {
719            // Maybe there's a WifiConfigPreference
720            Preference preference = getPreferenceScreen().getPreference(i);
721            if (preference instanceof AccessPoint) {
722                final AccessPoint accessPoint = (AccessPoint) preference;
723                accessPoint.update(mLastInfo, mLastState);
724            }
725        }
726    }
727
728    private void updateWifiState(int state) {
729        getActivity().invalidateOptionsMenu();
730
731        switch (state) {
732            case WifiManager.WIFI_STATE_ENABLED:
733                mScanner.resume();
734                return; // not break, to avoid the call to pause() below
735
736            case WifiManager.WIFI_STATE_ENABLING:
737                addMessagePreference(R.string.wifi_starting);
738                break;
739
740            case WifiManager.WIFI_STATE_DISABLED:
741                addMessagePreference(R.string.wifi_empty_list_wifi_off);
742                break;
743        }
744
745        mLastInfo = null;
746        mLastState = null;
747        mScanner.pause();
748    }
749
750    private class Scanner extends Handler {
751        private int mRetry = 0;
752
753        void resume() {
754            if (!hasMessages(0)) {
755                sendEmptyMessage(0);
756            }
757        }
758
759        void forceScan() {
760            removeMessages(0);
761            sendEmptyMessage(0);
762        }
763
764        void pause() {
765            mRetry = 0;
766            removeMessages(0);
767        }
768
769        @Override
770        public void handleMessage(Message message) {
771            if (mWifiManager.startScanActive()) {
772                mRetry = 0;
773            } else if (++mRetry >= 3) {
774                mRetry = 0;
775                Toast.makeText(getActivity(), R.string.wifi_fail_to_scan,
776                        Toast.LENGTH_LONG).show();
777                return;
778            }
779            sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS);
780        }
781    }
782
783    /**
784     * Renames/replaces "Next" button when appropriate. "Next" button usually exists in
785     * Wifi setup screens, not in usual wifi settings screen.
786     *
787     * @param connected true when the device is connected to a wifi network.
788     */
789    private void changeNextButtonState(boolean connected) {
790        if (mEnableNextOnConnection && hasNextButton()) {
791            getNextButton().setEnabled(connected);
792        }
793    }
794
795    public void onClick(DialogInterface dialogInterface, int button) {
796        if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
797            forget();
798        } else if (button == WifiDialog.BUTTON_SUBMIT) {
799            submit(mDialog.getController());
800        }
801    }
802
803    /* package */ void submit(WifiConfigController configController) {
804
805        final WifiConfiguration config = configController.getConfig();
806
807        if (config == null) {
808            if (mSelectedAccessPoint != null
809                    && !requireKeyStore(mSelectedAccessPoint.getConfig())
810                    && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
811                mWifiManager.connect(mChannel, mSelectedAccessPoint.networkId,
812                        mConnectListener);
813            }
814        } else if (config.networkId != INVALID_NETWORK_ID) {
815            if (mSelectedAccessPoint != null) {
816                mWifiManager.save(mChannel, config, mSaveListener);
817            }
818        } else {
819            if (configController.isEdit() || requireKeyStore(config)) {
820                mWifiManager.save(mChannel, config, mSaveListener);
821            } else {
822                mWifiManager.connect(mChannel, config, mConnectListener);
823            }
824        }
825
826        if (mWifiManager.isWifiEnabled()) {
827            mScanner.resume();
828        }
829        updateAccessPoints();
830    }
831
832    /* package */ void forget() {
833        if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) {
834            // Should not happen, but a monkey seems to triger it
835            Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig());
836            return;
837        }
838
839        mWifiManager.forget(mChannel, mSelectedAccessPoint.networkId, mForgetListener);
840
841        if (mWifiManager.isWifiEnabled()) {
842            mScanner.resume();
843        }
844        updateAccessPoints();
845
846        // We need to rename/replace "Next" button in wifi setup context.
847        changeNextButtonState(false);
848    }
849
850    /**
851     * Refreshes acccess points and ask Wifi module to scan networks again.
852     */
853    /* package */ void refreshAccessPoints() {
854        if (mWifiManager.isWifiEnabled()) {
855            mScanner.resume();
856        }
857
858        getPreferenceScreen().removeAll();
859    }
860
861    /**
862     * Called when "add network" button is pressed.
863     */
864    /* package */ void onAddNetworkPressed() {
865        // No exact access point is selected.
866        mSelectedAccessPoint = null;
867        showDialog(null, true);
868    }
869
870    /* package */ int getAccessPointsCount() {
871        final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
872        if (wifiIsEnabled) {
873            return getPreferenceScreen().getPreferenceCount();
874        } else {
875            return 0;
876        }
877    }
878
879    /**
880     * Requests wifi module to pause wifi scan. May be ignored when the module is disabled.
881     */
882    /* package */ void pauseWifiScan() {
883        if (mWifiManager.isWifiEnabled()) {
884            mScanner.pause();
885        }
886    }
887
888    /**
889     * Requests wifi module to resume wifi scan. May be ignored when the module is disabled.
890     */
891    /* package */ void resumeWifiScan() {
892        if (mWifiManager.isWifiEnabled()) {
893            mScanner.resume();
894        }
895    }
896
897    @Override
898    protected int getHelpResource() {
899        if (mSetupWizardMode) {
900            return 0;
901        }
902        return R.string.help_url_wifi;
903    }
904}
905