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