2 * Copyright (C) 2017 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package com.android.settings.wifi.details;
18 import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
19 import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
20 import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
21 import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
23 import android.app.Activity;
24 import android.app.AlertDialog;
25 import android.app.settings.SettingsEnums;
26 import android.content.BroadcastReceiver;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.graphics.Bitmap;
31 import android.graphics.drawable.BitmapDrawable;
32 import android.graphics.drawable.Drawable;
33 import android.graphics.drawable.VectorDrawable;
34 import android.net.ConnectivityManager;
35 import android.net.ConnectivityManager.NetworkCallback;
36 import android.net.LinkAddress;
37 import android.net.LinkProperties;
38 import android.net.Network;
39 import android.net.NetworkCapabilities;
40 import android.net.NetworkInfo;
41 import android.net.NetworkRequest;
42 import android.net.NetworkUtils;
43 import android.net.RouteInfo;
44 import android.net.wifi.WifiConfiguration;
45 import android.net.wifi.WifiInfo;
46 import android.net.wifi.WifiManager;
47 import android.os.CountDownTimer;
48 import android.os.Handler;
49 import android.text.TextUtils;
50 import android.util.FeatureFlagUtils;
51 import android.util.Log;
52 import android.widget.ImageView;
53 import android.widget.Toast;
55 import androidx.annotation.VisibleForTesting;
56 import androidx.core.text.BidiFormatter;
57 import androidx.fragment.app.Fragment;
58 import androidx.preference.Preference;
59 import androidx.preference.PreferenceCategory;
60 import androidx.preference.PreferenceFragmentCompat;
61 import androidx.preference.PreferenceScreen;
63 import com.android.settings.R;
64 import com.android.settings.Utils;
65 import com.android.settings.core.FeatureFlags;
66 import com.android.settings.core.PreferenceControllerMixin;
67 import com.android.settings.datausage.WifiDataUsageSummaryPreferenceController;
68 import com.android.settings.development.featureflags.FeatureFlagPersistent;
69 import com.android.settings.widget.EntityHeaderController;
70 import com.android.settings.wifi.WifiDialog;
71 import com.android.settings.wifi.WifiDialog.WifiDialogListener;
72 import com.android.settings.wifi.WifiUtils;
73 import com.android.settings.wifi.dpp.WifiDppUtils;
74 import com.android.settingslib.core.AbstractPreferenceController;
75 import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
76 import com.android.settingslib.core.lifecycle.Lifecycle;
77 import com.android.settingslib.core.lifecycle.LifecycleObserver;
78 import com.android.settingslib.core.lifecycle.events.OnPause;
79 import com.android.settingslib.core.lifecycle.events.OnResume;
80 import com.android.settingslib.widget.ActionButtonsPreference;
81 import com.android.settingslib.widget.LayoutPreference;
82 import com.android.settingslib.wifi.AccessPoint;
83 import com.android.settingslib.wifi.WifiTracker;
84 import com.android.settingslib.wifi.WifiTrackerFactory;
86 import java.net.Inet4Address;
87 import java.net.Inet6Address;
88 import java.net.InetAddress;
89 import java.net.UnknownHostException;
90 import java.time.Duration;
91 import java.util.StringJoiner;
92 import java.util.stream.Collectors;
95 * Controller for logic pertaining to displaying Wifi information for the
96 * {@link WifiNetworkDetailsFragment}.
98 public class WifiDetailPreferenceController extends AbstractPreferenceController
99 implements PreferenceControllerMixin, WifiDialogListener, LifecycleObserver, OnPause,
102 private static final String TAG = "WifiDetailsPrefCtrl";
103 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
106 static final String KEY_HEADER = "connection_header";
108 static final String KEY_DATA_USAGE_HEADER = "status_header";
110 static final String KEY_BUTTONS_PREF = "buttons";
112 static final String KEY_SIGNAL_STRENGTH_PREF = "signal_strength";
114 static final String KEY_TX_LINK_SPEED = "tx_link_speed";
116 static final String KEY_RX_LINK_SPEED = "rx_link_speed";
118 static final String KEY_FREQUENCY_PREF = "frequency";
120 static final String KEY_SECURITY_PREF = "security";
122 static final String KEY_SSID_PREF = "ssid";
124 static final String KEY_MAC_ADDRESS_PREF = "mac_address";
126 static final String KEY_IP_ADDRESS_PREF = "ip_address";
128 static final String KEY_GATEWAY_PREF = "gateway";
130 static final String KEY_SUBNET_MASK_PREF = "subnet_mask";
132 static final String KEY_DNS_PREF = "dns";
134 static final String KEY_IPV6_CATEGORY = "ipv6_category";
136 static final String KEY_IPV6_ADDRESSES_PREF = "ipv6_addresses";
138 private static final int STATE_NONE = 1;
139 private static final int STATE_ENABLE_WIFI = 2;
140 private static final int STATE_ENABLE_WIFI_FAILED = 3;
141 private static final int STATE_CONNECTING = 4;
142 private static final int STATE_CONNECTED = 5;
143 private static final int STATE_FAILED = 6;
144 private static final int STATE_NOT_IN_RANGE = 7;
145 private static final int STATE_DISCONNECTED = 8;
146 private static final long TIMEOUT = Duration.ofSeconds(10).toMillis();
148 // Be static to avoid too much object not be reset.
150 static CountDownTimer mTimer;
152 private AccessPoint mAccessPoint;
153 private final ConnectivityManager mConnectivityManager;
154 private final Fragment mFragment;
155 private final Handler mHandler;
156 private LinkProperties mLinkProperties;
157 private Network mNetwork;
158 private NetworkInfo mNetworkInfo;
159 private NetworkCapabilities mNetworkCapabilities;
160 private int mRssiSignalLevel = -1;
161 private String[] mSignalStr;
162 private WifiConfiguration mWifiConfig;
163 private WifiInfo mWifiInfo;
164 private final WifiManager mWifiManager;
165 private final WifiTracker mWifiTracker;
166 private final MetricsFeatureProvider mMetricsFeatureProvider;
167 private boolean mIsOutOfRange;
168 private boolean mIsEphemeral;
169 private boolean mConnected;
170 private int mConnectingState;
171 private WifiManager.ActionListener mConnectListener;
173 // UI elements - in order of appearance
174 private ActionButtonsPreference mButtonsPref;
175 private EntityHeaderController mEntityHeaderController;
176 private Preference mSignalStrengthPref;
177 private Preference mTxLinkSpeedPref;
178 private Preference mRxLinkSpeedPref;
179 private Preference mFrequencyPref;
180 private Preference mSecurityPref;
181 private Preference mSsidPref;
182 private Preference mMacAddressPref;
183 private Preference mIpAddressPref;
184 private Preference mGatewayPref;
185 private Preference mSubnetPref;
186 private Preference mDnsPref;
187 private PreferenceCategory mIpv6Category;
188 private Preference mIpv6AddressPref;
189 private Lifecycle mLifecycle;
190 Preference mDataUsageSummaryPref;
191 WifiDataUsageSummaryPreferenceController mSummaryHeaderController;
193 private final IconInjector mIconInjector;
194 private final IntentFilter mFilter;
195 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
197 public void onReceive(Context context, Intent intent) {
198 switch (intent.getAction()) {
199 case WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION:
200 if (!intent.getBooleanExtra(WifiManager.EXTRA_MULTIPLE_NETWORKS_CHANGED,
201 false /* defaultValue */)) {
202 // only one network changed
203 WifiConfiguration wifiConfiguration = intent
204 .getParcelableExtra(WifiManager.EXTRA_WIFI_CONFIGURATION);
205 if (mAccessPoint.matches(wifiConfiguration)) {
206 mWifiConfig = wifiConfiguration;
210 case WifiManager.NETWORK_STATE_CHANGED_ACTION:
211 case WifiManager.RSSI_CHANGED_ACTION:
218 private final NetworkRequest mNetworkRequest = new NetworkRequest.Builder()
219 .clearCapabilities().addTransportType(TRANSPORT_WIFI).build();
221 // Must be run on the UI thread since it directly manipulates UI state.
222 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
224 public void onLinkPropertiesChanged(Network network, LinkProperties lp) {
225 if (network.equals(mNetwork) && !lp.equals(mLinkProperties)) {
226 mLinkProperties = lp;
227 refreshIpLayerInfo();
231 private boolean hasCapabilityChanged(NetworkCapabilities nc, int cap) {
232 // If this is the first time we get NetworkCapabilities, report that something changed.
233 if (mNetworkCapabilities == null) return true;
235 // nc can never be null, see ConnectivityService#callCallbackForRequest.
236 return mNetworkCapabilities.hasCapability(cap) != nc.hasCapability(cap);
240 public void onCapabilitiesChanged(Network network, NetworkCapabilities nc) {
241 // If the network just validated or lost Internet access or detected partial internet
242 // connectivity, refresh network state. Don't do this on every NetworkCapabilities
243 // change because refreshNetworkState sends IPCs to the system server from the UI
244 // thread, which can cause jank.
245 if (network.equals(mNetwork) && !nc.equals(mNetworkCapabilities)) {
246 if (hasCapabilityChanged(nc, NET_CAPABILITY_VALIDATED)
247 || hasCapabilityChanged(nc, NET_CAPABILITY_CAPTIVE_PORTAL)
248 || hasCapabilityChanged(nc, NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
249 mAccessPoint.update(mWifiConfig, mWifiInfo, mNetworkInfo);
250 refreshEntityHeader();
252 mNetworkCapabilities = nc;
254 refreshIpLayerInfo();
259 public void onLost(Network network) {
260 // Ephemeral network not a saved network, leave detail page once disconnected
261 if (mIsEphemeral && network.equals(mNetwork)) {
268 final WifiTracker.WifiListener mWifiListener = new WifiTracker.WifiListener() {
269 /** Called when the state of Wifi has changed. */
270 public void onWifiStateChanged(int state) {
271 Log.d(TAG, "onWifiStateChanged(" + state + ")");
272 if (mConnectingState == STATE_ENABLE_WIFI && state == WifiManager.WIFI_STATE_ENABLED) {
273 updateConnectingState(STATE_CONNECTING);
274 } else if (mConnectingState != STATE_NONE && state == WifiManager.WIFI_STATE_DISABLED) {
275 // update as disconnected once Wi-Fi disabled since may not received
276 // onConnectedChanged for this case.
277 updateConnectingState(STATE_DISCONNECTED);
281 /** Called when the connection state of wifi has changed. */
282 public void onConnectedChanged() {
287 * Called to indicate the list of AccessPoints has been updated and
288 * {@link WifiTracker#getAccessPoints()} should be called to get the updated list.
290 public void onAccessPointsChanged() {
295 public static WifiDetailPreferenceController newInstance(
296 AccessPoint accessPoint,
297 ConnectivityManager connectivityManager,
302 WifiManager wifiManager,
303 MetricsFeatureProvider metricsFeatureProvider) {
304 return new WifiDetailPreferenceController(
305 accessPoint, connectivityManager, context, fragment, handler, lifecycle,
306 wifiManager, metricsFeatureProvider, new IconInjector(context));
310 /* package */ WifiDetailPreferenceController(
311 AccessPoint accessPoint,
312 ConnectivityManager connectivityManager,
317 WifiManager wifiManager,
318 MetricsFeatureProvider metricsFeatureProvider,
319 IconInjector injector) {
322 mAccessPoint = accessPoint;
323 mConnectivityManager = connectivityManager;
324 mFragment = fragment;
326 mSignalStr = context.getResources().getStringArray(R.array.wifi_signal);
327 mWifiConfig = accessPoint.getConfig();
328 mWifiManager = wifiManager;
329 mMetricsFeatureProvider = metricsFeatureProvider;
330 mIconInjector = injector;
332 mFilter = new IntentFilter();
333 mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
334 mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
335 mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
337 mLifecycle = lifecycle;
338 lifecycle.addObserver(this);
340 mWifiTracker = WifiTrackerFactory.create(
341 mFragment.getActivity(),
344 true /*includeSaved*/,
345 true /*includeScans*/);
346 mConnected = mAccessPoint.isActive();
347 // When lost the network connection, WifiInfo/NetworkInfo will be clear. So causes we
348 // could not check if the AccessPoint is ephemeral. Need to cache it in first.
349 mIsEphemeral = mAccessPoint.isEphemeral();
350 mConnectingState = STATE_NONE;
351 mConnectListener = new WifiManager.ActionListener() {
353 public void onSuccess() {
358 public void onFailure(int reason) {
359 updateConnectingState(STATE_FAILED);
365 public boolean isAvailable() {
370 public String getPreferenceKey() {
371 // Returns null since this controller contains more than one Preference
376 public void displayPreference(PreferenceScreen screen) {
377 super.displayPreference(screen);
379 setupEntityHeader(screen);
381 mButtonsPref = ((ActionButtonsPreference) screen.findPreference(KEY_BUTTONS_PREF))
382 .setButton1Text(R.string.forget)
383 .setButton1Icon(R.drawable.ic_settings_delete)
384 .setButton1OnClickListener(view -> forgetNetwork())
385 .setButton2Text(R.string.wifi_sign_in_button_text)
386 .setButton2Icon(R.drawable.ic_settings_sign_in)
387 .setButton2OnClickListener(view -> signIntoNetwork())
388 .setButton3Text(R.string.wifi_connect)
389 .setButton3Icon(R.drawable.ic_settings_wireless)
390 .setButton3OnClickListener(view -> connectNetwork())
391 .setButton3Enabled(true)
392 .setButton4Text(R.string.share)
393 .setButton4Icon(R.drawable.ic_qrcode_24dp)
394 .setButton4OnClickListener(view -> shareNetwork());
396 mSignalStrengthPref = screen.findPreference(KEY_SIGNAL_STRENGTH_PREF);
397 mTxLinkSpeedPref = screen.findPreference(KEY_TX_LINK_SPEED);
398 mRxLinkSpeedPref = screen.findPreference(KEY_RX_LINK_SPEED);
399 mFrequencyPref = screen.findPreference(KEY_FREQUENCY_PREF);
400 mSecurityPref = screen.findPreference(KEY_SECURITY_PREF);
402 mSsidPref = screen.findPreference(KEY_SSID_PREF);
403 mMacAddressPref = screen.findPreference(KEY_MAC_ADDRESS_PREF);
404 mIpAddressPref = screen.findPreference(KEY_IP_ADDRESS_PREF);
405 mGatewayPref = screen.findPreference(KEY_GATEWAY_PREF);
406 mSubnetPref = screen.findPreference(KEY_SUBNET_MASK_PREF);
407 mDnsPref = screen.findPreference(KEY_DNS_PREF);
409 mIpv6Category = screen.findPreference(KEY_IPV6_CATEGORY);
410 mIpv6AddressPref = screen.findPreference(KEY_IPV6_ADDRESSES_PREF);
412 mSecurityPref.setSummary(mAccessPoint.getSecurityString(/* concise */ false));
415 private void setupEntityHeader(PreferenceScreen screen) {
416 LayoutPreference headerPref = screen.findPreference(KEY_HEADER);
418 if (usingDataUsageHeader(mContext)) {
419 headerPref.setVisible(false);
420 mDataUsageSummaryPref = screen.findPreference(KEY_DATA_USAGE_HEADER);
421 mDataUsageSummaryPref.setVisible(true);
422 mSummaryHeaderController =
423 new WifiDataUsageSummaryPreferenceController(mFragment.getActivity(),
424 mLifecycle, (PreferenceFragmentCompat) mFragment, mAccessPoint.getSsid());
428 mEntityHeaderController =
429 EntityHeaderController.newInstance(
430 mFragment.getActivity(), mFragment,
431 headerPref.findViewById(R.id.entity_header));
433 ImageView iconView = headerPref.findViewById(R.id.entity_header_icon);
435 iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
437 mEntityHeaderController.setLabel(mAccessPoint.getTitle());
440 private void refreshEntityHeader() {
441 if (usingDataUsageHeader(mContext)) {
442 mSummaryHeaderController.updateState(mDataUsageSummaryPref);
444 mEntityHeaderController.setSummary(mAccessPoint.getSettingsSummary())
445 .done(mFragment.getActivity(), true /* rebind */);
449 private void updateNetworkInfo() {
450 mNetwork = mWifiManager.getCurrentNetwork();
451 mLinkProperties = mConnectivityManager.getLinkProperties(mNetwork);
452 mNetworkCapabilities = mConnectivityManager.getNetworkCapabilities(mNetwork);
456 public void onResume() {
457 // Ensure mNetwork is set before any callbacks above are delivered, since our
458 // NetworkCallback only looks at changes to mNetwork.
461 mContext.registerReceiver(mReceiver, mFilter);
462 mConnectivityManager.registerNetworkCallback(mNetworkRequest, mNetworkCallback,
467 public void onPause() {
469 mLinkProperties = null;
470 mNetworkCapabilities = null;
473 mContext.unregisterReceiver(mReceiver);
474 mConnectivityManager.unregisterNetworkCallback(mNetworkCallback);
477 private void refreshPage() {
478 if(!updateAccessPoint()) {
482 Log.d(TAG, "Update UI!");
485 refreshEntityHeader();
490 // Update Connection Header icon and Signal Strength Preference
494 // Transmit Link Speed Pref
496 // Receive Link Speed Pref
498 // IP related information
499 refreshIpLayerInfo();
507 boolean updateAccessPoint() {
508 boolean changed = false;
509 // remember mIsOutOfRange as old before updated
510 boolean oldState = mIsOutOfRange;
511 updateAccessPointFromScannedList();
513 if (mAccessPoint.isActive()) {
515 mNetworkInfo = mConnectivityManager.getNetworkInfo(mNetwork);
516 mWifiInfo = mWifiManager.getConnectionInfo();
517 if (mNetwork == null || mNetworkInfo == null || mWifiInfo == null) {
518 // Once connected, can't get mNetwork immediately, return false and wait for
519 // next time to update UI. also reset {@code mIsOutOfRange}
520 mIsOutOfRange = oldState;
523 changed |= mAccessPoint.update(mWifiConfig, mWifiInfo, mNetworkInfo);
526 // signal level changed
527 changed |= mRssiSignalLevel != mAccessPoint.getLevel();
528 // In/Out of range changed
529 changed |= oldState != mIsOutOfRange;
530 // connect state changed
531 if (mConnected != mAccessPoint.isActive()) {
532 mConnected = mAccessPoint.isActive();
534 updateConnectingState(mAccessPoint.isActive() ? STATE_CONNECTED : STATE_DISCONNECTED);
540 private void updateAccessPointFromScannedList() {
541 mIsOutOfRange = true;
543 for (AccessPoint ap : mWifiTracker.getAccessPoints()) {
544 if (mAccessPoint.matches(ap)) {
546 mWifiConfig = ap.getConfig();
547 mIsOutOfRange = !mAccessPoint.isReachable();
553 private void exitActivity() {
555 Log.d(TAG, "Exiting the WifiNetworkDetailsPage");
557 mFragment.getActivity().finish();
560 private void refreshRssiViews() {
561 int signalLevel = mAccessPoint.getLevel();
563 // Disappears signal view if not in range. e.g. for saved networks.
565 mSignalStrengthPref.setVisible(false);
566 mRssiSignalLevel = -1;
570 if (mRssiSignalLevel == signalLevel) {
573 mRssiSignalLevel = signalLevel;
574 Drawable wifiIcon = mIconInjector.getIcon(mRssiSignalLevel);
576 if (mEntityHeaderController != null) {
577 mEntityHeaderController
578 .setIcon(redrawIconForHeader(wifiIcon)).done(mFragment.getActivity(),
582 Drawable wifiIconDark = wifiIcon.getConstantState().newDrawable().mutate();
583 wifiIconDark.setTintList(Utils.getColorAttr(mContext, android.R.attr.colorControlNormal));
584 mSignalStrengthPref.setIcon(wifiIconDark);
586 mSignalStrengthPref.setSummary(mSignalStr[mRssiSignalLevel]);
587 mSignalStrengthPref.setVisible(true);
590 private Drawable redrawIconForHeader(Drawable original) {
591 final int iconSize = mContext.getResources().getDimensionPixelSize(
592 R.dimen.wifi_detail_page_header_image_size);
593 final int actualWidth = original.getMinimumWidth();
594 final int actualHeight = original.getMinimumHeight();
596 if ((actualWidth == iconSize && actualHeight == iconSize)
597 || !VectorDrawable.class.isInstance(original)) {
601 // clear tint list to make sure can set 87% black after enlarge
602 original.setTintList(null);
605 final Bitmap bitmap = Utils.createBitmap(original,
607 iconSize /*height*/);
608 Drawable newIcon = new BitmapDrawable(null /*resource*/, bitmap);
610 // config color for 87% black after enlarge
611 newIcon.setTintList(Utils.getColorAttr(mContext, android.R.attr.textColorPrimary));
616 private void refreshFrequency() {
617 if (mWifiInfo == null) {
618 mFrequencyPref.setVisible(false);
622 final int frequency = mWifiInfo.getFrequency();
624 if (frequency >= AccessPoint.LOWER_FREQ_24GHZ
625 && frequency < AccessPoint.HIGHER_FREQ_24GHZ) {
626 band = mContext.getResources().getString(R.string.wifi_band_24ghz);
627 } else if (frequency >= AccessPoint.LOWER_FREQ_5GHZ
628 && frequency < AccessPoint.HIGHER_FREQ_5GHZ) {
629 band = mContext.getResources().getString(R.string.wifi_band_5ghz);
631 Log.e(TAG, "Unexpected frequency " + frequency);
632 // Connecting state is unstable, make it disappeared if unexpected
633 if (mConnectingState == STATE_CONNECTING) {
634 mFrequencyPref.setVisible(false);
638 mFrequencyPref.setSummary(band);
639 mFrequencyPref.setVisible(true);
642 private void refreshTxSpeed() {
643 if (mWifiInfo == null) {
644 mTxLinkSpeedPref.setVisible(false);
648 int txLinkSpeedMbps = mWifiInfo.getTxLinkSpeedMbps();
649 mTxLinkSpeedPref.setVisible(txLinkSpeedMbps >= 0);
650 mTxLinkSpeedPref.setSummary(mContext.getString(
651 R.string.tx_link_speed, mWifiInfo.getTxLinkSpeedMbps()));
654 private void refreshRxSpeed() {
655 if (mWifiInfo == null) {
656 mRxLinkSpeedPref.setVisible(false);
660 int rxLinkSpeedMbps = mWifiInfo.getRxLinkSpeedMbps();
661 mRxLinkSpeedPref.setVisible(rxLinkSpeedMbps >= 0);
662 mRxLinkSpeedPref.setSummary(mContext.getString(
663 R.string.rx_link_speed, mWifiInfo.getRxLinkSpeedMbps()));
666 private void refreshSsid() {
667 if (mAccessPoint.isPasspoint() || mAccessPoint.isOsuProvider()) {
668 mSsidPref.setVisible(true);
669 mSsidPref.setSummary(mAccessPoint.getSsidStr());
671 mSsidPref.setVisible(false);
675 private void refreshMacAddress() {
676 String macAddress = getMacAddress();
677 if (macAddress == null) {
678 mMacAddressPref.setVisible(false);
682 mMacAddressPref.setVisible(true);
683 mMacAddressPref.setSummary(macAddress);
686 private String getMacAddress() {
687 if (mWifiInfo != null) {
688 // get MAC address from connected network information
689 return mWifiInfo.getMacAddress();
692 // return randomized MAC address
693 if (mWifiConfig != null &&
694 mWifiConfig.macRandomizationSetting == WifiConfiguration.RANDOMIZATION_PERSISTENT) {
695 return mWifiConfig.getRandomizedMacAddress().toString();
698 // return device MAC address
699 final String[] macAddresses = mWifiManager.getFactoryMacAddresses();
700 if (macAddresses != null && macAddresses.length > 0) {
701 return macAddresses[0];
704 Log.e(TAG, "Can't get device MAC address!");
708 private void updatePreference(Preference pref, String detailText) {
709 if (!TextUtils.isEmpty(detailText)) {
710 pref.setSummary(detailText);
711 pref.setVisible(true);
713 pref.setVisible(false);
717 private void refreshButtons() {
718 // Ephemeral network won't be removed permanently, but be putted in blacklist.
719 mButtonsPref.setButton1Text(
720 mIsEphemeral ? R.string.wifi_disconnect_button_text : R.string.forget);
722 boolean canForgetNetwork = canForgetNetwork();
723 boolean canSignIntoNetwork = canSignIntoNetwork();
724 boolean canConnectNetwork = canConnectNetwork();
725 boolean canShareNetwork = canShareNetwork();
727 mButtonsPref.setButton1Visible(canForgetNetwork);
728 mButtonsPref.setButton2Visible(canSignIntoNetwork);
729 mButtonsPref.setButton3Visible(canConnectNetwork);
730 mButtonsPref.setButton4Visible(canShareNetwork);
731 mButtonsPref.setVisible(canForgetNetwork
732 || canSignIntoNetwork
737 private boolean canConnectNetwork() {
738 // Display connect button for disconnected AP even not in the range.
739 return !mAccessPoint.isActive();
742 private void refreshIpLayerInfo() {
743 // Hide IP layer info if not a connected network.
744 if (!mAccessPoint.isActive() || mNetwork == null || mLinkProperties == null) {
745 mIpAddressPref.setVisible(false);
746 mSubnetPref.setVisible(false);
747 mGatewayPref.setVisible(false);
748 mDnsPref.setVisible(false);
749 mIpv6Category.setVisible(false);
753 // Find IPv4 and IPv6 addresses.
754 String ipv4Address = null;
755 String subnet = null;
756 StringJoiner ipv6Addresses = new StringJoiner("\n");
758 for (LinkAddress addr : mLinkProperties.getLinkAddresses()) {
759 if (addr.getAddress() instanceof Inet4Address) {
760 ipv4Address = addr.getAddress().getHostAddress();
761 subnet = ipv4PrefixLengthToSubnetMask(addr.getPrefixLength());
762 } else if (addr.getAddress() instanceof Inet6Address) {
763 ipv6Addresses.add(addr.getAddress().getHostAddress());
767 // Find IPv4 default gateway.
768 String gateway = null;
769 for (RouteInfo routeInfo : mLinkProperties.getRoutes()) {
770 if (routeInfo.isIPv4Default() && routeInfo.hasGateway()) {
771 gateway = routeInfo.getGateway().getHostAddress();
776 // Find all (IPv4 and IPv6) DNS addresses.
777 String dnsServers = mLinkProperties.getDnsServers().stream()
778 .map(InetAddress::getHostAddress)
779 .collect(Collectors.joining("\n"));
782 updatePreference(mIpAddressPref, ipv4Address);
783 updatePreference(mSubnetPref, subnet);
784 updatePreference(mGatewayPref, gateway);
785 updatePreference(mDnsPref, dnsServers);
787 if (ipv6Addresses.length() > 0) {
788 mIpv6AddressPref.setSummary(
789 BidiFormatter.getInstance().unicodeWrap(ipv6Addresses.toString()));
790 mIpv6Category.setVisible(true);
792 mIpv6Category.setVisible(false);
796 private static String ipv4PrefixLengthToSubnetMask(int prefixLength) {
798 InetAddress all = InetAddress.getByAddress(
799 new byte[]{(byte) 255, (byte) 255, (byte) 255, (byte) 255});
800 return NetworkUtils.getNetworkPart(all, prefixLength).getHostAddress();
801 } catch (UnknownHostException e) {
807 * Returns whether the network represented by this preference can be forgotten.
809 private boolean canForgetNetwork() {
810 return (mWifiInfo != null && mWifiInfo.isEphemeral()) || canModifyNetwork()
811 || mAccessPoint.isPasspoint() || mAccessPoint.isPasspointConfig();
815 * Returns whether the network represented by this preference can be modified.
817 public boolean canModifyNetwork() {
818 return mWifiConfig != null && !WifiUtils.isNetworkLockedDown(mContext, mWifiConfig);
822 * Returns whether the user can sign into the network represented by this preference.
824 private boolean canSignIntoNetwork() {
825 return mAccessPoint.isActive() && WifiUtils.canSignIntoNetwork(mNetworkCapabilities);
829 * Returns whether the user can share the network represented by this preference with QR code.
831 private boolean canShareNetwork() {
832 return mAccessPoint.getConfig() != null &&
833 WifiDppUtils.isSupportConfiguratorQrCodeGenerator(mContext, mAccessPoint);
837 * Forgets the wifi network associated with this preference.
839 private void forgetNetwork() {
840 if (mWifiInfo != null && mWifiInfo.isEphemeral()) {
841 mWifiManager.disableEphemeralNetwork(mWifiInfo.getSSID());
842 } else if (mAccessPoint.isPasspoint() || mAccessPoint.isPasspointConfig()) {
843 // Post a dialog to confirm if user really want to forget the passpoint network.
844 if (FeatureFlagPersistent.isEnabled(mContext, FeatureFlags.NETWORK_INTERNET_V2)) {
845 showConfirmForgetDialog();
850 mWifiManager.removePasspointConfiguration(mAccessPoint.getPasspointFqdn());
851 } catch (RuntimeException e) {
852 Log.e(TAG, "Failed to remove Passpoint configuration for "
853 + mAccessPoint.getPasspointFqdn());
855 } else if (mWifiConfig != null) {
856 mWifiManager.forget(mWifiConfig.networkId, null /* action listener */);
859 mMetricsFeatureProvider.action(
860 mFragment.getActivity(), SettingsEnums.ACTION_WIFI_FORGET);
861 mFragment.getActivity().finish();
865 protected void showConfirmForgetDialog() {
866 final AlertDialog dialog = new AlertDialog.Builder(mContext)
867 .setPositiveButton(R.string.forget, ((dialog1, which) -> {
869 mWifiManager.removePasspointConfiguration(mAccessPoint.getPasspointFqdn());
870 } catch (RuntimeException e) {
871 Log.e(TAG, "Failed to remove Passpoint configuration for "
872 + mAccessPoint.getPasspointFqdn());
874 mMetricsFeatureProvider.action(
875 mFragment.getActivity(), SettingsEnums.ACTION_WIFI_FORGET);
876 mFragment.getActivity().finish();
878 .setNegativeButton(R.string.cancel, null /* listener */)
879 .setTitle(R.string.wifi_forget_dialog_title)
880 .setMessage(R.string.forget_passpoint_dialog_message)
886 * Show QR code to share the network represented by this preference.
888 public void launchWifiDppConfiguratorActivity() {
889 final Intent intent = WifiDppUtils.getConfiguratorQrCodeGeneratorIntentOrNull(mContext,
890 mWifiManager, mAccessPoint);
892 if (intent == null) {
893 Log.e(TAG, "Launch Wi-Fi DPP QR code generator with a wrong Wi-Fi network!");
895 mContext.startActivity(intent);
900 * Share the wifi network with QR code.
902 private void shareNetwork() {
903 WifiDppUtils.showLockScreen(mContext, () -> launchWifiDppConfiguratorActivity());
907 * Sign in to the captive portal found on this wifi network associated with this preference.
909 private void signIntoNetwork() {
910 mMetricsFeatureProvider.action(
911 mFragment.getActivity(), SettingsEnums.ACTION_WIFI_SIGNIN);
912 mConnectivityManager.startCaptivePortalApp(mNetwork);
916 public void onSubmit(WifiDialog dialog) {
917 if (dialog.getController() != null) {
918 mWifiManager.save(dialog.getController().getConfig(), new WifiManager.ActionListener() {
920 public void onSuccess() {
924 public void onFailure(int reason) {
925 Activity activity = mFragment.getActivity();
926 if (activity != null) {
927 Toast.makeText(activity,
928 R.string.wifi_failed_save_message,
929 Toast.LENGTH_SHORT).show();
937 * Wrapper for testing compatibility.
940 static class IconInjector {
941 private final Context mContext;
943 public IconInjector(Context context) {
947 public Drawable getIcon(int level) {
948 return mContext.getDrawable(Utils.getWifiIconResource(level)).mutate();
952 private boolean usingDataUsageHeader(Context context) {
953 return FeatureFlagUtils.isEnabled(context, FeatureFlags.WIFI_DETAILS_DATAUSAGE_HEADER);
957 void connectNetwork() {
958 final Activity activity = mFragment.getActivity();
959 // error handling, connected/saved network should have mWifiConfig.
960 if (mWifiConfig == null) {
961 Toast.makeText(activity,
962 R.string.wifi_failed_connect_message,
963 Toast.LENGTH_SHORT).show();
967 // init state before connect
968 mConnectingState = STATE_NONE;
970 if (mWifiManager.isWifiEnabled()) {
971 updateConnectingState(STATE_CONNECTING);
973 // Enable Wi-Fi automatically to connect AP
974 updateConnectingState(STATE_ENABLE_WIFI);
978 private void updateConnectingState(int state) {
979 final Activity activity = mFragment.getActivity();
980 Log.d(TAG, "updateConnectingState from " + mConnectingState + " to " + state);
981 switch (mConnectingState) {
983 case STATE_ENABLE_WIFI:
984 if (state == STATE_ENABLE_WIFI) {
985 Log.d(TAG, "Turn on Wi-Fi automatically!");
986 updateConnectedButton(STATE_ENABLE_WIFI);
987 Toast.makeText(activity,
988 R.string.wifi_turned_on_message,
989 Toast.LENGTH_SHORT).show();
990 mWifiManager.setWifiEnabled(true);
991 // start timer for error handling
993 } else if (state == STATE_CONNECTING) {
994 Log.d(TAG, "connecting...");
995 updateConnectedButton(STATE_CONNECTING);
996 if (mAccessPoint.isPasspoint()) {
997 mWifiManager.connect(mWifiConfig, mConnectListener);
999 mWifiManager.connect(mWifiConfig.networkId, mConnectListener);
1001 // start timer for error handling since framework didn't call back if failed
1003 } else if (state == STATE_ENABLE_WIFI_FAILED) {
1004 Log.e(TAG, "Wi-Fi failed to enable network!");
1008 Toast.makeText(activity,
1009 R.string.wifi_failed_connect_message,
1010 Toast.LENGTH_SHORT).show();
1011 updateConnectedButton(STATE_ENABLE_WIFI_FAILED);
1013 // Do not break here for disconnected event.
1014 case STATE_CONNECTED:
1015 if (state == STATE_DISCONNECTED) {
1016 Log.d(TAG, "disconnected");
1019 updateConnectedButton(STATE_DISCONNECTED);
1021 // clear for getting MAC Address from saved configuration
1025 case STATE_CONNECTING:
1026 if (state == STATE_CONNECTED) {
1027 Log.d(TAG, "connected");
1029 updateConnectedButton(STATE_CONNECTED);
1030 Toast.makeText(activity,
1031 mContext.getString(R.string.wifi_connected_to_message,
1032 mAccessPoint.getTitle()),
1033 Toast.LENGTH_SHORT).show();
1036 } else if (state == STATE_NOT_IN_RANGE) {
1037 Log.d(TAG, "AP not in range");
1041 Toast.makeText(activity,
1042 R.string.wifi_not_in_range_message,
1043 Toast.LENGTH_SHORT).show();
1044 updateConnectedButton(STATE_NOT_IN_RANGE);
1045 } else if (state == STATE_FAILED) {
1046 Log.d(TAG, "failed");
1050 Toast.makeText(activity,
1051 R.string.wifi_failed_connect_message,
1052 Toast.LENGTH_SHORT).show();
1053 updateConnectedButton(STATE_FAILED);
1057 Log.e(TAG, "Invalid state : " + mConnectingState);
1058 // don't update invalid state
1062 mConnectingState = state;
1065 private void updateConnectedButton(int state) {
1067 case STATE_ENABLE_WIFI:
1068 case STATE_CONNECTING:
1069 mButtonsPref.setButton3Text(R.string.wifi_connecting)
1070 .setButton3Enabled(false);
1072 case STATE_CONNECTED:
1073 // init button state and set as invisible
1074 mButtonsPref.setButton3Text(R.string.wifi_connect)
1075 .setButton3Icon(R.drawable.ic_settings_wireless)
1076 .setButton3Enabled(true)
1077 .setButton3Visible(false);
1079 case STATE_DISCONNECTED:
1080 case STATE_NOT_IN_RANGE:
1082 case STATE_ENABLE_WIFI_FAILED:
1083 mButtonsPref.setButton3Text(R.string.wifi_connect)
1084 .setButton3Icon(R.drawable.ic_settings_wireless)
1085 .setButton3Enabled(true)
1086 .setButton3Visible(true);
1089 Log.e(TAG, "Invalid connect button state : " + state);
1094 private void startTimer() {
1095 if (mTimer != null) {
1099 mTimer = new CountDownTimer(TIMEOUT, TIMEOUT + 1) {
1101 public void onTick(long millisUntilFinished) {
1105 public void onFinish() {
1106 Log.e(TAG, "Timeout for state:" + mConnectingState);
1107 if (mConnectingState == STATE_ENABLE_WIFI) {
1108 updateConnectingState(STATE_ENABLE_WIFI_FAILED);
1109 } else if (mConnectingState == STATE_CONNECTING) {
1110 updateAccessPointFromScannedList();
1111 if (mIsOutOfRange) {
1112 updateConnectingState(STATE_NOT_IN_RANGE);
1114 updateConnectingState(STATE_FAILED);
1122 private void stopTimer() {
1123 if (mTimer == null) return;