WifiSettings.java revision 263bcc8b732dbb47d3ce63904e0e05191fabbad6
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.preference.PreferenceActivity;
23import com.android.settings.R;
24import com.android.settings.RestrictedSettingsFragment;
25import com.android.settings.SettingsActivity;
26import com.android.settings.wifi.p2p.WifiP2pSettings;
27
28import android.app.ActionBar;
29import android.app.Activity;
30import android.app.AlertDialog;
31import android.app.Dialog;
32import android.content.BroadcastReceiver;
33import android.content.Context;
34import android.content.DialogInterface;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.pm.PackageManager;
38import android.content.res.Resources;
39import android.content.res.TypedArray;
40import android.location.LocationManager;
41import android.net.ConnectivityManager;
42import android.net.NetworkInfo;
43import android.net.NetworkInfo.DetailedState;
44import android.net.wifi.ScanResult;
45import android.net.wifi.SupplicantState;
46import android.net.wifi.WifiConfiguration;
47import android.net.wifi.WifiInfo;
48import android.net.wifi.WifiManager;
49import android.net.wifi.WpsInfo;
50import android.os.Bundle;
51import android.os.Handler;
52import android.os.Message;
53import android.preference.Preference;
54import android.preference.PreferenceScreen;
55import android.util.AttributeSet;
56import android.util.Log;
57import android.view.ContextMenu;
58import android.view.ContextMenu.ContextMenuInfo;
59import android.view.Gravity;
60import android.view.LayoutInflater;
61import android.view.Menu;
62import android.view.MenuInflater;
63import android.view.MenuItem;
64import android.view.View;
65import android.view.View.OnClickListener;
66import android.view.ViewGroup;
67import android.widget.AdapterView.AdapterContextMenuInfo;
68import android.widget.Button;
69import android.widget.ImageButton;
70import android.widget.PopupMenu;
71import android.widget.PopupMenu.OnMenuItemClickListener;
72import android.widget.RelativeLayout;
73import android.widget.Switch;
74import android.widget.TextView;
75import android.widget.Toast;
76
77import java.util.ArrayList;
78import java.util.Collection;
79import java.util.Collections;
80import java.util.HashMap;
81import java.util.List;
82import java.util.concurrent.atomic.AtomicBoolean;
83
84/**
85 * Two types of UI are provided here.
86 *
87 * The first is for "usual Settings", appearing as any other Setup fragment.
88 *
89 * The second is for Setup Wizard, with a simplified interface that hides the action bar
90 * and menus.
91 */
92public class WifiSettings extends RestrictedSettingsFragment
93        implements DialogInterface.OnClickListener  {
94    private static final String TAG = "WifiSettings";
95    private static final int MENU_ID_WPS_PBC = Menu.FIRST;
96    private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1;
97    private static final int MENU_ID_P2P = Menu.FIRST + 2;
98    private static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3;
99    private static final int MENU_ID_ADVANCED = Menu.FIRST + 4;
100    private static final int MENU_ID_SCAN = Menu.FIRST + 5;
101    private static final int MENU_ID_CONNECT = Menu.FIRST + 6;
102    private static final int MENU_ID_FORGET = Menu.FIRST + 7;
103    private static final int MENU_ID_MODIFY = Menu.FIRST + 8;
104
105    private static final int WIFI_DIALOG_ID = 1;
106    private static final int WPS_PBC_DIALOG_ID = 2;
107    private static final int WPS_PIN_DIALOG_ID = 3;
108    private static final int WIFI_SKIPPED_DIALOG_ID = 4;
109    private static final int WIFI_AND_MOBILE_SKIPPED_DIALOG_ID = 5;
110
111    // Combo scans can take 5-6s to complete - set to 10s.
112    private static final int WIFI_RESCAN_INTERVAL_MS = 10 * 1000;
113
114    // Instance state keys
115    private static final String SAVE_DIALOG_EDIT_MODE = "edit_mode";
116    private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state";
117
118    // Activity result when pressing the Skip button
119    private static final int RESULT_SKIP = Activity.RESULT_FIRST_USER;
120
121    private final IntentFilter mFilter;
122    private final BroadcastReceiver mReceiver;
123    private final Scanner mScanner;
124
125    private WifiManager mWifiManager;
126    private WifiManager.ActionListener mConnectListener;
127    private WifiManager.ActionListener mSaveListener;
128    private WifiManager.ActionListener mForgetListener;
129    private boolean mP2pSupported;
130
131    private WifiEnabler mWifiEnabler;
132    // An access point being editted is stored here.
133    private AccessPoint mSelectedAccessPoint;
134
135    private DetailedState mLastState;
136    private WifiInfo mLastInfo;
137
138    private final AtomicBoolean mConnected = new AtomicBoolean(false);
139
140    private WifiDialog mDialog;
141
142    private TextView mEmptyView;
143
144    /* Used in Wifi Setup context */
145
146    // this boolean extra specifies whether to disable the Next button when not connected
147    private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
148
149    // this boolean extra specifies whether to auto finish when connection is established
150    private static final String EXTRA_AUTO_FINISH_ON_CONNECT = "wifi_auto_finish_on_connect";
151
152    // this boolean extra shows a custom button that we can control
153    protected static final String EXTRA_SHOW_CUSTOM_BUTTON = "wifi_show_custom_button";
154
155    // show a text regarding data charges when wifi connection is required during setup wizard
156    protected static final String EXTRA_SHOW_WIFI_REQUIRED_INFO = "wifi_show_wifi_required_info";
157
158    // this boolean extra is set if we are being invoked by the Setup Wizard
159    private static final String EXTRA_IS_FIRST_RUN = "firstRun";
160
161    // should Next button only be enabled when we have a connection?
162    private boolean mEnableNextOnConnection;
163
164    // should activity finish once we have a connection?
165    private boolean mAutoFinishOnConnection;
166
167    // Save the dialog details
168    private boolean mDlgEdit;
169    private AccessPoint mDlgAccessPoint;
170    private Bundle mAccessPointSavedState;
171
172    // the action bar uses a different set of controls for Setup Wizard
173    private boolean mSetupWizardMode;
174
175    private Switch mSwitch;
176
177    /* End of "used in Wifi Setup context" */
178
179    public WifiSettings() {
180        super(DISALLOW_CONFIG_WIFI);
181        mFilter = new IntentFilter();
182        mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
183        mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
184        mFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
185        mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
186        mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
187        mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
188        mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
189        mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
190
191        mReceiver = new BroadcastReceiver() {
192            @Override
193            public void onReceive(Context context, Intent intent) {
194                handleEvent(context, intent);
195            }
196        };
197
198        mScanner = new Scanner();
199    }
200
201    @Override
202    public void onCreate(Bundle icicle) {
203        // Set this flag early, as it's needed by getHelpResource(), which is called by super
204        mSetupWizardMode = getActivity().getIntent().getBooleanExtra(EXTRA_IS_FIRST_RUN, false);
205
206        super.onCreate(icicle);
207    }
208
209    @Override
210    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
211            Bundle savedInstanceState) {
212        if (mSetupWizardMode) {
213            View view = inflater.inflate(R.layout.setup_preference, container, false);
214            View other = view.findViewById(R.id.other_network);
215            other.setOnClickListener(new OnClickListener() {
216                @Override
217                public void onClick(View v) {
218                    if (mWifiManager.isWifiEnabled()) {
219                        onAddNetworkPressed();
220                    }
221                }
222            });
223            final ImageButton b = (ImageButton) view.findViewById(R.id.more);
224            if (b != null) {
225                b.setOnClickListener(new OnClickListener() {
226                    @Override
227                    public void onClick(View v) {
228                        if (mWifiManager.isWifiEnabled()) {
229                            PopupMenu pm = new PopupMenu(inflater.getContext(), b);
230                            pm.inflate(R.menu.wifi_setup);
231                            pm.setOnMenuItemClickListener(new OnMenuItemClickListener() {
232                                @Override
233                                public boolean onMenuItemClick(MenuItem item) {
234                                    if (R.id.wifi_wps == item.getItemId()) {
235                                        showDialog(WPS_PBC_DIALOG_ID);
236                                        return true;
237                                    }
238                                    return false;
239                                }
240                            });
241                            pm.show();
242                        }
243                    }
244                });
245            }
246
247            Intent intent = getActivity().getIntent();
248            if (intent.getBooleanExtra(EXTRA_SHOW_CUSTOM_BUTTON, false)) {
249                view.findViewById(R.id.button_bar).setVisibility(View.VISIBLE);
250                view.findViewById(R.id.back_button).setVisibility(View.INVISIBLE);
251                view.findViewById(R.id.skip_button).setVisibility(View.INVISIBLE);
252                view.findViewById(R.id.next_button).setVisibility(View.INVISIBLE);
253
254                Button customButton = (Button) view.findViewById(R.id.custom_button);
255                customButton.setVisibility(View.VISIBLE);
256                customButton.setOnClickListener(new OnClickListener() {
257                    @Override
258                    public void onClick(View v) {
259                        boolean isConnected = false;
260                        Activity activity = getActivity();
261                        final ConnectivityManager connectivity = (ConnectivityManager)
262                                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
263                        if (connectivity != null) {
264                            final NetworkInfo info = connectivity.getActiveNetworkInfo();
265                            isConnected = (info != null) && info.isConnected();
266                        }
267                        if (isConnected) {
268                            // Warn of possible data charges
269                            showDialog(WIFI_SKIPPED_DIALOG_ID);
270                        } else {
271                            // Warn of lack of updates
272                            showDialog(WIFI_AND_MOBILE_SKIPPED_DIALOG_ID);
273                        }
274                    }
275                });
276            }
277
278            if (intent.getBooleanExtra(EXTRA_SHOW_WIFI_REQUIRED_INFO, false)) {
279                view.findViewById(R.id.wifi_required_info).setVisibility(View.VISIBLE);
280            }
281
282            return view;
283        } else {
284            return super.onCreateView(inflater, container, savedInstanceState);
285        }
286    }
287
288    @Override
289    public void onActivityCreated(Bundle savedInstanceState) {
290        super.onActivityCreated(savedInstanceState);
291
292        mP2pSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT);
293        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
294
295        mConnectListener = new WifiManager.ActionListener() {
296                                   @Override
297                                   public void onSuccess() {
298                                   }
299                                   @Override
300                                   public void onFailure(int reason) {
301                                       Activity activity = getActivity();
302                                       if (activity != null) {
303                                           Toast.makeText(activity,
304                                                R.string.wifi_failed_connect_message,
305                                                Toast.LENGTH_SHORT).show();
306                                       }
307                                   }
308                               };
309
310        mSaveListener = new WifiManager.ActionListener() {
311                                @Override
312                                public void onSuccess() {
313                                }
314                                @Override
315                                public void onFailure(int reason) {
316                                    Activity activity = getActivity();
317                                    if (activity != null) {
318                                        Toast.makeText(activity,
319                                            R.string.wifi_failed_save_message,
320                                            Toast.LENGTH_SHORT).show();
321                                    }
322                                }
323                            };
324
325        mForgetListener = new WifiManager.ActionListener() {
326                                   @Override
327                                   public void onSuccess() {
328                                   }
329                                   @Override
330                                   public void onFailure(int reason) {
331                                       Activity activity = getActivity();
332                                       if (activity != null) {
333                                           Toast.makeText(activity,
334                                               R.string.wifi_failed_forget_message,
335                                               Toast.LENGTH_SHORT).show();
336                                       }
337                                   }
338                               };
339
340        if (savedInstanceState != null
341                && savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) {
342            mDlgEdit = savedInstanceState.getBoolean(SAVE_DIALOG_EDIT_MODE);
343            mAccessPointSavedState = savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
344        }
345
346        final Activity activity = getActivity();
347        final Intent intent = activity.getIntent();
348
349        // first if we're supposed to finish once we have a connection
350        mAutoFinishOnConnection = intent.getBooleanExtra(EXTRA_AUTO_FINISH_ON_CONNECT, false);
351
352        if (mAutoFinishOnConnection) {
353            // Hide the next button
354            if (hasNextButton()) {
355                getNextButton().setVisibility(View.GONE);
356            }
357
358            final ConnectivityManager connectivity = (ConnectivityManager)
359                    activity.getSystemService(Context.CONNECTIVITY_SERVICE);
360            if (connectivity != null
361                    && connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
362                activity.setResult(Activity.RESULT_OK);
363                activity.finish();
364                return;
365            }
366        }
367
368        // if we're supposed to enable/disable the Next button based on our current connection
369        // state, start it off in the right state
370        mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
371
372        if (mEnableNextOnConnection) {
373            if (hasNextButton()) {
374                final ConnectivityManager connectivity = (ConnectivityManager)
375                        activity.getSystemService(Context.CONNECTIVITY_SERVICE);
376                if (connectivity != null) {
377                    NetworkInfo info = connectivity.getNetworkInfo(
378                            ConnectivityManager.TYPE_WIFI);
379                    changeNextButtonState(info.isConnected());
380                }
381            }
382        }
383
384        addPreferencesFromResource(R.xml.wifi_settings);
385
386        if (mSetupWizardMode) {
387            getView().setSystemUiVisibility(
388                    View.STATUS_BAR_DISABLE_HOME |
389                    View.STATUS_BAR_DISABLE_RECENT |
390                    View.STATUS_BAR_DISABLE_NOTIFICATION_ALERTS |
391                    View.STATUS_BAR_DISABLE_CLOCK);
392        }
393
394        mEmptyView = (TextView) getView().findViewById(android.R.id.empty);
395        getListView().setEmptyView(mEmptyView);
396
397        if (!mSetupWizardMode) {
398            registerForContextMenu(getListView());
399        }
400        setHasOptionsMenu(true);
401    }
402
403    @Override
404    public void onStart() {
405        super.onStart();
406
407        // On/off switch is hidden for Setup Wizard
408        if (!mSetupWizardMode) {
409            final Activity activity = getActivity();
410
411            mSwitch = new Switch(activity);
412
413            if (activity instanceof SettingsActivity) {
414                SettingsActivity sa = (SettingsActivity) activity;
415                if (!sa.onIsHidingHeaders()) {
416                    final int padding = activity.getResources().getDimensionPixelSize(
417                            R.dimen.action_bar_switch_padding);
418                    mSwitch.setPaddingRelative(0, 0, padding, 0);
419                    activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
420                            ActionBar.DISPLAY_SHOW_CUSTOM);
421                    activity.getActionBar().setCustomView(mSwitch, new ActionBar.LayoutParams(
422                            ActionBar.LayoutParams.WRAP_CONTENT,
423                            ActionBar.LayoutParams.WRAP_CONTENT,
424                            Gravity.CENTER_VERTICAL | Gravity.END));
425                }
426            }
427
428            mWifiEnabler = new WifiEnabler(activity, mSwitch);
429        }
430    }
431
432    @Override
433    public void onStop() {
434        super.onStop();
435        Activity activity = getActivity();
436        boolean onIsHidingHeaders = true;
437        if (activity instanceof SettingsActivity){
438            SettingsActivity sa = (SettingsActivity) activity;
439            onIsHidingHeaders = sa.onIsHidingHeaders();
440        } else if (activity instanceof PreferenceActivity) {
441            PreferenceActivity pa = (PreferenceActivity) activity;
442            onIsHidingHeaders = pa.onIsHidingHeaders();
443        }
444        if (!onIsHidingHeaders) {
445            activity.getActionBar().setDisplayOptions(0, ActionBar.DISPLAY_SHOW_CUSTOM);
446            activity.getActionBar().setCustomView(null);
447        }
448    }
449
450    @Override
451    public void onResume() {
452        super.onResume();
453        if (mWifiEnabler != null) {
454            mWifiEnabler.resume();
455        }
456
457        getActivity().registerReceiver(mReceiver, mFilter);
458        updateAccessPoints();
459    }
460
461    @Override
462    public void onPause() {
463        super.onPause();
464        if (mWifiEnabler != null) {
465            mWifiEnabler.pause();
466        }
467        getActivity().unregisterReceiver(mReceiver);
468        mScanner.pause();
469    }
470
471    @Override
472    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
473        // If the user is not allowed to configure wifi, do not show the menu.
474        if (isRestrictedAndNotPinProtected()) return;
475
476        final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
477        TypedArray ta = getActivity().getTheme().obtainStyledAttributes(
478                new int[] {R.attr.ic_menu_add, R.attr.ic_wps});
479        if (mSetupWizardMode) {
480            menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc)
481                    .setIcon(ta.getDrawable(1))
482                    .setEnabled(wifiIsEnabled)
483                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
484            menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
485                    .setEnabled(wifiIsEnabled)
486                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
487        } else {
488            menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc)
489                    .setIcon(ta.getDrawable(1))
490                    .setEnabled(wifiIsEnabled)
491                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
492            menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
493                    .setIcon(ta.getDrawable(0))
494                    .setEnabled(wifiIsEnabled)
495                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
496            menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan)
497                    //.setIcon(R.drawable.ic_menu_scan_network)
498                    .setEnabled(wifiIsEnabled)
499                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
500            menu.add(Menu.NONE, MENU_ID_WPS_PIN, 0, R.string.wifi_menu_wps_pin)
501                    .setEnabled(wifiIsEnabled)
502                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
503            if (mP2pSupported) {
504                menu.add(Menu.NONE, MENU_ID_P2P, 0, R.string.wifi_menu_p2p)
505                        .setEnabled(wifiIsEnabled)
506                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
507            }
508            menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced)
509                    //.setIcon(android.R.drawable.ic_menu_manage)
510                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
511        }
512        ta.recycle();
513        super.onCreateOptionsMenu(menu, inflater);
514    }
515
516    @Override
517    public void onSaveInstanceState(Bundle outState) {
518        super.onSaveInstanceState(outState);
519
520        // If the dialog is showing, save its state.
521        if (mDialog != null && mDialog.isShowing()) {
522            outState.putBoolean(SAVE_DIALOG_EDIT_MODE, mDlgEdit);
523            if (mDlgAccessPoint != null) {
524                mAccessPointSavedState = new Bundle();
525                mDlgAccessPoint.saveWifiState(mAccessPointSavedState);
526                outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState);
527            }
528        }
529    }
530
531    @Override
532    public boolean onOptionsItemSelected(MenuItem item) {
533        // If the user is not allowed to configure wifi, do not handle menu selections.
534        if (isRestrictedAndNotPinProtected()) return false;
535
536        switch (item.getItemId()) {
537            case MENU_ID_WPS_PBC:
538                showDialog(WPS_PBC_DIALOG_ID);
539                return true;
540            case MENU_ID_P2P:
541                if (getActivity() instanceof SettingsActivity) {
542                    ((SettingsActivity) getActivity()).startPreferencePanel(
543                            WifiP2pSettings.class.getCanonicalName(),
544                            null,
545                            R.string.wifi_p2p_settings_title, null,
546                            this, 0);
547                } else {
548                    startFragment(this, WifiP2pSettings.class.getCanonicalName(), -1, null);
549                }
550                return true;
551            case MENU_ID_WPS_PIN:
552                showDialog(WPS_PIN_DIALOG_ID);
553                return true;
554            case MENU_ID_SCAN:
555                if (mWifiManager.isWifiEnabled()) {
556                    mScanner.forceScan();
557                }
558                return true;
559            case MENU_ID_ADD_NETWORK:
560                if (mWifiManager.isWifiEnabled()) {
561                    onAddNetworkPressed();
562                }
563                return true;
564            case MENU_ID_ADVANCED:
565                if (getActivity() instanceof SettingsActivity) {
566                    ((SettingsActivity) getActivity()).startPreferencePanel(
567                            AdvancedWifiSettings.class.getCanonicalName(),
568                            null,
569                            R.string.wifi_advanced_titlebar, null,
570                            this, 0);
571                } else {
572                    startFragment(this, AdvancedWifiSettings.class.getCanonicalName(), -1, null);
573                }
574                return true;
575        }
576        return super.onOptionsItemSelected(item);
577    }
578
579    @Override
580    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
581        if (info instanceof AdapterContextMenuInfo) {
582            Preference preference = (Preference) getListView().getItemAtPosition(
583                    ((AdapterContextMenuInfo) info).position);
584
585            if (preference instanceof AccessPoint) {
586                mSelectedAccessPoint = (AccessPoint) preference;
587                menu.setHeaderTitle(mSelectedAccessPoint.ssid);
588                if (mSelectedAccessPoint.getLevel() != -1
589                        && mSelectedAccessPoint.getState() == null) {
590                    menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect);
591                }
592                if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
593                    menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget);
594                    menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify);
595                }
596            }
597        }
598    }
599
600    @Override
601    public boolean onContextItemSelected(MenuItem item) {
602        if (mSelectedAccessPoint == null) {
603            return super.onContextItemSelected(item);
604        }
605        switch (item.getItemId()) {
606            case MENU_ID_CONNECT: {
607                if (mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
608                    mWifiManager.connect(mSelectedAccessPoint.networkId,
609                            mConnectListener);
610                } else if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE) {
611                    /** Bypass dialog for unsecured networks */
612                    mSelectedAccessPoint.generateOpenNetworkConfig();
613                    mWifiManager.connect(mSelectedAccessPoint.getConfig(),
614                            mConnectListener);
615                } else {
616                    showDialog(mSelectedAccessPoint, true);
617                }
618                return true;
619            }
620            case MENU_ID_FORGET: {
621                mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener);
622                return true;
623            }
624            case MENU_ID_MODIFY: {
625                showDialog(mSelectedAccessPoint, true);
626                return true;
627            }
628        }
629        return super.onContextItemSelected(item);
630    }
631
632    @Override
633    public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
634        if (preference instanceof AccessPoint) {
635            mSelectedAccessPoint = (AccessPoint) preference;
636            /** Bypass dialog for unsecured, unsaved networks */
637            if (mSelectedAccessPoint.security == AccessPoint.SECURITY_NONE &&
638                    mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) {
639                mSelectedAccessPoint.generateOpenNetworkConfig();
640                mWifiManager.connect(mSelectedAccessPoint.getConfig(), mConnectListener);
641            } else {
642                showDialog(mSelectedAccessPoint, false);
643            }
644        } else {
645            return super.onPreferenceTreeClick(screen, preference);
646        }
647        return true;
648    }
649
650    private void showDialog(AccessPoint accessPoint, boolean edit) {
651        if (mDialog != null) {
652            removeDialog(WIFI_DIALOG_ID);
653            mDialog = null;
654        }
655
656        // Save the access point and edit mode
657        mDlgAccessPoint = accessPoint;
658        mDlgEdit = edit;
659
660        showDialog(WIFI_DIALOG_ID);
661    }
662
663    @Override
664    public Dialog onCreateDialog(int dialogId) {
665        switch (dialogId) {
666            case WIFI_DIALOG_ID:
667                AccessPoint ap = mDlgAccessPoint; // For manual launch
668                if (ap == null) { // For re-launch from saved state
669                    if (mAccessPointSavedState != null) {
670                        ap = new AccessPoint(getActivity(), mAccessPointSavedState);
671                        // For repeated orientation changes
672                        mDlgAccessPoint = ap;
673                        // Reset the saved access point data
674                        mAccessPointSavedState = null;
675                    }
676                }
677                // If it's still null, fine, it's for Add Network
678                mSelectedAccessPoint = ap;
679                mDialog = new WifiDialog(getActivity(), this, ap, mDlgEdit);
680                return mDialog;
681            case WPS_PBC_DIALOG_ID:
682                return new WpsDialog(getActivity(), WpsInfo.PBC);
683            case WPS_PIN_DIALOG_ID:
684                return new WpsDialog(getActivity(), WpsInfo.DISPLAY);
685            case WIFI_SKIPPED_DIALOG_ID:
686                return new AlertDialog.Builder(getActivity())
687                            .setMessage(R.string.wifi_skipped_message)
688                            .setCancelable(false)
689                            .setNegativeButton(R.string.wifi_skip_anyway,
690                                    new DialogInterface.OnClickListener() {
691                                @Override
692                                public void onClick(DialogInterface dialog, int id) {
693                                    getActivity().setResult(RESULT_SKIP);
694                                    getActivity().finish();
695                                }
696                            })
697                            .setPositiveButton(R.string.wifi_dont_skip,
698                                    new DialogInterface.OnClickListener() {
699                                @Override
700                                public void onClick(DialogInterface dialog, int id) {
701                                }
702                            })
703                            .create();
704            case WIFI_AND_MOBILE_SKIPPED_DIALOG_ID:
705                return new AlertDialog.Builder(getActivity())
706                            .setMessage(R.string.wifi_and_mobile_skipped_message)
707                            .setCancelable(false)
708                            .setNegativeButton(R.string.wifi_skip_anyway,
709                                    new DialogInterface.OnClickListener() {
710                                @Override
711                                public void onClick(DialogInterface dialog, int id) {
712                                    getActivity().setResult(RESULT_SKIP);
713                                    getActivity().finish();
714                                }
715                            })
716                            .setPositiveButton(R.string.wifi_dont_skip,
717                                    new DialogInterface.OnClickListener() {
718                                @Override
719                                public void onClick(DialogInterface dialog, int id) {
720                                }
721                            })
722                            .create();
723
724        }
725        return super.onCreateDialog(dialogId);
726    }
727
728    /**
729     * Shows the latest access points available with supplimental information like
730     * the strength of network and the security for it.
731     */
732    private void updateAccessPoints() {
733        // Safeguard from some delayed event handling
734        if (getActivity() == null) return;
735
736        if (isRestrictedAndNotPinProtected()) {
737            addMessagePreference(R.string.wifi_empty_list_user_restricted);
738            return;
739        }
740        final int wifiState = mWifiManager.getWifiState();
741
742        switch (wifiState) {
743            case WifiManager.WIFI_STATE_ENABLED:
744                // AccessPoints are automatically sorted with TreeSet.
745                final Collection<AccessPoint> accessPoints = constructAccessPoints();
746                getPreferenceScreen().removeAll();
747                if(accessPoints.size() == 0) {
748                    addMessagePreference(R.string.wifi_empty_list_wifi_on);
749                }
750                for (AccessPoint accessPoint : accessPoints) {
751                    getPreferenceScreen().addPreference(accessPoint);
752                }
753                break;
754
755            case WifiManager.WIFI_STATE_ENABLING:
756                getPreferenceScreen().removeAll();
757                break;
758
759            case WifiManager.WIFI_STATE_DISABLING:
760                addMessagePreference(R.string.wifi_stopping);
761                break;
762
763            case WifiManager.WIFI_STATE_DISABLED:
764                setOffMessage();
765                break;
766        }
767    }
768
769    private void setOffMessage() {
770        if (mEmptyView != null) {
771            mEmptyView.setText(R.string.wifi_empty_list_wifi_off);
772            if (android.provider.Settings.Global.getInt(getActivity().getContentResolver(),
773                    android.provider.Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1) {
774                mEmptyView.append("\n\n");
775                int resId;
776                if (android.provider.Settings.Secure.isLocationProviderEnabled(
777                        getActivity().getContentResolver(), LocationManager.NETWORK_PROVIDER)) {
778                    resId = R.string.wifi_scan_notify_text_location_on;
779                } else {
780                    resId = R.string.wifi_scan_notify_text_location_off;
781                }
782                CharSequence charSeq = getText(resId);
783                mEmptyView.append(charSeq);
784            }
785        }
786        getPreferenceScreen().removeAll();
787    }
788
789    private void addMessagePreference(int messageId) {
790        if (mEmptyView != null) mEmptyView.setText(messageId);
791        getPreferenceScreen().removeAll();
792    }
793
794    /** Returns sorted list of access points */
795    private List<AccessPoint> constructAccessPoints() {
796        ArrayList<AccessPoint> accessPoints = new ArrayList<AccessPoint>();
797        /** Lookup table to more quickly update AccessPoints by only considering objects with the
798         * correct SSID.  Maps SSID -> List of AccessPoints with the given SSID.  */
799        Multimap<String, AccessPoint> apMap = new Multimap<String, AccessPoint>();
800
801        final List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
802        if (configs != null) {
803            for (WifiConfiguration config : configs) {
804                AccessPoint accessPoint = new AccessPoint(getActivity(), config);
805                accessPoint.update(mLastInfo, mLastState);
806                accessPoints.add(accessPoint);
807                apMap.put(accessPoint.ssid, accessPoint);
808            }
809        }
810
811        final List<ScanResult> results = mWifiManager.getScanResults();
812        if (results != null) {
813            for (ScanResult result : results) {
814                // Ignore hidden and ad-hoc networks.
815                if (result.SSID == null || result.SSID.length() == 0 ||
816                        result.capabilities.contains("[IBSS]")) {
817                    continue;
818                }
819
820                boolean found = false;
821                for (AccessPoint accessPoint : apMap.getAll(result.SSID)) {
822                    if (accessPoint.update(result))
823                        found = true;
824                }
825                if (!found) {
826                    AccessPoint accessPoint = new AccessPoint(getActivity(), result);
827                    accessPoints.add(accessPoint);
828                    apMap.put(accessPoint.ssid, accessPoint);
829                }
830            }
831        }
832
833        // Pre-sort accessPoints to speed preference insertion
834        Collections.sort(accessPoints);
835        return accessPoints;
836    }
837
838    /** A restricted multimap for use in constructAccessPoints */
839    private class Multimap<K,V> {
840        private final HashMap<K,List<V>> store = new HashMap<K,List<V>>();
841        /** retrieve a non-null list of values with key K */
842        List<V> getAll(K key) {
843            List<V> values = store.get(key);
844            return values != null ? values : Collections.<V>emptyList();
845        }
846
847        void put(K key, V val) {
848            List<V> curVals = store.get(key);
849            if (curVals == null) {
850                curVals = new ArrayList<V>(3);
851                store.put(key, curVals);
852            }
853            curVals.add(val);
854        }
855    }
856
857    private void handleEvent(Context context, Intent intent) {
858        String action = intent.getAction();
859        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
860            updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
861                    WifiManager.WIFI_STATE_UNKNOWN));
862        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action) ||
863                WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action) ||
864                WifiManager.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)) {
865                updateAccessPoints();
866        } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
867            //Ignore supplicant state changes when network is connected
868            //TODO: we should deprecate SUPPLICANT_STATE_CHANGED_ACTION and
869            //introduce a broadcast that combines the supplicant and network
870            //network state change events so the apps dont have to worry about
871            //ignoring supplicant state change when network is connected
872            //to get more fine grained information.
873            SupplicantState state = (SupplicantState) intent.getParcelableExtra(
874                    WifiManager.EXTRA_NEW_STATE);
875            if (!mConnected.get() && SupplicantState.isHandshakeState(state)) {
876                updateConnectionState(WifiInfo.getDetailedStateOf(state));
877             } else {
878                 // During a connect, we may have the supplicant
879                 // state change affect the detailed network state.
880                 // Make sure a lost connection is updated as well.
881                 updateConnectionState(null);
882             }
883        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
884            NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
885                    WifiManager.EXTRA_NETWORK_INFO);
886            mConnected.set(info.isConnected());
887            changeNextButtonState(info.isConnected());
888            updateAccessPoints();
889            updateConnectionState(info.getDetailedState());
890            if (mAutoFinishOnConnection && info.isConnected()) {
891                Activity activity = getActivity();
892                if (activity != null) {
893                    activity.setResult(Activity.RESULT_OK);
894                    activity.finish();
895                }
896                return;
897            }
898        } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
899            updateConnectionState(null);
900        }
901    }
902
903    private void updateConnectionState(DetailedState state) {
904        /* sticky broadcasts can call this when wifi is disabled */
905        if (!mWifiManager.isWifiEnabled()) {
906            mScanner.pause();
907            return;
908        }
909
910        if (state == DetailedState.OBTAINING_IPADDR) {
911            mScanner.pause();
912        } else {
913            mScanner.resume();
914        }
915
916        mLastInfo = mWifiManager.getConnectionInfo();
917        if (state != null) {
918            mLastState = state;
919        }
920
921        for (int i = getPreferenceScreen().getPreferenceCount() - 1; i >= 0; --i) {
922            // Maybe there's a WifiConfigPreference
923            Preference preference = getPreferenceScreen().getPreference(i);
924            if (preference instanceof AccessPoint) {
925                final AccessPoint accessPoint = (AccessPoint) preference;
926                accessPoint.update(mLastInfo, mLastState);
927            }
928        }
929    }
930
931    private void updateWifiState(int state) {
932        Activity activity = getActivity();
933        if (activity != null) {
934            activity.invalidateOptionsMenu();
935        }
936
937        switch (state) {
938            case WifiManager.WIFI_STATE_ENABLED:
939                mScanner.resume();
940                return; // not break, to avoid the call to pause() below
941
942            case WifiManager.WIFI_STATE_ENABLING:
943                addMessagePreference(R.string.wifi_starting);
944                break;
945
946            case WifiManager.WIFI_STATE_DISABLED:
947                setOffMessage();
948                break;
949        }
950
951        mLastInfo = null;
952        mLastState = null;
953        mScanner.pause();
954    }
955
956    private class Scanner extends Handler {
957        private int mRetry = 0;
958
959        void resume() {
960            if (!hasMessages(0)) {
961                sendEmptyMessage(0);
962            }
963        }
964
965        void forceScan() {
966            removeMessages(0);
967            sendEmptyMessage(0);
968        }
969
970        void pause() {
971            mRetry = 0;
972            removeMessages(0);
973        }
974
975        @Override
976        public void handleMessage(Message message) {
977            if (mWifiManager.startScan()) {
978                mRetry = 0;
979            } else if (++mRetry >= 3) {
980                mRetry = 0;
981                Activity activity = getActivity();
982                if (activity != null) {
983                    Toast.makeText(activity, R.string.wifi_fail_to_scan,
984                            Toast.LENGTH_LONG).show();
985                }
986                return;
987            }
988            sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS);
989        }
990    }
991
992    /**
993     * Renames/replaces "Next" button when appropriate. "Next" button usually exists in
994     * Wifi setup screens, not in usual wifi settings screen.
995     *
996     * @param connected true when the device is connected to a wifi network.
997     */
998    private void changeNextButtonState(boolean connected) {
999        if (mEnableNextOnConnection && hasNextButton()) {
1000            getNextButton().setEnabled(connected);
1001        }
1002    }
1003
1004    @Override
1005    public void onClick(DialogInterface dialogInterface, int button) {
1006        if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
1007            forget();
1008        } else if (button == WifiDialog.BUTTON_SUBMIT) {
1009            if (mDialog != null) {
1010                submit(mDialog.getController());
1011            }
1012        }
1013    }
1014
1015    /* package */ void submit(WifiConfigController configController) {
1016
1017        final WifiConfiguration config = configController.getConfig();
1018
1019        if (config == null) {
1020            if (mSelectedAccessPoint != null
1021                    && mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
1022                mWifiManager.connect(mSelectedAccessPoint.networkId,
1023                        mConnectListener);
1024            }
1025        } else if (config.networkId != INVALID_NETWORK_ID) {
1026            if (mSelectedAccessPoint != null) {
1027                mWifiManager.save(config, mSaveListener);
1028            }
1029        } else {
1030            if (configController.isEdit()) {
1031                mWifiManager.save(config, mSaveListener);
1032            } else {
1033                mWifiManager.connect(config, mConnectListener);
1034            }
1035        }
1036
1037        if (mWifiManager.isWifiEnabled()) {
1038            mScanner.resume();
1039        }
1040        updateAccessPoints();
1041    }
1042
1043    /* package */ void forget() {
1044        if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) {
1045            // Should not happen, but a monkey seems to triger it
1046            Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig());
1047            return;
1048        }
1049
1050        mWifiManager.forget(mSelectedAccessPoint.networkId, mForgetListener);
1051
1052        if (mWifiManager.isWifiEnabled()) {
1053            mScanner.resume();
1054        }
1055        updateAccessPoints();
1056
1057        // We need to rename/replace "Next" button in wifi setup context.
1058        changeNextButtonState(false);
1059    }
1060
1061    /**
1062     * Refreshes acccess points and ask Wifi module to scan networks again.
1063     */
1064    /* package */ void refreshAccessPoints() {
1065        if (mWifiManager.isWifiEnabled()) {
1066            mScanner.resume();
1067        }
1068
1069        getPreferenceScreen().removeAll();
1070    }
1071
1072    /**
1073     * Called when "add network" button is pressed.
1074     */
1075    /* package */ void onAddNetworkPressed() {
1076        // No exact access point is selected.
1077        mSelectedAccessPoint = null;
1078        showDialog(null, true);
1079    }
1080
1081    /* package */ int getAccessPointsCount() {
1082        final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
1083        if (wifiIsEnabled) {
1084            return getPreferenceScreen().getPreferenceCount();
1085        } else {
1086            return 0;
1087        }
1088    }
1089
1090    /**
1091     * Requests wifi module to pause wifi scan. May be ignored when the module is disabled.
1092     */
1093    /* package */ void pauseWifiScan() {
1094        if (mWifiManager.isWifiEnabled()) {
1095            mScanner.pause();
1096        }
1097    }
1098
1099    /**
1100     * Requests wifi module to resume wifi scan. May be ignored when the module is disabled.
1101     */
1102    /* package */ void resumeWifiScan() {
1103        if (mWifiManager.isWifiEnabled()) {
1104            mScanner.resume();
1105        }
1106    }
1107
1108    @Override
1109    protected int getHelpResource() {
1110        if (mSetupWizardMode) {
1111            return 0;
1112        }
1113        return R.string.help_url_wifi;
1114    }
1115
1116    /**
1117     * Used as the outer frame of all setup wizard pages that need to adjust their margins based
1118     * on the total size of the available display. (e.g. side margins set to 10% of total width.)
1119     */
1120    public static class ProportionalOuterFrame extends RelativeLayout {
1121        public ProportionalOuterFrame(Context context) {
1122            super(context);
1123        }
1124        public ProportionalOuterFrame(Context context, AttributeSet attrs) {
1125            super(context, attrs);
1126        }
1127        public ProportionalOuterFrame(Context context, AttributeSet attrs, int defStyle) {
1128            super(context, attrs, defStyle);
1129        }
1130
1131        /**
1132         * Set our margins and title area height proportionally to the available display size
1133         */
1134        @Override
1135        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
1136            int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
1137            int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
1138            final Resources resources = getContext().getResources();
1139            float titleHeight = resources.getFraction(R.dimen.setup_title_height, 1, 1);
1140            float sideMargin = resources.getFraction(R.dimen.setup_border_width, 1, 1);
1141            int bottom = resources.getDimensionPixelSize(R.dimen.setup_margin_bottom);
1142            setPaddingRelative(
1143                    (int) (parentWidth * sideMargin),
1144                    0,
1145                    (int) (parentWidth * sideMargin),
1146                    bottom);
1147            View title = findViewById(R.id.title_area);
1148            if (title != null) {
1149                title.setMinimumHeight((int) (parentHeight * titleHeight));
1150            }
1151            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
1152        }
1153    }
1154
1155}
1156