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