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