WifiSettings.java revision 4cfe39f5397d037d106abf07db31b0e01484bd92
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 android.app.Activity;
20import android.app.AlertDialog;
21import android.app.AppGlobals;
22import android.app.Dialog;
23import android.app.admin.DevicePolicyManager;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.ApplicationInfo;
31import android.content.pm.IPackageManager;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.res.Resources;
35import android.content.res.TypedArray;
36import android.net.ConnectivityManager;
37import android.net.NetworkInfo;
38import android.net.NetworkInfo.State;
39import android.net.wifi.WifiConfiguration;
40import android.net.wifi.WifiManager;
41import android.net.wifi.WpsInfo;
42import android.nfc.NfcAdapter;
43import android.os.Bundle;
44import android.os.HandlerThread;
45import android.os.Process;
46import android.os.RemoteException;
47import android.os.UserHandle;
48import android.provider.Settings;
49import android.support.v7.preference.Preference;
50import android.text.Spannable;
51import android.text.style.TextAppearanceSpan;
52import android.util.Log;
53import android.view.ContextMenu;
54import android.view.ContextMenu.ContextMenuInfo;
55import android.view.Gravity;
56import android.view.Menu;
57import android.view.MenuInflater;
58import android.view.MenuItem;
59import android.view.View;
60import android.widget.ProgressBar;
61import android.widget.TextView;
62import android.widget.TextView.BufferType;
63import android.widget.Toast;
64import com.android.internal.logging.MetricsLogger;
65import com.android.settings.LinkifyUtils;
66import com.android.settings.R;
67import com.android.settings.RestrictedSettingsFragment;
68import com.android.settings.SettingsActivity;
69import com.android.settings.dashboard.SummaryLoader;
70import com.android.settings.location.ScanningSettings;
71import com.android.settings.search.BaseSearchIndexProvider;
72import com.android.settings.search.Indexable;
73import com.android.settings.search.SearchIndexableRaw;
74import com.android.settings.wifi.AccessPointPreference.UserBadgeCache;
75import com.android.settingslib.wifi.AccessPoint;
76import com.android.settingslib.wifi.AccessPoint.AccessPointListener;
77import com.android.settingslib.wifi.WifiStatusTracker;
78import com.android.settingslib.wifi.WifiTracker;
79
80import java.util.ArrayList;
81import java.util.Collection;
82import java.util.List;
83
84import static android.os.UserManager.DISALLOW_CONFIG_WIFI;
85
86/**
87 * Two types of UI are provided here.
88 *
89 * The first is for "usual Settings", appearing as any other Setup fragment.
90 *
91 * The second is for Setup Wizard, with a simplified interface that hides the action bar
92 * and menus.
93 */
94public class WifiSettings extends RestrictedSettingsFragment
95        implements Indexable, WifiTracker.WifiListener, AccessPointListener,
96        WifiDialog.WifiDialogListener {
97
98    private static final String TAG = "WifiSettings";
99
100    /* package */ static final int MENU_ID_WPS_PBC = Menu.FIRST;
101    private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1;
102    private static final int MENU_ID_SAVED_NETWORK = Menu.FIRST + 2;
103    /* package */ static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3;
104    private static final int MENU_ID_ADVANCED = Menu.FIRST + 4;
105    private static final int MENU_ID_SCAN = Menu.FIRST + 5;
106    private static final int MENU_ID_CONNECT = Menu.FIRST + 6;
107    private static final int MENU_ID_FORGET = Menu.FIRST + 7;
108    private static final int MENU_ID_MODIFY = Menu.FIRST + 8;
109    private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9;
110
111    public static final int WIFI_DIALOG_ID = 1;
112    /* package */ static final int WPS_PBC_DIALOG_ID = 2;
113    private static final int WPS_PIN_DIALOG_ID = 3;
114    private static final int WRITE_NFC_DIALOG_ID = 6;
115
116    // Instance state keys
117    private static final String SAVE_DIALOG_MODE = "dialog_mode";
118    private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state";
119    private static final String SAVED_WIFI_NFC_DIALOG_STATE = "wifi_nfc_dlg_state";
120
121    private static boolean savedNetworksExist;
122
123    protected WifiManager mWifiManager;
124    private WifiManager.ActionListener mConnectListener;
125    private WifiManager.ActionListener mSaveListener;
126    private WifiManager.ActionListener mForgetListener;
127
128    private WifiEnabler mWifiEnabler;
129    // An access point being editted is stored here.
130    private AccessPoint mSelectedAccessPoint;
131
132    private WifiDialog mDialog;
133    private WriteWifiConfigToNfcDialog mWifiToNfcDialog;
134
135    private TextView mEmptyView;
136    private ProgressBar mProgressHeader;
137
138    // this boolean extra specifies whether to disable the Next button when not connected. Used by
139    // account creation outside of setup wizard.
140    private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
141    // This string extra specifies a network to open the connect dialog on, so the user can enter
142    // network credentials.  This is used by quick settings for secured networks.
143    private static final String EXTRA_START_CONNECT_SSID = "wifi_start_connect_ssid";
144
145    // should Next button only be enabled when we have a connection?
146    private boolean mEnableNextOnConnection;
147
148    // Save the dialog details
149    private int mDialogMode;
150    private AccessPoint mDlgAccessPoint;
151    private Bundle mAccessPointSavedState;
152    private Bundle mWifiNfcDialogSavedState;
153
154    private WifiTracker mWifiTracker;
155    private String mOpenSsid;
156
157    private HandlerThread mBgThread;
158
159    private UserBadgeCache mUserBadgeCache;
160
161    /* End of "used in Wifi Setup context" */
162
163    public WifiSettings() {
164        super(DISALLOW_CONFIG_WIFI);
165    }
166
167    @Override
168    public void onViewCreated(View view, Bundle savedInstanceState) {
169        super.onViewCreated(view, savedInstanceState);
170        final Activity activity = getActivity();
171        if (activity != null) {
172            mProgressHeader = (ProgressBar) setPinnedHeaderView(R.layout.wifi_progress_header);
173        }
174    }
175
176    @Override
177    public void onCreate(Bundle icicle) {
178        super.onCreate(icicle);
179        addPreferencesFromResource(R.xml.wifi_settings);
180        mUserBadgeCache = new UserBadgeCache(getPackageManager());
181
182        mBgThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
183        mBgThread.start();
184    }
185
186    @Override
187    public void onDestroy() {
188        mBgThread.quit();
189        super.onDestroy();
190    }
191
192    @Override
193    public void onActivityCreated(Bundle savedInstanceState) {
194        super.onActivityCreated(savedInstanceState);
195
196        mWifiTracker =
197                new WifiTracker(getActivity(), this, mBgThread.getLooper(), true, true, false);
198        mWifiManager = mWifiTracker.getManager();
199
200        mConnectListener = new WifiManager.ActionListener() {
201                                   @Override
202                                   public void onSuccess() {
203                                   }
204                                   @Override
205                                   public void onFailure(int reason) {
206                                       Activity activity = getActivity();
207                                       if (activity != null) {
208                                           Toast.makeText(activity,
209                                                R.string.wifi_failed_connect_message,
210                                                Toast.LENGTH_SHORT).show();
211                                       }
212                                   }
213                               };
214
215        mSaveListener = new WifiManager.ActionListener() {
216                                @Override
217                                public void onSuccess() {
218                                }
219                                @Override
220                                public void onFailure(int reason) {
221                                    Activity activity = getActivity();
222                                    if (activity != null) {
223                                        Toast.makeText(activity,
224                                            R.string.wifi_failed_save_message,
225                                            Toast.LENGTH_SHORT).show();
226                                    }
227                                }
228                            };
229
230        mForgetListener = new WifiManager.ActionListener() {
231                                   @Override
232                                   public void onSuccess() {
233                                   }
234                                   @Override
235                                   public void onFailure(int reason) {
236                                       Activity activity = getActivity();
237                                       if (activity != null) {
238                                           Toast.makeText(activity,
239                                               R.string.wifi_failed_forget_message,
240                                               Toast.LENGTH_SHORT).show();
241                                       }
242                                   }
243                               };
244
245        if (savedInstanceState != null) {
246            mDialogMode = savedInstanceState.getInt(SAVE_DIALOG_MODE);
247            if (savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) {
248                mAccessPointSavedState =
249                    savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
250            }
251
252            if (savedInstanceState.containsKey(SAVED_WIFI_NFC_DIALOG_STATE)) {
253                mWifiNfcDialogSavedState =
254                    savedInstanceState.getBundle(SAVED_WIFI_NFC_DIALOG_STATE);
255            }
256        }
257
258        // if we're supposed to enable/disable the Next button based on our current connection
259        // state, start it off in the right state
260        Intent intent = getActivity().getIntent();
261        mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
262
263        if (mEnableNextOnConnection) {
264            if (hasNextButton()) {
265                final ConnectivityManager connectivity = (ConnectivityManager)
266                        getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
267                if (connectivity != null) {
268                    NetworkInfo info = connectivity.getNetworkInfo(
269                            ConnectivityManager.TYPE_WIFI);
270                    changeNextButtonState(info.isConnected());
271                }
272            }
273        }
274
275        mEmptyView = initEmptyView();
276        registerForContextMenu(getListView());
277        setHasOptionsMenu(true);
278
279        if (intent.hasExtra(EXTRA_START_CONNECT_SSID)) {
280            mOpenSsid = intent.getStringExtra(EXTRA_START_CONNECT_SSID);
281            onAccessPointsChanged();
282        }
283    }
284
285    @Override
286    public void onDestroyView() {
287        super.onDestroyView();
288
289        if (mWifiEnabler != null) {
290            mWifiEnabler.teardownSwitchBar();
291        }
292    }
293
294    @Override
295    public void onStart() {
296        super.onStart();
297
298        // On/off switch is hidden for Setup Wizard (returns null)
299        mWifiEnabler = createWifiEnabler();
300    }
301
302    /**
303     * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard)
304     */
305    /* package */ WifiEnabler createWifiEnabler() {
306        final SettingsActivity activity = (SettingsActivity) getActivity();
307        return new WifiEnabler(activity, activity.getSwitchBar());
308    }
309
310    @Override
311    public void onResume() {
312        final Activity activity = getActivity();
313        super.onResume();
314        removePreference("dummy");
315        if (mWifiEnabler != null) {
316            mWifiEnabler.resume(activity);
317        }
318
319        mWifiTracker.startTracking();
320    }
321
322    @Override
323    public void onPause() {
324        super.onPause();
325        if (mWifiEnabler != null) {
326            mWifiEnabler.pause();
327        }
328
329        mWifiTracker.stopTracking();
330    }
331
332    @Override
333    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
334        // If the user is not allowed to configure wifi, do not show the menu.
335        if (isUiRestricted()) return;
336
337        addOptionsMenuItems(menu);
338        super.onCreateOptionsMenu(menu, inflater);
339    }
340
341    /**
342     * @param menu
343     */
344    void addOptionsMenuItems(Menu menu) {
345        final boolean wifiIsEnabled = mWifiTracker.isWifiEnabled();
346        TypedArray ta = getActivity().getTheme().obtainStyledAttributes(
347                new int[] {R.attr.ic_menu_add, R.attr.ic_wps});
348        menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
349                .setIcon(ta.getDrawable(0))
350                .setEnabled(wifiIsEnabled)
351                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
352        if (savedNetworksExist) {
353            menu.add(Menu.NONE, MENU_ID_SAVED_NETWORK, 0, R.string.wifi_saved_access_points_label)
354                    .setIcon(ta.getDrawable(0))
355                    .setEnabled(wifiIsEnabled)
356                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
357        }
358        menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.menu_stats_refresh)
359               .setEnabled(wifiIsEnabled)
360               .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
361        menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced)
362                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
363        ta.recycle();
364    }
365
366    @Override
367    protected int getMetricsCategory() {
368        return MetricsLogger.WIFI;
369    }
370
371    @Override
372    public void onSaveInstanceState(Bundle outState) {
373        super.onSaveInstanceState(outState);
374
375        // If the dialog is showing, save its state.
376        if (mDialog != null && mDialog.isShowing()) {
377            outState.putInt(SAVE_DIALOG_MODE, mDialogMode);
378            if (mDlgAccessPoint != null) {
379                mAccessPointSavedState = new Bundle();
380                mDlgAccessPoint.saveWifiState(mAccessPointSavedState);
381                outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState);
382            }
383        }
384
385        if (mWifiToNfcDialog != null && mWifiToNfcDialog.isShowing()) {
386            Bundle savedState = new Bundle();
387            mWifiToNfcDialog.saveState(savedState);
388            outState.putBundle(SAVED_WIFI_NFC_DIALOG_STATE, savedState);
389        }
390    }
391
392    @Override
393    public boolean onOptionsItemSelected(MenuItem item) {
394        // If the user is not allowed to configure wifi, do not handle menu selections.
395        if (isUiRestricted()) return false;
396
397        switch (item.getItemId()) {
398            case MENU_ID_WPS_PBC:
399                showDialog(WPS_PBC_DIALOG_ID);
400                return true;
401                /*
402            case MENU_ID_P2P:
403                if (getActivity() instanceof SettingsActivity) {
404                    ((SettingsActivity) getActivity()).startPreferencePanel(
405                            WifiP2pSettings.class.getCanonicalName(),
406                            null,
407                            R.string.wifi_p2p_settings_title, null,
408                            this, 0);
409                } else {
410                    startFragment(this, WifiP2pSettings.class.getCanonicalName(),
411                            R.string.wifi_p2p_settings_title, -1, null);
412                }
413                return true;
414                */
415            case MENU_ID_WPS_PIN:
416                showDialog(WPS_PIN_DIALOG_ID);
417                return true;
418            case MENU_ID_SCAN:
419                MetricsLogger.action(getActivity(), MetricsLogger.ACTION_WIFI_FORCE_SCAN);
420                mWifiTracker.forceScan();
421                return true;
422            case MENU_ID_ADD_NETWORK:
423                if (mWifiTracker.isWifiEnabled()) {
424                    onAddNetworkPressed();
425                }
426                return true;
427            case MENU_ID_SAVED_NETWORK:
428                if (getActivity() instanceof SettingsActivity) {
429                    ((SettingsActivity) getActivity()).startPreferencePanel(
430                            SavedAccessPointsWifiSettings.class.getCanonicalName(), null,
431                            R.string.wifi_saved_access_points_titlebar, null, this, 0);
432                } else {
433                    startFragment(this, SavedAccessPointsWifiSettings.class.getCanonicalName(),
434                            R.string.wifi_saved_access_points_titlebar,
435                            -1 /* Do not request a result */, null);
436                }
437                return true;
438            case MENU_ID_ADVANCED:
439                if (getActivity() instanceof SettingsActivity) {
440                    ((SettingsActivity) getActivity()).startPreferencePanel(
441                            AdvancedWifiSettings.class.getCanonicalName(), null,
442                            R.string.wifi_advanced_titlebar, null, this, 0);
443                } else {
444                    startFragment(this, AdvancedWifiSettings.class.getCanonicalName(),
445                            R.string.wifi_advanced_titlebar, -1 /* Do not request a results */,
446                            null);
447                }
448                return true;
449        }
450        return super.onOptionsItemSelected(item);
451    }
452
453    @Override
454    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
455            Preference preference = (Preference) view.getTag();
456
457            if (preference instanceof AccessPointPreference) {
458                mSelectedAccessPoint = ((AccessPointPreference) preference).getAccessPoint();
459                menu.setHeaderTitle(mSelectedAccessPoint.getSsid());
460                if (mSelectedAccessPoint.isConnectable()) {
461                    menu.add(Menu.NONE, MENU_ID_CONNECT, 0, R.string.wifi_menu_connect);
462                }
463
464                WifiConfiguration config = mSelectedAccessPoint.getConfig();
465                // Some configs are ineditable
466                if (isEditabilityLockedDown(getActivity(), config)) {
467                    return;
468                }
469
470                if (mSelectedAccessPoint.isSaved() || mSelectedAccessPoint.isEphemeral()) {
471                    // Allow forgetting a network if either the network is saved or ephemerally
472                    // connected. (In the latter case, "forget" blacklists the network so it won't
473                    // be used again, ephemerally).
474                    menu.add(Menu.NONE, MENU_ID_FORGET, 0, R.string.wifi_menu_forget);
475                }
476                if (mSelectedAccessPoint.isSaved()) {
477                    menu.add(Menu.NONE, MENU_ID_MODIFY, 0, R.string.wifi_menu_modify);
478                    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
479                    if (nfcAdapter != null && nfcAdapter.isEnabled() &&
480                            mSelectedAccessPoint.getSecurity() != AccessPoint.SECURITY_NONE) {
481                        // Only allow writing of NFC tags for password-protected networks.
482                        menu.add(Menu.NONE, MENU_ID_WRITE_NFC, 0, R.string.wifi_menu_write_to_nfc);
483                    }
484                }
485            }
486    }
487
488    @Override
489    public boolean onContextItemSelected(MenuItem item) {
490        if (mSelectedAccessPoint == null) {
491            return super.onContextItemSelected(item);
492        }
493        switch (item.getItemId()) {
494            case MENU_ID_CONNECT: {
495                if (mSelectedAccessPoint.isSaved()) {
496                    connect(mSelectedAccessPoint.getConfig());
497                } else if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE) {
498                    /** Bypass dialog for unsecured networks */
499                    mSelectedAccessPoint.generateOpenNetworkConfig();
500                    connect(mSelectedAccessPoint.getConfig());
501                } else {
502                    showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT);
503                }
504                return true;
505            }
506            case MENU_ID_FORGET: {
507                forget();
508                return true;
509            }
510            case MENU_ID_MODIFY: {
511                showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_MODIFY);
512                return true;
513            }
514            case MENU_ID_WRITE_NFC:
515                showDialog(WRITE_NFC_DIALOG_ID);
516                return true;
517
518        }
519        return super.onContextItemSelected(item);
520    }
521
522    @Override
523    public boolean onPreferenceTreeClick(Preference preference) {
524        if (preference instanceof AccessPointPreference) {
525            mSelectedAccessPoint = ((AccessPointPreference) preference).getAccessPoint();
526            /** Bypass dialog for unsecured, unsaved, and inactive networks */
527            if (mSelectedAccessPoint.getSecurity() == AccessPoint.SECURITY_NONE &&
528                    !mSelectedAccessPoint.isSaved() && !mSelectedAccessPoint.isActive()) {
529                mSelectedAccessPoint.generateOpenNetworkConfig();
530                if (!savedNetworksExist) {
531                    savedNetworksExist = true;
532                    getActivity().invalidateOptionsMenu();
533                }
534                connect(mSelectedAccessPoint.getConfig());
535            } else if (mSelectedAccessPoint.isSaved()){
536                showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_VIEW);
537            } else {
538                showDialog(mSelectedAccessPoint, WifiConfigUiBase.MODE_CONNECT);
539            }
540        } else {
541            return super.onPreferenceTreeClick(preference);
542        }
543        return true;
544    }
545
546    private void showDialog(AccessPoint accessPoint, int dialogMode) {
547        if (accessPoint != null) {
548            WifiConfiguration config = accessPoint.getConfig();
549            if (isEditabilityLockedDown(getActivity(), config) && accessPoint.isActive()) {
550                final int userId = UserHandle.getUserId(config.creatorUid);
551                final PackageManager pm = getActivity().getPackageManager();
552                final IPackageManager ipm = AppGlobals.getPackageManager();
553                String appName = pm.getNameForUid(config.creatorUid);
554                try {
555                    final ApplicationInfo appInfo = ipm.getApplicationInfo(appName, /* flags */ 0,
556                            userId);
557                    final CharSequence label = pm.getApplicationLabel(appInfo);
558                    if (label != null) {
559                        appName = label.toString();
560                    }
561                } catch (RemoteException e) {
562                    // leave appName as packageName
563                }
564                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
565                builder.setTitle(accessPoint.getSsid())
566                        .setMessage(getString(R.string.wifi_alert_lockdown_by_device_owner,
567                                appName))
568                        .setPositiveButton(android.R.string.ok, null)
569                        .show();
570                return;
571            }
572        }
573
574        if (mDialog != null) {
575            removeDialog(WIFI_DIALOG_ID);
576            mDialog = null;
577        }
578
579        // Save the access point and edit mode
580        mDlgAccessPoint = accessPoint;
581        mDialogMode = dialogMode;
582
583        showDialog(WIFI_DIALOG_ID);
584    }
585
586    @Override
587    public Dialog onCreateDialog(int dialogId) {
588        switch (dialogId) {
589            case WIFI_DIALOG_ID:
590                AccessPoint ap = mDlgAccessPoint; // For manual launch
591                if (ap == null) { // For re-launch from saved state
592                    if (mAccessPointSavedState != null) {
593                        ap = new AccessPoint(getActivity(), mAccessPointSavedState);
594                        // For repeated orientation changes
595                        mDlgAccessPoint = ap;
596                        // Reset the saved access point data
597                        mAccessPointSavedState = null;
598                    }
599                }
600                // If it's null, fine, it's for Add Network
601                mSelectedAccessPoint = ap;
602                final boolean hideForget = (ap == null || isEditabilityLockedDown(getActivity(),
603                        ap.getConfig()));
604                mDialog = new WifiDialog(getActivity(), this, ap, mDialogMode,
605                        /* no hide submit/connect */ false,
606                        /* hide forget if config locked down */ hideForget);
607                return mDialog;
608            case WPS_PBC_DIALOG_ID:
609                return new WpsDialog(getActivity(), WpsInfo.PBC);
610            case WPS_PIN_DIALOG_ID:
611                return new WpsDialog(getActivity(), WpsInfo.DISPLAY);
612            case WRITE_NFC_DIALOG_ID:
613                if (mSelectedAccessPoint != null) {
614                    mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(
615                            getActivity(), mSelectedAccessPoint.getConfig().networkId,
616                            mSelectedAccessPoint.getSecurity(),
617                            mWifiManager);
618                } else if (mWifiNfcDialogSavedState != null) {
619                    mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(
620                            getActivity(), mWifiNfcDialogSavedState, mWifiManager);
621                }
622
623                return mWifiToNfcDialog;
624        }
625        return super.onCreateDialog(dialogId);
626    }
627
628    /**
629     * Shows the latest access points available with supplemental information like
630     * the strength of network and the security for it.
631     */
632    @Override
633    public void onAccessPointsChanged() {
634        // Safeguard from some delayed event handling
635        if (getActivity() == null) return;
636
637        if (isUiRestricted()) {
638            addMessagePreference(R.string.wifi_empty_list_user_restricted);
639            return;
640        }
641        final int wifiState = mWifiManager.getWifiState();
642
643        switch (wifiState) {
644            case WifiManager.WIFI_STATE_ENABLED:
645                // AccessPoints are automatically sorted with TreeSet.
646                final Collection<AccessPoint> accessPoints =
647                        mWifiTracker.getAccessPoints();
648                getPreferenceScreen().removeAll();
649
650                boolean hasAvailableAccessPoints = false;
651                int index = 0;
652                for (AccessPoint accessPoint : accessPoints) {
653                    // Ignore access points that are out of range.
654                    if (accessPoint.getLevel() != -1) {
655                        hasAvailableAccessPoints = true;
656                        if (accessPoint.getTag() != null) {
657                            final Preference pref = (Preference) accessPoint.getTag();
658                            pref.setOrder(index++);
659                            getPreferenceScreen().addPreference(pref);
660                            continue;
661                        }
662                        AccessPointPreference preference = new AccessPointPreference(accessPoint,
663                                getPrefContext(), mUserBadgeCache, false, this);
664                        preference.setOrder(index++);
665
666                        if (mOpenSsid != null && mOpenSsid.equals(accessPoint.getSsidStr())
667                                && !accessPoint.isSaved()
668                                && accessPoint.getSecurity() != AccessPoint.SECURITY_NONE) {
669                            onPreferenceTreeClick(preference);
670                            mOpenSsid = null;
671                        }
672                        getPreferenceScreen().addPreference(preference);
673                        accessPoint.setListener(this);
674                    }
675                }
676                if (!hasAvailableAccessPoints) {
677                    setProgressBarVisible(true);
678                    addMessagePreference(R.string.wifi_empty_list_wifi_on);
679                } else {
680                    setProgressBarVisible(false);
681                }
682                break;
683
684            case WifiManager.WIFI_STATE_ENABLING:
685                getPreferenceScreen().removeAll();
686                setProgressBarVisible(true);
687                break;
688
689            case WifiManager.WIFI_STATE_DISABLING:
690                addMessagePreference(R.string.wifi_stopping);
691                setProgressBarVisible(true);
692                break;
693
694            case WifiManager.WIFI_STATE_DISABLED:
695                setOffMessage();
696                setProgressBarVisible(false);
697                break;
698        }
699        // Update "Saved Networks" menu option.
700        if (savedNetworksExist != mWifiTracker.doSavedNetworksExist()) {
701            savedNetworksExist = !savedNetworksExist;
702            getActivity().invalidateOptionsMenu();
703        }
704    }
705
706    protected TextView initEmptyView() {
707        TextView emptyView = (TextView) getActivity().findViewById(android.R.id.empty);
708        emptyView.setGravity(Gravity.START | Gravity.CENTER_VERTICAL);
709        setEmptyView(emptyView);
710        return emptyView;
711    }
712
713    private void setOffMessage() {
714        if (mEmptyView == null) {
715            return;
716        }
717
718        final CharSequence briefText = getText(R.string.wifi_empty_list_wifi_off);
719
720        // Don't use WifiManager.isScanAlwaysAvailable() to check the Wi-Fi scanning mode. Instead,
721        // read the system settings directly. Because when the device is in Airplane mode, even if
722        // Wi-Fi scanning mode is on, WifiManager.isScanAlwaysAvailable() still returns "off".
723        final ContentResolver resolver = getActivity().getContentResolver();
724        final boolean wifiScanningMode = Settings.Global.getInt(
725                resolver, Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1;
726
727        if (isUiRestricted() || !wifiScanningMode) {
728            // Show only the brief text if the user is not allowed to configure scanning settings,
729            // or the scanning mode has been turned off.
730            mEmptyView.setText(briefText, BufferType.SPANNABLE);
731        } else {
732            // Append the description of scanning settings with link.
733            final StringBuilder contentBuilder = new StringBuilder();
734            contentBuilder.append(briefText);
735            contentBuilder.append("\n\n");
736            contentBuilder.append(getText(R.string.wifi_scan_notify_text));
737            LinkifyUtils.linkify(mEmptyView, contentBuilder, new LinkifyUtils.OnClickListener() {
738                @Override
739                public void onClick() {
740                    final SettingsActivity activity =
741                            (SettingsActivity) WifiSettings.this.getActivity();
742                    activity.startPreferencePanel(ScanningSettings.class.getName(), null,
743                            R.string.location_scanning_screen_title, null, null, 0);
744                }
745            });
746        }
747        // Embolden and enlarge the brief description anyway.
748        Spannable boldSpan = (Spannable) mEmptyView.getText();
749        boldSpan.setSpan(
750                new TextAppearanceSpan(getActivity(), android.R.style.TextAppearance_Medium), 0,
751                briefText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
752        getPreferenceScreen().removeAll();
753    }
754
755    private void addMessagePreference(int messageId) {
756        if (mEmptyView != null) mEmptyView.setText(messageId);
757        getPreferenceScreen().removeAll();
758    }
759
760    protected void setProgressBarVisible(boolean visible) {
761        if (mProgressHeader != null) {
762            mProgressHeader.setVisibility(visible ? View.VISIBLE : View.GONE);
763        }
764    }
765
766    @Override
767    public void onWifiStateChanged(int state) {
768        Activity activity = getActivity();
769        if (activity != null) {
770            activity.invalidateOptionsMenu();
771        }
772
773        switch (state) {
774            case WifiManager.WIFI_STATE_ENABLING:
775                addMessagePreference(R.string.wifi_starting);
776                setProgressBarVisible(true);
777                break;
778
779            case WifiManager.WIFI_STATE_DISABLED:
780                setOffMessage();
781                setProgressBarVisible(false);
782                break;
783        }
784    }
785
786    @Override
787    public void onConnectedChanged() {
788        changeNextButtonState(mWifiTracker.isConnected());
789    }
790
791    /**
792     * Renames/replaces "Next" button when appropriate. "Next" button usually exists in
793     * Wifi setup screens, not in usual wifi settings screen.
794     *
795     * @param enabled true when the device is connected to a wifi network.
796     */
797    private void changeNextButtonState(boolean enabled) {
798        if (mEnableNextOnConnection && hasNextButton()) {
799            getNextButton().setEnabled(enabled);
800        }
801    }
802
803    @Override
804    public void onForget(WifiDialog dialog) {
805        forget();
806    }
807
808    @Override
809    public void onSubmit(WifiDialog dialog) {
810        if (mDialog != null) {
811            submit(mDialog.getController());
812        }
813    }
814
815    /* package */ void submit(WifiConfigController configController) {
816
817        final WifiConfiguration config = configController.getConfig();
818
819        if (config == null) {
820            if (mSelectedAccessPoint != null
821                    && mSelectedAccessPoint.isSaved()) {
822                connect(mSelectedAccessPoint.getConfig());
823            }
824        } else if (configController.getMode() == WifiConfigUiBase.MODE_MODIFY) {
825            mWifiManager.save(config, mSaveListener);
826        } else {
827            mWifiManager.save(config, mSaveListener);
828            if (mSelectedAccessPoint != null) { // Not an "Add network"
829                connect(config);
830            }
831        }
832
833        mWifiTracker.resumeScanning();
834    }
835
836    /* package */ void forget() {
837        MetricsLogger.action(getActivity(), MetricsLogger.ACTION_WIFI_FORGET);
838        if (!mSelectedAccessPoint.isSaved()) {
839            if (mSelectedAccessPoint.getNetworkInfo() != null &&
840                    mSelectedAccessPoint.getNetworkInfo().getState() != State.DISCONNECTED) {
841                // Network is active but has no network ID - must be ephemeral.
842                mWifiManager.disableEphemeralNetwork(
843                        AccessPoint.convertToQuotedString(mSelectedAccessPoint.getSsidStr()));
844            } else {
845                // Should not happen, but a monkey seems to trigger it
846                Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig());
847                return;
848            }
849        } else {
850            mWifiManager.forget(mSelectedAccessPoint.getConfig().networkId, mForgetListener);
851        }
852
853        mWifiTracker.resumeScanning();
854
855        // We need to rename/replace "Next" button in wifi setup context.
856        changeNextButtonState(false);
857    }
858
859    protected void connect(final WifiConfiguration config) {
860        MetricsLogger.action(getActivity(), MetricsLogger.ACTION_WIFI_CONNECT);
861        mWifiManager.connect(config, mConnectListener);
862    }
863
864    protected void connect(final int networkId) {
865        MetricsLogger.action(getActivity(), MetricsLogger.ACTION_WIFI_CONNECT);
866        mWifiManager.connect(networkId, mConnectListener);
867    }
868
869    /**
870     * Refreshes acccess points and ask Wifi module to scan networks again.
871     */
872    /* package */ void refreshAccessPoints() {
873        mWifiTracker.resumeScanning();
874
875        getPreferenceScreen().removeAll();
876    }
877
878    /**
879     * Called when "add network" button is pressed.
880     */
881    /* package */ void onAddNetworkPressed() {
882        MetricsLogger.action(getActivity(), MetricsLogger.ACTION_WIFI_ADD_NETWORK);
883        // No exact access point is selected.
884        mSelectedAccessPoint = null;
885        showDialog(null, WifiConfigUiBase.MODE_CONNECT);
886    }
887
888    /* package */ int getAccessPointsCount() {
889        final boolean wifiIsEnabled = mWifiTracker.isWifiEnabled();
890        if (wifiIsEnabled) {
891            return getPreferenceScreen().getPreferenceCount();
892        } else {
893            return 0;
894        }
895    }
896
897    /**
898     * Requests wifi module to pause wifi scan. May be ignored when the module is disabled.
899     */
900    /* package */ void pauseWifiScan() {
901        mWifiTracker.pauseScanning();
902    }
903
904    /**
905     * Requests wifi module to resume wifi scan. May be ignored when the module is disabled.
906     */
907    /* package */ void resumeWifiScan() {
908        mWifiTracker.resumeScanning();
909    }
910
911    @Override
912    protected int getHelpResource() {
913        return R.string.help_url_wifi;
914    }
915
916    @Override
917    public void onAccessPointChanged(AccessPoint accessPoint) {
918        ((AccessPointPreference) accessPoint.getTag()).refresh();
919    }
920
921    @Override
922    public void onLevelChanged(AccessPoint accessPoint) {
923        ((AccessPointPreference) accessPoint.getTag()).onLevelChanged();
924    }
925
926    public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
927        new BaseSearchIndexProvider() {
928            @Override
929            public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) {
930                final List<SearchIndexableRaw> result = new ArrayList<SearchIndexableRaw>();
931                final Resources res = context.getResources();
932
933                // Add fragment title
934                SearchIndexableRaw data = new SearchIndexableRaw(context);
935                data.title = res.getString(R.string.wifi_settings);
936                data.screenTitle = res.getString(R.string.wifi_settings);
937                data.keywords = res.getString(R.string.keywords_wifi);
938                result.add(data);
939
940                // Add saved Wi-Fi access points
941                final Collection<AccessPoint> accessPoints =
942                        WifiTracker.getCurrentAccessPoints(context, true, false, false);
943                for (AccessPoint accessPoint : accessPoints) {
944                    data = new SearchIndexableRaw(context);
945                    data.title = accessPoint.getSsidStr();
946                    data.screenTitle = res.getString(R.string.wifi_settings);
947                    data.enabled = enabled;
948                    result.add(data);
949                }
950
951                return result;
952            }
953        };
954
955    /**
956     * Returns true if the config is not editable through Settings.
957     * @param context Context of caller
958     * @param config The WiFi config.
959     * @return true if the config is not editable through Settings.
960     */
961    static boolean isEditabilityLockedDown(Context context, WifiConfiguration config) {
962        return !canModifyNetwork(context, config);
963    }
964
965    /**
966     * This method is a stripped version of WifiConfigStore.canModifyNetwork.
967     * TODO: refactor to have only one method.
968     * @param context Context of caller
969     * @param config The WiFi config.
970     * @return true if Settings can modify the config.
971     */
972    static boolean canModifyNetwork(Context context, WifiConfiguration config) {
973        if (config == null) {
974            return true;
975        }
976
977        final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
978                Context.DEVICE_POLICY_SERVICE);
979
980        // Check if device has DPM capability. If it has and dpm is still null, then we
981        // treat this case with suspicion and bail out.
982        final PackageManager pm = context.getPackageManager();
983        if (pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN) && dpm == null) {
984            return false;
985        }
986
987        boolean isConfigEligibleForLockdown = false;
988        if (dpm != null) {
989            final ComponentName deviceOwner = dpm.getDeviceOwnerComponentOnAnyUser();
990            if (deviceOwner != null) {
991                final int deviceOwnerUserId = dpm.getDeviceOwnerUserId();
992                try {
993                    final int deviceOwnerUid = pm.getPackageUid(deviceOwner.getPackageName(),
994                            deviceOwnerUserId);
995                    isConfigEligibleForLockdown = deviceOwnerUid == config.creatorUid;
996                } catch (NameNotFoundException e) {
997                    // don't care
998                }
999            }
1000        }
1001        if (!isConfigEligibleForLockdown) {
1002            return true;
1003        }
1004
1005        final ContentResolver resolver = context.getContentResolver();
1006        final boolean isLockdownFeatureEnabled = Settings.Global.getInt(resolver,
1007                Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) != 0;
1008        return !isLockdownFeatureEnabled;
1009    }
1010
1011    private static class SummaryProvider extends BroadcastReceiver
1012            implements SummaryLoader.SummaryProvider {
1013
1014        private final Context mContext;
1015        private final WifiManager mWifiManager;
1016        private final WifiStatusTracker mWifiTracker;
1017        private final SummaryLoader mSummaryLoader;
1018
1019        public SummaryProvider(Context context, SummaryLoader summaryLoader) {
1020            mContext = context;
1021            mSummaryLoader = summaryLoader;
1022            mWifiManager = context.getSystemService(WifiManager.class);
1023            mWifiTracker = new WifiStatusTracker(mWifiManager);
1024        }
1025
1026        private CharSequence getSummary() {
1027            if (!mWifiTracker.enabled) {
1028                return mContext.getString(R.string.disabled);
1029            }
1030            if (!mWifiTracker.connected) {
1031                return mContext.getString(R.string.disconnected);
1032            }
1033            return mWifiTracker.ssid;
1034        }
1035
1036        @Override
1037        public void setListening(boolean listening) {
1038            if (listening) {
1039                IntentFilter filter = new IntentFilter();
1040                filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
1041                filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
1042                filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
1043                mContext.registerReceiver(this, filter);
1044            } else {
1045                mContext.unregisterReceiver(this);
1046            }
1047        }
1048
1049        @Override
1050        public void onReceive(Context context, Intent intent) {
1051            mWifiTracker.handleBroadcast(intent);
1052            mSummaryLoader.setSummary(this, getSummary());
1053        }
1054    }
1055
1056    public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY
1057            = new SummaryLoader.SummaryProviderFactory() {
1058        @Override
1059        public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity,
1060                                                                   SummaryLoader summaryLoader) {
1061            return new SummaryProvider(activity, summaryLoader);
1062        }
1063    };
1064}
1065