WifiSettings.java revision 568d1560898687de216f38bdc2bd5f933aed3f7d
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settings.wifi;
18
19import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID;
20import static android.os.UserManager.DISALLOW_CONFIG_WIFI;
21
22import android.app.Activity;
23import android.app.Dialog;
24import android.content.BroadcastReceiver;
25import android.content.Context;
26import android.content.DialogInterface;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.res.Resources;
30import android.content.res.TypedArray;
31import android.location.LocationManager;
32import android.net.ConnectivityManager;
33import android.net.NetworkInfo;
34import android.net.NetworkInfo.DetailedState;
35import android.net.NetworkInfo.State;
36import android.net.wifi.ScanResult;
37import android.net.wifi.WifiConfiguration;
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.os.UserHandle;
45import android.preference.Preference;
46import android.preference.PreferenceScreen;
47import android.util.Log;
48import android.view.ContextMenu;
49import android.view.ContextMenu.ContextMenuInfo;
50import android.view.Menu;
51import android.view.MenuInflater;
52import android.view.MenuItem;
53import android.view.View;
54import android.widget.AdapterView.AdapterContextMenuInfo;
55import android.widget.TextView;
56import android.widget.Toast;
57
58import com.android.settings.R;
59import com.android.settings.RestrictedSettingsFragment;
60import com.android.settings.SettingsActivity;
61import com.android.settings.search.BaseSearchIndexProvider;
62import com.android.settings.search.Indexable;
63import com.android.settings.search.SearchIndexableRaw;
64
65import java.util.ArrayList;
66import java.util.Collection;
67import java.util.Collections;
68import java.util.HashMap;
69import java.util.List;
70import java.util.concurrent.atomic.AtomicBoolean;
71
72/**
73 * Two types of UI are provided here.
74 *
75 * The first is for "usual Settings", appearing as any other Setup fragment.
76 *
77 * The second is for Setup Wizard, with a simplified interface that hides the action bar
78 * and menus.
79 */
80public class WifiSettings extends RestrictedSettingsFragment
81        implements DialogInterface.OnClickListener, Indexable  {
82
83    private static final String TAG = "WifiSettings";
84
85    /* package */ static final int MENU_ID_WPS_PBC = Menu.FIRST;
86    private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1;
87    private static final int MENU_ID_SAVED_NETWORK = Menu.FIRST + 2;
88    /* package */ static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3;
89    private static final int MENU_ID_ADVANCED = Menu.FIRST + 4;
90    private static final int MENU_ID_SCAN = Menu.FIRST + 5;
91    private static final int MENU_ID_CONNECT = Menu.FIRST + 6;
92    private static final int MENU_ID_FORGET = Menu.FIRST + 7;
93    private static final int MENU_ID_MODIFY = Menu.FIRST + 8;
94    private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9;
95    private static final int MENU_ID_APPS = Menu.FIRST + 10;
96
97    public static final int WIFI_DIALOG_ID = 1;
98    /* package */ static final int WPS_PBC_DIALOG_ID = 2;
99    private static final int WPS_PIN_DIALOG_ID = 3;
100    private static final int WRITE_NFC_DIALOG_ID = 6;
101
102    // Combo scans can take 5-6s to complete - set to 10s.
103    private static final int WIFI_RESCAN_INTERVAL_MS = 10 * 1000;
104
105    // Instance state keys
106    private static final String SAVE_DIALOG_EDIT_MODE = "edit_mode";
107    private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state";
108
109    private static boolean savedNetworksExist;
110
111    private final IntentFilter mFilter;
112    private final BroadcastReceiver mReceiver;
113    private final Scanner mScanner;
114
115    /* package */ WifiManager mWifiManager;
116    private WifiManager.ActionListener mConnectListener;
117    private WifiManager.ActionListener mSaveListener;
118    private WifiManager.ActionListener mForgetListener;
119
120    private WifiEnabler mWifiEnabler;
121    // An access point being editted is stored here.
122    private AccessPoint mSelectedAccessPoint;
123
124    private NetworkInfo mLastNetworkInfo;
125    private WifiInfo mLastInfo;
126
127    private final AtomicBoolean mConnected = new AtomicBoolean(false);
128
129    private WifiDialog mDialog;
130    private WriteWifiConfigToNfcDialog mWifiToNfcDialog;
131
132    private TextView mEmptyView;
133
134    private boolean showAppIcons = false;
135    private MenuItem showAppMenuItem = null;
136
137    // this boolean extra specifies whether to disable the Next button when not connected. Used by
138    // account creation outside of setup wizard.
139    private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
140    // This string extra specifies a network to open the connect dialog on, so the user can enter
141    // network credentials.  This is used by quick settings for secured networks.
142    private static final String EXTRA_START_CONNECT_SSID = "wifi_start_connect_ssid";
143
144    // should Next button only be enabled when we have a connection?
145    private boolean mEnableNextOnConnection;
146
147    // Save the dialog details
148    private boolean mDlgEdit;
149    private AccessPoint mDlgAccessPoint;
150    private Bundle mAccessPointSavedState;
151
152    /** verbose logging flag. this flag is set thru developer debugging options
153     * and used so as to assist with in-the-field WiFi connectivity debugging  */
154    public static int mVerboseLogging = 0;
155
156    /* End of "used in Wifi Setup context" */
157
158    /** A restricted multimap for use in constructAccessPoints */
159    private static class Multimap<K,V> {
160        private final HashMap<K,List<V>> store = new HashMap<K,List<V>>();
161        /** retrieve a non-null list of values with key K */
162        List<V> getAll(K key) {
163            List<V> values = store.get(key);
164            return values != null ? values : Collections.<V>emptyList();
165        }
166
167        void put(K key, V val) {
168            List<V> curVals = store.get(key);
169            if (curVals == null) {
170                curVals = new ArrayList<V>(3);
171                store.put(key, curVals);
172            }
173            curVals.add(val);
174        }
175    }
176
177    private static class Scanner extends Handler {
178        private int mRetry = 0;
179        private WifiSettings mWifiSettings = null;
180
181        Scanner(WifiSettings wifiSettings) {
182            mWifiSettings = wifiSettings;
183        }
184
185        void resume() {
186            if (!hasMessages(0)) {
187                sendEmptyMessage(0);
188            }
189        }
190
191        void forceScan() {
192            removeMessages(0);
193            sendEmptyMessage(0);
194        }
195
196        void pause() {
197            mRetry = 0;
198            removeMessages(0);
199        }
200
201        @Override
202        public void handleMessage(Message message) {
203            if (mWifiSettings.mWifiManager.startScan()) {
204                mRetry = 0;
205            } else if (++mRetry >= 3) {
206                mRetry = 0;
207                Activity activity = mWifiSettings.getActivity();
208                if (activity != null) {
209                    Toast.makeText(activity, R.string.wifi_fail_to_scan, Toast.LENGTH_LONG).show();
210                }
211                return;
212            }
213            sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS);
214        }
215    }
216
217    public WifiSettings() {
218        super(DISALLOW_CONFIG_WIFI);
219        mFilter = new IntentFilter();
220        mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
221        mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
222        mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
223        mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
224        mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
225        mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
226        mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
227        mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
228
229        mReceiver = new BroadcastReceiver() {
230            @Override
231            public void onReceive(Context context, Intent intent) {
232                handleEvent(intent);
233            }
234        };
235
236        mScanner = new Scanner(this);
237    }
238
239    @Override
240    public void onActivityCreated(Bundle savedInstanceState) {
241        super.onActivityCreated(savedInstanceState);
242
243        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
244
245        mConnectListener = new WifiManager.ActionListener() {
246                                   @Override
247                                   public void onSuccess() {
248                                   }
249                                   @Override
250                                   public void onFailure(int reason) {
251                                       Activity activity = getActivity();
252                                       if (activity != null) {
253                                           Toast.makeText(activity,
254                                                R.string.wifi_failed_connect_message,
255                                                Toast.LENGTH_SHORT).show();
256                                       }
257                                   }
258                               };
259
260        mSaveListener = new WifiManager.ActionListener() {
261                                @Override
262                                public void onSuccess() {
263                                }
264                                @Override
265                                public void onFailure(int reason) {
266                                    Activity activity = getActivity();
267                                    if (activity != null) {
268                                        Toast.makeText(activity,
269                                            R.string.wifi_failed_save_message,
270                                            Toast.LENGTH_SHORT).show();
271                                    }
272                                }
273                            };
274
275        mForgetListener = new WifiManager.ActionListener() {
276                                   @Override
277                                   public void onSuccess() {
278                                   }
279                                   @Override
280                                   public void onFailure(int reason) {
281                                       Activity activity = getActivity();
282                                       if (activity != null) {
283                                           Toast.makeText(activity,
284                                               R.string.wifi_failed_forget_message,
285                                               Toast.LENGTH_SHORT).show();
286                                       }
287                                   }
288                               };
289
290        if (savedInstanceState != null) {
291            mDlgEdit = savedInstanceState.getBoolean(SAVE_DIALOG_EDIT_MODE);
292            if (savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) {
293                mAccessPointSavedState =
294                    savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
295            }
296        }
297
298        // if we're supposed to enable/disable the Next button based on our current connection
299        // state, start it off in the right state
300        Intent intent = getActivity().getIntent();
301        mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
302
303        if (mEnableNextOnConnection) {
304            if (hasNextButton()) {
305                final ConnectivityManager connectivity = (ConnectivityManager)
306                        getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
307                if (connectivity != null) {
308                    NetworkInfo info = connectivity.getNetworkInfo(
309                            ConnectivityManager.TYPE_WIFI);
310                    changeNextButtonState(info.isConnected());
311                }
312            }
313        }
314
315        addPreferencesFromResource(R.xml.wifi_settings);
316
317        mEmptyView = initEmptyView();
318        registerForContextMenu(getListView());
319        setHasOptionsMenu(true);
320
321        if (intent.hasExtra(EXTRA_START_CONNECT_SSID)) {
322            String ssid = intent.getStringExtra(EXTRA_START_CONNECT_SSID);
323            updateAccessPoints();
324            PreferenceScreen preferenceScreen = getPreferenceScreen();
325            for (int i = 0; i < preferenceScreen.getPreferenceCount(); i++) {
326                Preference preference = preferenceScreen.getPreference(i);
327                if (preference instanceof AccessPoint) {
328                    AccessPoint accessPoint = (AccessPoint) preference;
329                    if (ssid.equals(accessPoint.ssid) && accessPoint.networkId == -1
330                            && accessPoint.security != AccessPoint.SECURITY_NONE) {
331                        onPreferenceTreeClick(preferenceScreen, preference);
332                        break;
333                    }
334                }
335            }
336        }
337    }
338
339    @Override
340    public void onDestroyView() {
341        super.onDestroyView();
342
343        if (mWifiEnabler != null) {
344            mWifiEnabler.teardownSwitchBar();
345        }
346    }
347
348    @Override
349    public void onStart() {
350        super.onStart();
351
352        // On/off switch is hidden for Setup Wizard (returns null)
353        mWifiEnabler = createWifiEnabler();
354    }
355
356    /**
357     * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard)
358     */
359    /* package */ WifiEnabler createWifiEnabler() {
360        final SettingsActivity activity = (SettingsActivity) getActivity();
361        return new WifiEnabler(activity, activity.getSwitchBar());
362    }
363
364    @Override
365    public void onResume() {
366        final Activity activity = getActivity();
367        super.onResume();
368        if (mWifiEnabler != null) {
369            mWifiEnabler.resume(activity);
370        }
371
372        activity.registerReceiver(mReceiver, mFilter);
373        updateAccessPoints();
374    }
375
376    @Override
377    public void onPause() {
378        super.onPause();
379        if (mWifiEnabler != null) {
380            mWifiEnabler.pause();
381        }
382
383        getActivity().unregisterReceiver(mReceiver);
384        mScanner.pause();
385    }
386
387    @Override
388    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
389        // If the user is not allowed to configure wifi, do not show the menu.
390        if (isUiRestricted()) return;
391
392        addOptionsMenuItems(menu);
393        super.onCreateOptionsMenu(menu, inflater);
394    }
395
396    /**
397     * @param menu
398     */
399    void addOptionsMenuItems(Menu menu) {
400        final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
401        TypedArray ta = getActivity().getTheme().obtainStyledAttributes(
402                new int[] {R.attr.ic_menu_add, R.attr.ic_wps});
403        menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
404                .setIcon(ta.getDrawable(0))
405                .setEnabled(wifiIsEnabled)
406                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
407        if (savedNetworksExist) {
408            menu.add(Menu.NONE, MENU_ID_SAVED_NETWORK, 0, R.string.wifi_saved_access_points_label)
409                    .setIcon(ta.getDrawable(0))
410                    .setEnabled(wifiIsEnabled)
411                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
412        }
413        menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.menu_stats_refresh)
414               .setEnabled(wifiIsEnabled)
415               .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
416        menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced)
417                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
418        showAppMenuItem = menu.add(Menu.NONE, MENU_ID_APPS, 0, R.string.wifi_menu_apps);
419        showAppMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
420        ta.recycle();
421    }
422
423    @Override
424    public void onSaveInstanceState(Bundle outState) {
425        super.onSaveInstanceState(outState);
426
427        // If the dialog is showing, save its state.
428        if (mDialog != null && mDialog.isShowing()) {
429            outState.putBoolean(SAVE_DIALOG_EDIT_MODE, mDlgEdit);
430            if (mDlgAccessPoint != null) {
431                mAccessPointSavedState = new Bundle();
432                mDlgAccessPoint.saveWifiState(mAccessPointSavedState);
433                outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState);
434            }
435        }
436    }
437
438    @Override
439    public boolean onOptionsItemSelected(MenuItem item) {
440        // If the user is not allowed to configure wifi, do not handle menu selections.
441        if (isUiRestricted()) return false;
442
443        switch (item.getItemId()) {
444            case MENU_ID_WPS_PBC:
445                showDialog(WPS_PBC_DIALOG_ID);
446                return true;
447                /*
448            case MENU_ID_P2P:
449                if (getActivity() instanceof SettingsActivity) {
450                    ((SettingsActivity) getActivity()).startPreferencePanel(
451                            WifiP2pSettings.class.getCanonicalName(),
452                            null,
453                            R.string.wifi_p2p_settings_title, null,
454                            this, 0);
455                } else {
456                    startFragment(this, WifiP2pSettings.class.getCanonicalName(),
457                            R.string.wifi_p2p_settings_title, -1, null);
458                }
459                return true;
460                */
461            case MENU_ID_WPS_PIN:
462                showDialog(WPS_PIN_DIALOG_ID);
463                return true;
464            case MENU_ID_SCAN:
465                if (mWifiManager.isWifiEnabled()) {
466                    mScanner.forceScan();
467                }
468                return true;
469            case MENU_ID_ADD_NETWORK:
470                if (mWifiManager.isWifiEnabled()) {
471                    onAddNetworkPressed();
472                }
473                return true;
474            case MENU_ID_SAVED_NETWORK:
475                if (getActivity() instanceof SettingsActivity) {
476                    ((SettingsActivity) getActivity()).startPreferencePanel(
477                            SavedAccessPointsWifiSettings.class.getCanonicalName(), null,
478                            R.string.wifi_saved_access_points_titlebar, null, this, 0);
479                } else {
480                    startFragment(this, SavedAccessPointsWifiSettings.class.getCanonicalName(),
481                            R.string.wifi_saved_access_points_titlebar,
482                            -1 /* Do not request a result */, null);
483                }
484                return true;
485            case MENU_ID_ADVANCED:
486                if (getActivity() instanceof SettingsActivity) {
487                    ((SettingsActivity) getActivity()).startPreferencePanel(
488                            AdvancedWifiSettings.class.getCanonicalName(), null,
489                            R.string.wifi_advanced_titlebar, null, this, 0);
490                } else {
491                    startFragment(this, AdvancedWifiSettings.class.getCanonicalName(),
492                            R.string.wifi_advanced_titlebar, -1 /* Do not request a results */,
493                            null);
494                }
495                return true;
496            case MENU_ID_APPS:
497                showAppIcons = !showAppIcons;
498
499                if (showAppIcons) {
500                    showAppMenuItem.setTitle(R.string.wifi_menu_apps_strength);
501                } else {
502                    showAppMenuItem.setTitle(R.string.wifi_menu_apps);
503                }
504                updateAccessPoints();
505                return true;
506        }
507        return super.onOptionsItemSelected(item);
508    }
509
510    @Override
511    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
512        if (info instanceof AdapterContextMenuInfo) {
513            Preference preference = (Preference) getListView().getItemAtPosition(
514                    ((AdapterContextMenuInfo) info).position);
515
516            if (preference instanceof AccessPoint) {
517                mSelectedAccessPoint = (AccessPoint) preference;
518                menu.setHeaderTitle(mSelectedAccessPoint.ssid);
519                if (mSelectedAccessPoint.getLevel() != -1) {
520                    int connectStringRes = 0;
521                    if (mSelectedAccessPoint.getState() == null) {
522                        connectStringRes = R.string.wifi_menu_connect;
523                    } else if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID &&
524                            mSelectedAccessPoint.getNetworkInfo().getState()
525                                != State.DISCONNECTED) {
526                        // State is non-null (and not disconnected) but this network has no
527                        // configuration, which means it is ephemeral. Allow the user to save the
528                        // configuration permanently (but still issue this as a CONNECT command).
529                        connectStringRes = R.string.wifi_menu_remember;
530                    }
531
532                    if (connectStringRes != 0) {
533                        menu.add(Menu.NONE, MENU_ID_CONNECT, 0, connectStringRes);
534                    }
535                }
536                if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
537                    menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget);
538                    menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify);
539
540                    if (mSelectedAccessPoint.security != AccessPoint.SECURITY_NONE) {
541                        // Only allow writing of NFC tags for password-protected networks.
542                        menu.add(Menu.NONE, MENU_ID_WRITE_NFC, 0, R.string.wifi_menu_write_to_nfc);
543                    }
544                }
545            }
546        }
547    }
548
549    @Override
550    public boolean onContextItemSelected(MenuItem item) {
551        if (mSelectedAccessPoint == null) {
552            return super.onContextItemSelected(item);
553        }
554        switch (item.getItemId()) {
555            case MENU_ID_CONNECT: {
556                if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
557                    connect(mSelectedAccessPoint.networkId);
558                } else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) {
559                    /** Bypass dialog for unsecured networks */
560                    mSelectedAccessPoint.generateOpenNetworkConfig();
561                    connect(mSelectedAccessPoint.getConfig());
562                } else {
563                    showDialog(mSelectedAccessPoint, true);
564                }
565                return true;
566            }
567            case MENU_ID_FORGET: {
568                mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener);
569                return true;
570            }
571            case MENU_ID_MODIFY: {
572                showDialog(mSelectedAccessPoint, true);
573                return true;
574            }
575            case MENU_ID_WRITE_NFC:
576                showDialog(WRITE_NFC_DIALOG_ID);
577                return true;
578
579        }
580        return super.onContextItemSelected(item);
581    }
582
583    @Override
584    public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
585        if (preference instanceof AccessPoint) {
586            mSelectedAccessPoint = (AccessPoint) preference;
587            /** Bypass dialog for unsecured, unsaved networks */
588            if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE &&
589                    mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) {
590                mSelectedAccessPoint.generateOpenNetworkConfig();
591                if (!savedNetworksExist) {
592                    savedNetworksExist = true;
593                    getActivity().invalidateOptionsMenu();
594                }
595                connect(mSelectedAccessPoint.getConfig());
596            } else {
597                showDialog(mSelectedAccessPoint, false);
598            }
599        } else {
600            return super.onPreferenceTreeClick(screen, preference);
601        }
602        return true;
603    }
604
605    private void showDialog(AccessPoint accessPoint, boolean edit) {
606        if (mDialog != null) {
607            removeDialog(WIFI_DIALOG_ID);
608            mDialog = null;
609        }
610
611        // Save the access point and edit mode
612        mDlgAccessPoint = accessPoint;
613        mDlgEdit = edit;
614
615        showDialog(WIFI_DIALOG_ID);
616    }
617
618    @Override
619    public Dialog onCreateDialog(int dialogId) {
620        switch (dialogId) {
621            case WIFI_DIALOG_ID:
622                AccessPoint ap = mDlgAccessPoint; // For manual launch
623                if (ap == null) { // For re-launch from saved state
624                    if (mAccessPointSavedState != null) {
625                        ap = new AccessPoint(getActivity(), mAccessPointSavedState);
626                        // For repeated orientation changes
627                        mDlgAccessPoint = ap;
628                        // Reset the saved access point data
629                        mAccessPointSavedState = null;
630                    }
631                }
632                // If it's null, fine, it's for Add Network
633                mSelectedAccessPoint = ap;
634                mDialog = new WifiDialog(getActivity(), this, ap, mDlgEdit);
635                return mDialog;
636            case WPS_PBC_DIALOG_ID:
637                return new WpsDialog(getActivity(), WpsInfo.PBC);
638            case WPS_PIN_DIALOG_ID:
639                return new WpsDialog(getActivity(), WpsInfo.DISPLAY);
640            case WRITE_NFC_DIALOG_ID:
641                if (mSelectedAccessPoint != null) {
642                    mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(
643                            getActivity(), mSelectedAccessPoint, mWifiManager);
644                    return mWifiToNfcDialog;
645                }
646
647        }
648        return super.onCreateDialog(dialogId);
649    }
650
651    /**
652     * Shows the latest access points available with supplemental information like
653     * the strength of network and the security for it.
654     */
655    private void updateAccessPoints() {
656        // Safeguard from some delayed event handling
657        if (getActivity() == null) return;
658
659        if (isUiRestricted()) {
660            addMessagePreference(R.string.wifi_empty_list_user_restricted);
661            return;
662        }
663        final int wifiState = mWifiManager.getWifiState();
664
665        //when we update the screen, check if verbose logging has been turned on or off
666        mVerboseLogging = mWifiManager.getVerboseLoggingLevel();
667
668        switch (wifiState) {
669            case WifiManager.WIFI_STATE_ENABLED:
670                // AccessPoints are automatically sorted with TreeSet.
671                final Collection<AccessPoint> accessPoints =
672                        constructAccessPoints(getActivity(), mWifiManager, mLastInfo,
673                                mLastNetworkInfo);
674                getPreferenceScreen().removeAll();
675                if (accessPoints.size() == 0) {
676                    addMessagePreference(R.string.wifi_empty_list_wifi_on);
677                }
678
679                for (AccessPoint accessPoint : accessPoints) {
680                    if (showAppIcons) {
681                        accessPoint.showAppIcon();
682                    }
683
684                    // Ignore access points that are out of range.
685                    if (accessPoint.getLevel() != -1) {
686                        getPreferenceScreen().addPreference(accessPoint);
687                    }
688                }
689                break;
690
691            case WifiManager.WIFI_STATE_ENABLING:
692                getPreferenceScreen().removeAll();
693                break;
694
695            case WifiManager.WIFI_STATE_DISABLING:
696                addMessagePreference(R.string.wifi_stopping);
697                break;
698
699            case WifiManager.WIFI_STATE_DISABLED:
700                setOffMessage();
701                break;
702        }
703    }
704
705    protected TextView initEmptyView() {
706        TextView emptyView = (TextView) getActivity().findViewById(android.R.id.empty);
707        getListView().setEmptyView(emptyView);
708        return emptyView;
709    }
710
711    private void setOffMessage() {
712        if (mEmptyView != null) {
713            mEmptyView.setText(R.string.wifi_empty_list_wifi_off);
714            if (android.provider.Settings.Global.getInt(getActivity().getContentResolver(),
715                    android.provider.Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1) {
716                mEmptyView.append("\n\n");
717                int resId;
718                if (android.provider.Settings.Secure.isLocationProviderEnabled(
719                        getActivity().getContentResolver(), LocationManager.NETWORK_PROVIDER)) {
720                    resId = R.string.wifi_scan_notify_text_location_on;
721                } else {
722                    resId = R.string.wifi_scan_notify_text_location_off;
723                }
724                CharSequence charSeq = getText(resId);
725                mEmptyView.append(charSeq);
726            }
727        }
728        getPreferenceScreen().removeAll();
729    }
730
731    private void addMessagePreference(int messageId) {
732        if (mEmptyView != null) mEmptyView.setText(messageId);
733        getPreferenceScreen().removeAll();
734    }
735
736    /** Returns sorted list of access points */
737    private static List<AccessPoint> constructAccessPoints(Context context,
738            WifiManager wifiManager, WifiInfo lastInfo, NetworkInfo lastNetworkInfo) {
739        ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>();
740        /** Lookup table to more quickly update AccessPoints by only considering objects with the
741         * correct SSID.  Maps SSID -> List of AccessPoints with the given SSID.  */
742        Multimap<String, AccessPoint> apMap = new Multimap<String, AccessPoint>();
743
744        final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
745        if (configs != null) {
746            // Update "Saved Networks" menu option.
747            if (savedNetworksExist != (configs.size() > 0)) {
748                savedNetworksExist = !savedNetworksExist;
749                if (context instanceof Activity) {
750                    ((Activity) context).invalidateOptionsMenu();
751                }
752            }
753            for (WifiConfiguration config : configs) {
754                if (config.selfAdded && config.numAssociation == 0) {
755                    continue;
756                }
757                AccessPoint accessPoint = new AccessPoint(context, config);
758                if (lastInfo != null && lastNetworkInfo != null) {
759                    accessPoint.update(lastInfo, lastNetworkInfo);
760                }
761                accessPoints.add(accessPoint);
762                apMap.put(accessPoint.ssid, accessPoint);
763            }
764        }
765
766        final List<ScanResult> results = wifiManager.getScanResults();
767        if (results != null) {
768            for (ScanResult result : results) {
769                // Ignore hidden and ad-hoc networks.
770                if (result.SSID == null || result.SSID.length() == 0 ||
771                        result.capabilities.contains("[IBSS]")) {
772                    continue;
773                }
774
775                boolean found = false;
776                for (AccessPoint accessPoint : apMap.getAll(result.SSID)) {
777                    if (accessPoint.update(result))
778                        found = true;
779                }
780                if (!found) {
781                    AccessPoint accessPoint = new AccessPoint(context, result);
782                    if (lastInfo != null && lastNetworkInfo != null) {
783                        accessPoint.update(lastInfo, lastNetworkInfo);
784                    }
785                    accessPoints.add(accessPoint);
786                    apMap.put(accessPoint.ssid, accessPoint);
787                }
788            }
789        }
790
791        // Pre-sort accessPoints to speed preference insertion
792        Collections.sort(accessPoints);
793        return accessPoints;
794    }
795
796    private void handleEvent(Intent intent) {
797        String action = intent.getAction();
798        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
799            updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
800                    WifiManager.WIFI_STATE_UNKNOWN));
801        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) ||
802                WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) ||
803                WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) {
804                updateAccessPoints();
805        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
806            NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
807                    WifiManager.EXTRA_NETWORK_INFO);
808            mConnected.set(info.isConnected());
809            changeNextButtonState(info.isConnected());
810            updateAccessPoints();
811            updateNetworkInfo(info);
812        } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
813            updateNetworkInfo(null);
814        }
815    }
816
817    private void updateNetworkInfo(NetworkInfo networkInfo) {
818        /* sticky broadcasts can call this when wifi is disabled */
819        if (!mWifiManager.isWifiEnabled()) {
820            mScanner.pause();
821            return;
822        }
823
824        if (networkInfo != null &&
825                networkInfo.getDetailedState() == DetailedState.OBTAINING_IPADDR) {
826            mScanner.pause();
827        } else {
828            mScanner.resume();
829        }
830
831        mLastInfo = mWifiManager.getConnectionInfo();
832        if (networkInfo != null) {
833            mLastNetworkInfo = networkInfo;
834        }
835
836        for (int i = getPreferenceScreen().getPreferenceCount() - 1; i >= 0; --i) {
837            // Maybe there's a WifiConfigPreference
838            Preference preference = getPreferenceScreen().getPreference(i);
839            if (preference instanceof AccessPoint) {
840                final AccessPoint accessPoint = (AccessPoint) preference;
841                accessPoint.update(mLastInfo, mLastNetworkInfo);
842            }
843        }
844    }
845
846    private void updateWifiState(int state) {
847        Activity activity = getActivity();
848        if (activity != null) {
849            activity.invalidateOptionsMenu();
850        }
851
852        switch (state) {
853            case WifiManager.WIFI_STATE_ENABLED:
854                mScanner.resume();
855                return; // not break, to avoid the call to pause() below
856
857            case WifiManager.WIFI_STATE_ENABLING:
858                addMessagePreference(R.string.wifi_starting);
859                break;
860
861            case WifiManager.WIFI_STATE_DISABLED:
862                setOffMessage();
863                break;
864        }
865
866        mLastInfo = null;
867        mLastNetworkInfo = null;
868        mScanner.pause();
869    }
870
871    /**
872     * Renames/replaces "Next" button when appropriate. "Next" button usually exists in
873     * Wifi setup screens, not in usual wifi settings screen.
874     *
875     * @param enabled true when the device is connected to a wifi network.
876     */
877    private void changeNextButtonState(boolean enabled) {
878        if (mEnableNextOnConnection && hasNextButton()) {
879            getNextButton().setEnabled(enabled);
880        }
881    }
882
883    @Override
884    public void onClick(DialogInterface dialogInterface, int button) {
885        if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
886            forget();
887        } else if (button == WifiDialog.BUTTON_SUBMIT) {
888            if (mDialog != null) {
889                submit(mDialog.getController());
890            }
891        }
892    }
893
894    /* package */ void submit(WifiConfigController configController) {
895
896        final WifiConfiguration config = configController.getConfig();
897
898        if (config == null) {
899            if (mSelectedAccessPoint != null
900                    && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
901                connect(mSelectedAccessPoint.networkId);
902            }
903        } else if (config.networkId != INVALID_NETWORK_ID) {
904            if (mSelectedAccessPoint != null) {
905                mWifiManager.save(config, mSaveListener);
906            }
907        } else {
908            if (configController.isEdit()) {
909                mWifiManager.save(config, mSaveListener);
910            } else {
911                connect(config);
912            }
913        }
914
915        if (mWifiManager.isWifiEnabled()) {
916            mScanner.resume();
917        }
918        updateAccessPoints();
919    }
920
921    /* package */ void forget() {
922        if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) {
923            // Should not happen, but a monkey seems to trigger it
924            Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig());
925            return;
926        }
927
928        mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener);
929
930        if (mWifiManager.isWifiEnabled()) {
931            mScanner.resume();
932        }
933        updateAccessPoints();
934
935        // We need to rename/replace "Next" button in wifi setup context.
936        changeNextButtonState(false);
937    }
938
939    protected void connect(final WifiConfiguration config) {
940        mWifiManager.connect(config, mConnectListener);
941    }
942
943    protected void connect(final int networkId) {
944        mWifiManager.connect(networkId, mConnectListener);
945    }
946
947    /**
948     * Refreshes acccess points and ask Wifi module to scan networks again.
949     */
950    /* package */ void refreshAccessPoints() {
951        if (mWifiManager.isWifiEnabled()) {
952            mScanner.resume();
953        }
954
955        getPreferenceScreen().removeAll();
956    }
957
958    /**
959     * Called when "add network" button is pressed.
960     */
961    /* package */ void onAddNetworkPressed() {
962        // No exact access point is selected.
963        mSelectedAccessPoint = null;
964        showDialog(null, true);
965    }
966
967    /* package */ int getAccessPointsCount() {
968        final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
969        if (wifiIsEnabled) {
970            return getPreferenceScreen().getPreferenceCount();
971        } else {
972            return 0;
973        }
974    }
975
976    /**
977     * Requests wifi module to pause wifi scan. May be ignored when the module is disabled.
978     */
979    /* package */ void pauseWifiScan() {
980        if (mWifiManager.isWifiEnabled()) {
981            mScanner.pause();
982        }
983    }
984
985    /**
986     * Requests wifi module to resume wifi scan. May be ignored when the module is disabled.
987     */
988    /* package */ void resumeWifiScan() {
989        if (mWifiManager.isWifiEnabled()) {
990            mScanner.resume();
991        }
992    }
993
994    @Override
995    protected int getHelpResource() {
996        return R.string.help_url_wifi;
997    }
998
999    public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
1000        new BaseSearchIndexProvider() {
1001            @Override
1002            public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) {
1003                final List<SearchIndexableRaw> result = new ArrayList<SearchIndexableRaw>();
1004                final Resources res = context.getResources();
1005
1006                // Add fragment title
1007                SearchIndexableRaw data = new SearchIndexableRaw(context);
1008                data.title = res.getString(R.string.wifi_settings);
1009                data.screenTitle = res.getString(R.string.wifi_settings);
1010                data.keywords = res.getString(R.string.keywords_wifi);
1011                result.add(data);
1012
1013                // Add available Wi-Fi access points
1014                WifiManager wifiManager =
1015                        (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
1016                final Collection<AccessPoint> accessPoints =
1017                        constructAccessPoints(context, wifiManager, null, null);
1018                for (AccessPoint accessPoint : accessPoints) {
1019                    // We are indexing only the saved Wi-Fi networks.
1020                    if (accessPoint.getConfig() == null) continue;
1021                    data = new SearchIndexableRaw(context);
1022                    data.title = accessPoint.getTitle().toString();
1023                    data.screenTitle = res.getString(R.string.wifi_settings);
1024                    data.enabled = enabled;
1025                    result.add(data);
1026                }
1027
1028                return result;
1029            }
1030        };
1031}
1032