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