[Wi-Fi] Replace WifiTracker with WifiTracker2 in WifiDetailPreferenceController2

There are still many methods not implemented in WifiEntry. This change has below workarounds:

1. Add WifiEntryShell to provide dummy WifiEntry methods.
2. Add @Ignore to WifiDetailPreferenceController2Test.

Must remove these workarounds after we have more constructed WifiEntry methods.

Bug: 143326832
Test: make RunSettingsRoboTests ROBOTEST_FILTER=com.android.settings.wifi.details2
      make RunSettingsRoboTests ROBOTEST_FILTER=com.android.settings.wifi.savedaccesspoints2
      make RunSettingsRoboTests ROBOTEST_FILTER=com.android.settings.wifi
Change-Id: Ic2edb424b9c645838558fe131991ccb9105dc64c
This commit is contained in:
Arc Wang
2019-11-27 14:58:43 +08:00
parent 5921312f43
commit b60e91bf0b
11 changed files with 596 additions and 982 deletions

View File

@@ -0,0 +1,131 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.wifi;
import android.net.NetworkInfo.DetailedState;
import com.android.wifitrackerlib.WifiEntry;
/**
* {@link WifiEntry is working in progess, many methods are not available, this class is to group
* all the unavalable {@link AccessPoint} methods & constants.
*
* TODO(b/143326832): Replace all methods & constants with WifiEntry version when it's available.
* TODO(b/143326832): How about AccessPoint#getSettingsSummary(boolean convertSavedAsDisconnected)?
*/
public class WifiEntryShell {
public WifiEntryShell(){};
/**
* Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels
*/
public static final int LOWER_FREQ_24GHZ = 2400;
/**
* Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels
*/
public static final int HIGHER_FREQ_24GHZ = 2500;
/**
* Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
*/
public static final int LOWER_FREQ_5GHZ = 4900;
/**
* Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
*/
public static final int HIGHER_FREQ_5GHZ = 5900;
/**
* Mapping of the corresponding {@link WifiConfiguration} field
*/
public static int getNetworkId(WifiEntry wifiEntry) {
return 0;
}
/**
* Mapping of the corresponding {@link WifiConfiguration} field
*/
public static boolean hiddenSSID(WifiEntry wifiEntry) {
return false;
}
/**
* Mapping of the corresponding {@link WifiDetailPreferenceController} method
*/
public static boolean canModifyNetwork(WifiEntry wifiEntry) {
return false;
}
/**
* Mapping of the corresponding {@link AccessPoint} method
*/
public static String getSecurityString(WifiEntry wifiEntry, boolean concise) {
return "None";
}
/**
* Mapping of the corresponding {@link AccessPoint} method
*/
public static DetailedState getDetailedState(WifiEntry wifiEntry) {
return null;
}
// Passpoint methods
/**
* Mapping of the corresponding {@link AccessPoint} method
*/
public static boolean isPasspoint(WifiEntry wifiEntry) {
return false;
}
/**
* Mapping of the corresponding {@link AccessPoint} method
*/
public static boolean isExpired(WifiEntry wifiEntry) {
return false;
}
/**
* Mapping of the corresponding {@link AccessPoint} method
*/
public static boolean isPasspointConfigurationR1(WifiEntry wifiEntry) {
return false;
}
/**
* Mapping of the corresponding {@link AccessPoint} method
*/
public static boolean isPasspointConfigurationOsuProvisioned(WifiEntry wifiEntry) {
return false;
}
/**
* Mapping of the corresponding {@link AccessPoint} method
*/
public static boolean isOsuProvider(WifiEntry wifiEntry) {
return false;
}
/**
* Mapping of the corresponding {@link AccessPoint} method
*/
public static String getPasspointFqdn(WifiEntry wifiEntry) {
return "Fake passpoint FQDN";
}
}

View File

@@ -25,7 +25,7 @@ import androidx.preference.Preference;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.wifi.dpp.WifiDppUtils;
import com.android.settingslib.wifi.AccessPoint;
import com.android.wifitrackerlib.WifiEntry;
/**
* {@link BasePreferenceController} that launches Wi-Fi Easy Connect configurator flow
@@ -36,7 +36,7 @@ public class AddDevicePreferenceController2 extends BasePreferenceController {
private static final String KEY_ADD_DEVICE = "add_device_to_network";
private AccessPoint mAccessPoint;
private WifiEntry mWifiEntry;
private WifiManager mWifiManager;
public AddDevicePreferenceController2(Context context) {
@@ -45,18 +45,13 @@ public class AddDevicePreferenceController2 extends BasePreferenceController {
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}
/**
* Initiate with an {@link AccessPoint}.
*/
public AddDevicePreferenceController2 init(AccessPoint accessPoint) {
mAccessPoint = accessPoint;
return this;
public void setWifiEntry(WifiEntry wifiEntry) {
mWifiEntry = wifiEntry;
}
@Override
public int getAvailabilityStatus() {
if (WifiDppUtils.isSupportConfiguratorQrCodeScanner(mContext, mAccessPoint)) {
if (WifiDppUtils.isSupportConfiguratorQrCodeScanner(mContext, mWifiEntry)) {
return AVAILABLE;
} else {
return CONDITIONALLY_UNAVAILABLE;
@@ -75,7 +70,7 @@ public class AddDevicePreferenceController2 extends BasePreferenceController {
private void launchWifiDppConfiguratorQrCodeScanner() {
final Intent intent = WifiDppUtils.getConfiguratorQrCodeScannerIntentOrNull(mContext,
mWifiManager, mAccessPoint);
mWifiManager, mWifiEntry);
if (intent == null) {
Log.e(TAG, "Launch Wi-Fi QR code scanner with a wrong Wi-Fi network!");

View File

@@ -23,10 +23,8 @@ import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.settings.SettingsEnums;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
@@ -41,10 +39,8 @@ import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.NetworkUtils;
import android.net.RouteInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.util.FeatureFlagUtils;
@@ -67,7 +63,7 @@ import com.android.settings.datausage.WifiDataUsageSummaryPreferenceController;
import com.android.settings.widget.EntityHeaderController;
import com.android.settings.wifi.WifiDialog;
import com.android.settings.wifi.WifiDialog.WifiDialogListener;
import com.android.settings.wifi.WifiUtils;
import com.android.settings.wifi.WifiEntryShell;
import com.android.settings.wifi.dpp.WifiDppUtils;
import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
@@ -77,15 +73,17 @@ import com.android.settingslib.core.lifecycle.events.OnPause;
import com.android.settingslib.core.lifecycle.events.OnResume;
import com.android.settingslib.widget.ActionButtonsPreference;
import com.android.settingslib.widget.LayoutPreference;
import com.android.settingslib.wifi.AccessPoint;
import com.android.settingslib.wifi.WifiTracker;
import com.android.settingslib.wifi.WifiTrackerFactory;
import com.android.wifitrackerlib.WifiEntry;
import com.android.wifitrackerlib.WifiEntry.ConnectedInfo;
import com.android.wifitrackerlib.WifiEntry.WifiEntryCallback;
import com.android.wifitrackerlib.WifiEntry.WifiEntryCallback.ConnectStatus;
import com.android.wifitrackerlib.WifiEntry.WifiEntryCallback.DisconnectStatus;
import com.android.wifitrackerlib.WifiEntry.WifiEntryCallback.ForgetStatus;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.StringJoiner;
import java.util.stream.Collectors;
@@ -95,7 +93,7 @@ import java.util.stream.Collectors;
*/
public class WifiDetailPreferenceController2 extends AbstractPreferenceController
implements PreferenceControllerMixin, WifiDialogListener, LifecycleObserver, OnPause,
OnResume {
OnResume, WifiEntryCallback {
private static final String TAG = "WifiDetailsPrefCtrl2";
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
@@ -133,21 +131,7 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
@VisibleForTesting
static final String KEY_IPV6_ADDRESSES_PREF = "ipv6_addresses";
private static final int STATE_NONE = 1;
private static final int STATE_ENABLE_WIFI = 2;
private static final int STATE_ENABLE_WIFI_FAILED = 3;
private static final int STATE_CONNECTING = 4;
private static final int STATE_CONNECTED = 5;
private static final int STATE_FAILED = 6;
private static final int STATE_NOT_IN_RANGE = 7;
private static final int STATE_DISCONNECTED = 8;
private static final long TIMEOUT = Duration.ofSeconds(10).toMillis();
// Be static to avoid too much object not be reset.
@VisibleForTesting
static CountDownTimer sTimer;
private AccessPoint mAccessPoint;
private final WifiEntry mWifiEntry;
private final ConnectivityManager mConnectivityManager;
private final PreferenceFragmentCompat mFragment;
private final Handler mHandler;
@@ -157,16 +141,9 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
private NetworkCapabilities mNetworkCapabilities;
private int mRssiSignalLevel = -1;
private String[] mSignalStr;
private WifiConfiguration mWifiConfig;
private WifiInfo mWifiInfo;
private final WifiManager mWifiManager;
private final WifiTracker mWifiTracker;
private final MetricsFeatureProvider mMetricsFeatureProvider;
private boolean mIsOutOfRange;
private boolean mIsEphemeral;
private boolean mConnected;
private int mConnectingState;
private WifiManager.ActionListener mConnectListener;
// UI elements - in order of appearance
private ActionButtonsPreference mButtonsPref;
@@ -189,36 +166,6 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
WifiDataUsageSummaryPreferenceController mSummaryHeaderController;
private final IconInjector mIconInjector;
private final IntentFilter mFilter;
// Passpoint information - cache it in case of losing these information after
// updateAccessPointFromScannedList(). For R2, we should update these data from
// WifiManager#getPasspointConfigurations() after users manage the passpoint profile.
private boolean mIsExpired;
private boolean mIsPasspointConfigurationR1;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION:
if (!intent.getBooleanExtra(WifiManager.EXTRA_MULTIPLE_NETWORKS_CHANGED,
false /* defaultValue */)) {
// only one network changed
WifiConfiguration wifiConfiguration = intent
.getParcelableExtra(WifiManager.EXTRA_WIFI_CONFIGURATION);
if (mAccessPoint.matches(wifiConfiguration)) {
mWifiConfig = wifiConfiguration;
}
}
// fall through
case WifiManager.NETWORK_STATE_CHANGED_ACTION:
case WifiManager.RSSI_CHANGED_ACTION:
refreshPage();
break;
}
}
};
private final NetworkRequest mNetworkRequest = new NetworkRequest.Builder()
.clearCapabilities().addTransportType(TRANSPORT_WIFI).build();
@@ -265,7 +212,8 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
|| hasCapabilityChanged(nc, NET_CAPABILITY_VALIDATED)
|| hasCapabilityChanged(nc, NET_CAPABILITY_CAPTIVE_PORTAL)
|| hasCapabilityChanged(nc, NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
mAccessPoint.update(mWifiConfig, mWifiInfo, mNetworkInfo);
// TODO(b/143326832): What to do with WifiEntry?
// mAccessPoint.update(mWifiConfig, mWifiInfo, mNetworkInfo);
refreshEntityHeader();
}
mNetworkCapabilities = nc;
@@ -277,37 +225,12 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
@Override
public void onLost(Network network) {
// Ephemeral network not a saved network, leave detail page once disconnected
if (mIsEphemeral && network.equals(mNetwork)) {
exitActivity();
if (!mWifiEntry.isSaved() && network.equals(mNetwork)) {
if (DEBUG) {
Log.d(TAG, "OnLost and exit WifiNetworkDetailsPage");
}
mFragment.getActivity().finish();
}
};
@VisibleForTesting
final WifiTracker.WifiListener mWifiListener = new WifiTracker.WifiListener() {
/** Called when the state of Wifi has changed. */
public void onWifiStateChanged(int state) {
Log.d(TAG, "onWifiStateChanged(" + state + ")");
if (mConnectingState == STATE_ENABLE_WIFI && state == WifiManager.WIFI_STATE_ENABLED) {
updateConnectingState(STATE_CONNECTING);
} else if (mConnectingState != STATE_NONE && state == WifiManager.WIFI_STATE_DISABLED) {
// update as disconnected once Wi-Fi disabled since may not received
// onConnectedChanged for this case.
updateConnectingState(STATE_DISCONNECTED);
}
}
/** Called when the connection state of wifi has changed. */
public void onConnectedChanged() {
refreshPage();
}
/**
* Called to indicate the list of AccessPoints has been updated and
* {@link WifiTracker#getAccessPoints()} should be called to get the updated list.
*/
public void onAccessPointsChanged() {
refreshPage();
}
};
@@ -315,7 +238,7 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
* To get an instance of {@link WifiDetailPreferenceController2}
*/
public static WifiDetailPreferenceController2 newInstance(
AccessPoint accessPoint,
WifiEntry wifiEntry,
ConnectivityManager connectivityManager,
Context context,
PreferenceFragmentCompat fragment,
@@ -324,13 +247,13 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
WifiManager wifiManager,
MetricsFeatureProvider metricsFeatureProvider) {
return new WifiDetailPreferenceController2(
accessPoint, connectivityManager, context, fragment, handler, lifecycle,
wifiEntry, connectivityManager, context, fragment, handler, lifecycle,
wifiManager, metricsFeatureProvider, new IconInjector(context));
}
@VisibleForTesting
/* package */ WifiDetailPreferenceController2(
AccessPoint accessPoint,
WifiEntry wifiEntry,
ConnectivityManager connectivityManager,
Context context,
PreferenceFragmentCompat fragment,
@@ -341,49 +264,18 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
IconInjector injector) {
super(context);
mAccessPoint = accessPoint;
mWifiEntry = wifiEntry;
mWifiEntry.setListener(this);
mConnectivityManager = connectivityManager;
mFragment = fragment;
mHandler = handler;
mSignalStr = context.getResources().getStringArray(R.array.wifi_signal);
mWifiConfig = accessPoint.getConfig();
mWifiManager = wifiManager;
mMetricsFeatureProvider = metricsFeatureProvider;
mIconInjector = injector;
mFilter = new IntentFilter();
mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
mFilter.addAction(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
mLifecycle = lifecycle;
lifecycle.addObserver(this);
mWifiTracker = WifiTrackerFactory.create(
mFragment.getActivity(),
mWifiListener,
mLifecycle,
true /*includeSaved*/,
true /*includeScans*/);
mConnected = mAccessPoint.isActive();
// When lost the network connection, WifiInfo/NetworkInfo will be clear. So causes we
// could not check if the AccessPoint is ephemeral. Need to cache it in first.
mIsEphemeral = mAccessPoint.isEphemeral();
mConnectingState = STATE_NONE;
mConnectListener = new WifiManager.ActionListener() {
@Override
public void onSuccess() {
// Do nothing
}
@Override
public void onFailure(int reason) {
updateConnectingState(STATE_FAILED);
}
};
mIsExpired = mAccessPoint.isExpired();
mIsPasspointConfigurationR1 = mAccessPoint.isPasspointConfigurationR1();
}
@Override
@@ -404,7 +296,8 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
setupEntityHeader(screen);
mButtonsPref = ((ActionButtonsPreference) screen.findPreference(KEY_BUTTONS_PREF))
.setButton1Text(R.string.forget)
.setButton1Text(!mWifiEntry.isSaved()
? R.string.wifi_disconnect_button_text : R.string.forget)
.setButton1Icon(R.drawable.ic_settings_delete)
.setButton1OnClickListener(view -> forgetNetwork())
.setButton2Text(R.string.wifi_sign_in_button_text)
@@ -418,11 +311,6 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
.setButton4Icon(R.drawable.ic_qrcode_24dp)
.setButton4OnClickListener(view -> shareNetwork());
if (isPasspointConfigurationR1Expired()) {
// Hide Connect button.
mButtonsPref.setButton3Visible(false);
}
mSignalStrengthPref = screen.findPreference(KEY_SIGNAL_STRENGTH_PREF);
mTxLinkSpeedPref = screen.findPreference(KEY_TX_LINK_SPEED);
mRxLinkSpeedPref = screen.findPreference(KEY_RX_LINK_SPEED);
@@ -439,7 +327,7 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
mIpv6Category = screen.findPreference(KEY_IPV6_CATEGORY);
mIpv6AddressPref = screen.findPreference(KEY_IPV6_ADDRESSES_PREF);
mSecurityPref.setSummary(mAccessPoint.getSecurityString(/* concise */ false));
mSecurityPref.setSummary(WifiEntryShell.getSecurityString(mWifiEntry, /* concise */ false));
}
private void setupEntityHeader(PreferenceScreen screen) {
@@ -451,7 +339,8 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
mDataUsageSummaryPref.setVisible(true);
mSummaryHeaderController =
new WifiDataUsageSummaryPreferenceController(mFragment.getActivity(),
mLifecycle, (PreferenceFragmentCompat) mFragment, mAccessPoint.getSsid());
mLifecycle, (PreferenceFragmentCompat) mFragment,
mWifiEntry.getTitle());
return;
}
@@ -464,22 +353,14 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
mEntityHeaderController.setLabel(mAccessPoint.getTitle());
mEntityHeaderController.setLabel(mWifiEntry.getTitle());
}
private void refreshEntityHeader() {
if (usingDataUsageHeader(mContext)) {
mSummaryHeaderController.updateState(mDataUsageSummaryPref);
} else {
String summary;
if (isPasspointConfigurationR1Expired()) {
// Not able to get summary from AccessPoint because we may lost
// PasspointConfiguration information after updateAccessPointFromScannedList().
summary = mContext.getResources().getString(
com.android.settingslib.R.string.wifi_passpoint_expired);
} else {
summary = mAccessPoint.getSettingsSummary(true /* convertSavedAsDisconnected */);
}
String summary = mWifiEntry.getSummary();
mEntityHeaderController
.setSummary(summary)
@@ -489,9 +370,19 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
}
private void updateNetworkInfo() {
if (mWifiEntry.getConnectedState() == WifiEntry.CONNECTED_STATE_CONNECTED) {
mNetwork = mWifiManager.getCurrentNetwork();
mLinkProperties = mConnectivityManager.getLinkProperties(mNetwork);
mNetworkCapabilities = mConnectivityManager.getNetworkCapabilities(mNetwork);
mNetworkInfo = mConnectivityManager.getNetworkInfo(mNetwork);
mWifiInfo = mWifiManager.getConnectionInfo();
} else {
mNetwork = null;
mLinkProperties = null;
mNetworkCapabilities = null;
mNetworkInfo = null;
mWifiInfo = null;
}
}
@Override
@@ -500,27 +391,16 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
// NetworkCallback only looks at changes to mNetwork.
updateNetworkInfo();
refreshPage();
mContext.registerReceiver(mReceiver, mFilter);
mConnectivityManager.registerNetworkCallback(mNetworkRequest, mNetworkCallback,
mHandler);
}
@Override
public void onPause() {
mNetwork = null;
mLinkProperties = null;
mNetworkCapabilities = null;
mNetworkInfo = null;
mWifiInfo = null;
mContext.unregisterReceiver(mReceiver);
mConnectivityManager.unregisterNetworkCallback(mNetworkCallback);
}
private void refreshPage() {
if (!updateAccessPoint()) {
return;
}
Log.d(TAG, "Update UI!");
// refresh header
@@ -545,65 +425,11 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
refreshMacAddress();
}
@VisibleForTesting
boolean updateAccessPoint() {
boolean changed = false;
// remember mIsOutOfRange as old before updated
boolean oldState = mIsOutOfRange;
updateAccessPointFromScannedList();
if (mAccessPoint.isActive()) {
updateNetworkInfo();
mNetworkInfo = mConnectivityManager.getNetworkInfo(mNetwork);
mWifiInfo = mWifiManager.getConnectionInfo();
if (mNetwork == null || mNetworkInfo == null || mWifiInfo == null) {
// Once connected, can't get mNetwork immediately, return false and wait for
// next time to update UI. also reset {@code mIsOutOfRange}
mIsOutOfRange = oldState;
return false;
}
changed |= mAccessPoint.update(mWifiConfig, mWifiInfo, mNetworkInfo);
}
// signal level changed
changed |= mRssiSignalLevel != mAccessPoint.getLevel();
// In/Out of range changed
changed |= oldState != mIsOutOfRange;
// connect state changed
if (mConnected != mAccessPoint.isActive()) {
mConnected = mAccessPoint.isActive();
changed = true;
updateConnectingState(mAccessPoint.isActive() ? STATE_CONNECTED : STATE_DISCONNECTED);
}
return changed;
}
private void updateAccessPointFromScannedList() {
mIsOutOfRange = true;
for (AccessPoint ap : mWifiTracker.getAccessPoints()) {
if (mAccessPoint.matches(ap)) {
mAccessPoint = ap;
mWifiConfig = ap.getConfig();
mIsOutOfRange = !mAccessPoint.isReachable();
return;
}
}
}
private void exitActivity() {
if (DEBUG) {
Log.d(TAG, "Exiting the WifiNetworkDetailsPage");
}
mFragment.getActivity().finish();
}
private void refreshRssiViews() {
int signalLevel = mAccessPoint.getLevel();
int signalLevel = mWifiEntry.getLevel();
// Disappears signal view if not in range. e.g. for saved networks.
if (mIsOutOfRange) {
if (signalLevel == WifiEntry.WIFI_LEVEL_UNREACHABLE) {
mSignalStrengthPref.setVisible(false);
mRssiSignalLevel = -1;
return;
@@ -656,24 +482,26 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
}
private void refreshFrequency() {
if (mWifiInfo == null) {
final ConnectedInfo connectedInfo = mWifiEntry.getConnectedInfo();
if (connectedInfo == null) {
mFrequencyPref.setVisible(false);
return;
}
final int frequency = mWifiInfo.getFrequency();
final int frequency = connectedInfo.frequencyMhz;
String band = null;
if (frequency >= AccessPoint.LOWER_FREQ_24GHZ
&& frequency < AccessPoint.HIGHER_FREQ_24GHZ) {
if (frequency >= WifiEntryShell.LOWER_FREQ_24GHZ
&& frequency < WifiEntryShell.HIGHER_FREQ_24GHZ) {
band = mContext.getResources().getString(R.string.wifi_band_24ghz);
} else if (frequency >= AccessPoint.LOWER_FREQ_5GHZ
&& frequency < AccessPoint.HIGHER_FREQ_5GHZ) {
} else if (frequency >= WifiEntryShell.LOWER_FREQ_5GHZ
&& frequency < WifiEntryShell.HIGHER_FREQ_5GHZ) {
band = mContext.getResources().getString(R.string.wifi_band_5ghz);
} else {
Log.e(TAG, "Unexpected frequency " + frequency);
// Connecting state is unstable, make it disappeared if unexpected
if (mConnectingState == STATE_CONNECTING) {
if (mWifiEntry.getConnectedState() == WifiEntry.CONNECTED_STATE_CONNECTING) {
mFrequencyPref.setVisible(false);
} else {
Log.e(TAG, "Unexpected frequency " + frequency);
}
return;
}
@@ -706,9 +534,9 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
}
private void refreshSsid() {
if (mAccessPoint.isPasspoint() || mAccessPoint.isOsuProvider()) {
if (WifiEntryShell.isPasspoint(mWifiEntry) || WifiEntryShell.isOsuProvider(mWifiEntry)) {
mSsidPref.setVisible(true);
mSsidPref.setSummary(mAccessPoint.getSsidStr());
mSsidPref.setSummary(mWifiEntry.getTitle());
} else {
mSsidPref.setVisible(false);
}
@@ -733,15 +561,8 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
}
private String getMacAddress() {
if (mWifiInfo != null) {
// get MAC address from connected network information
return mWifiInfo.getMacAddress();
}
// return randomized MAC address
if (mWifiConfig != null && mWifiConfig.macRandomizationSetting
== WifiConfiguration.RANDOMIZATION_PERSISTENT) {
return mWifiConfig.getRandomizedMacAddress().toString();
if (mWifiEntry.isSaved() && mWifiEntry.getPrivacy() == WifiEntry.PRIVACY_RANDOMIZED_MAC) {
return mWifiEntry.getMacAddress();
}
// return device MAC address
@@ -764,13 +585,9 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
}
private void refreshButtons() {
// Ephemeral network won't be removed permanently, but be putted in blacklist.
mButtonsPref.setButton1Text(
mIsEphemeral ? R.string.wifi_disconnect_button_text : R.string.forget);
boolean canForgetNetwork = canForgetNetwork();
boolean canForgetNetwork = mWifiEntry.canForget();
boolean canSignIntoNetwork = canSignIntoNetwork();
boolean canConnectNetwork = canConnectNetwork() && !isPasspointConfigurationR1Expired();
boolean canConnectNetwork = mWifiEntry.canConnect();
boolean canShareNetwork = canShareNetwork();
mButtonsPref.setButton1Visible(canForgetNetwork);
@@ -783,18 +600,10 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
|| canShareNetwork);
}
private boolean canConnectNetwork() {
// Display connect button for disconnected AP even not in the range.
return !mAccessPoint.isActive();
}
private boolean isPasspointConfigurationR1Expired() {
return mIsPasspointConfigurationR1 && mIsExpired;
}
private void refreshIpLayerInfo() {
// Hide IP layer info if not a connected network.
if (!mAccessPoint.isActive() || mNetwork == null || mLinkProperties == null) {
if (mWifiEntry.getConnectedState() != WifiEntry.CONNECTED_STATE_CONNECTED
|| mNetwork == null || mLinkProperties == null) {
mIpAddressPref.setVisible(false);
mSubnetPref.setVisible(false);
mGatewayPref.setVisible(false);
@@ -856,48 +665,37 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
}
}
/**
* Returns whether the network represented by this preference can be forgotten.
*/
private boolean canForgetNetwork() {
return (mWifiInfo != null && mWifiInfo.isEphemeral()) || canModifyNetwork()
|| mAccessPoint.isPasspoint() || mAccessPoint.isPasspointConfig();
}
/**
* Returns whether the network represented by this preference can be modified.
*/
public boolean canModifyNetwork() {
return mWifiConfig != null && !WifiUtils.isNetworkLockedDown(mContext, mWifiConfig);
return WifiEntryShell.canModifyNetwork(mWifiEntry);
}
/**
* Returns whether the user can sign into the network represented by this preference.
*/
private boolean canSignIntoNetwork() {
return mAccessPoint.isActive() && WifiUtils.canSignIntoNetwork(mNetworkCapabilities);
return mWifiEntry.canSignIn();
}
/**
* Returns whether the user can share the network represented by this preference with QR code.
*/
private boolean canShareNetwork() {
return mAccessPoint.getConfig() != null
&& WifiDppUtils.isSupportConfiguratorQrCodeGenerator(mContext, mAccessPoint);
return mWifiEntry.canShare();
}
/**
* Forgets the wifi network associated with this preference.
*/
private void forgetNetwork() {
if (mWifiInfo != null && mWifiInfo.isEphemeral()) {
mWifiManager.disableEphemeralNetwork(mWifiInfo.getSSID());
} else if (mAccessPoint.isPasspoint() || mAccessPoint.isPasspointConfig()) {
if (WifiEntryShell.isPasspoint(mWifiEntry)) {
// Post a dialog to confirm if user really want to forget the passpoint network.
showConfirmForgetDialog();
return;
} else if (mWifiConfig != null) {
mWifiManager.forget(mWifiConfig.networkId, null /* action listener */);
} else {
mWifiEntry.forget();
}
mMetricsFeatureProvider.action(
@@ -910,10 +708,10 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
final AlertDialog dialog = new AlertDialog.Builder(mContext)
.setPositiveButton(R.string.forget, ((dialog1, which) -> {
try {
mWifiManager.removePasspointConfiguration(mAccessPoint.getPasspointFqdn());
mWifiEntry.forget();
} catch (RuntimeException e) {
Log.e(TAG, "Failed to remove Passpoint configuration for "
+ mAccessPoint.getPasspointFqdn());
+ WifiEntryShell.getPasspointFqdn(mWifiEntry));
}
mMetricsFeatureProvider.action(
mFragment.getActivity(), SettingsEnums.ACTION_WIFI_FORGET);
@@ -931,7 +729,7 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
*/
private void launchWifiDppConfiguratorActivity() {
final Intent intent = WifiDppUtils.getConfiguratorQrCodeGeneratorIntentOrNull(mContext,
mWifiManager, mAccessPoint);
mWifiManager, mWifiEntry);
if (intent == null) {
Log.e(TAG, "Launch Wi-Fi DPP QR code generator with a wrong Wi-Fi network!");
@@ -1005,203 +803,95 @@ public class WifiDetailPreferenceController2 extends AbstractPreferenceControlle
@VisibleForTesting
void connectNetwork() {
final Activity activity = mFragment.getActivity();
// error handling, connected/saved network should have mWifiConfig.
if (mWifiConfig == null) {
Toast.makeText(activity,
R.string.wifi_failed_connect_message,
Toast.LENGTH_SHORT).show();
return;
}
// init state before connect
mConnectingState = STATE_NONE;
if (mWifiManager.isWifiEnabled()) {
updateConnectingState(STATE_CONNECTING);
} else {
// Enable Wi-Fi automatically to connect AP
updateConnectingState(STATE_ENABLE_WIFI);
}
}
private void updateConnectingState(int state) {
final Activity activity = mFragment.getActivity();
Log.d(TAG, "updateConnectingState from " + mConnectingState + " to " + state);
switch (mConnectingState) {
case STATE_NONE:
case STATE_ENABLE_WIFI:
if (state == STATE_ENABLE_WIFI) {
Log.d(TAG, "Turn on Wi-Fi automatically!");
updateConnectedButton(STATE_ENABLE_WIFI);
Toast.makeText(activity,
R.string.wifi_turned_on_message,
Toast.LENGTH_SHORT).show();
mWifiManager.setWifiEnabled(true);
// start timer for error handling
startTimer();
} else if (state == STATE_CONNECTING) {
Log.d(TAG, "connecting...");
updateConnectedButton(STATE_CONNECTING);
if (mAccessPoint.isPasspoint()) {
mWifiManager.connect(mWifiConfig, mConnectListener);
} else {
mWifiManager.connect(mWifiConfig.networkId, mConnectListener);
}
// start timer for error handling since framework didn't call back if failed
startTimer();
} else if (state == STATE_ENABLE_WIFI_FAILED) {
Log.e(TAG, "Wi-Fi failed to enable network!");
stopTimer();
// reset state
state = STATE_NONE;
Toast.makeText(activity,
R.string.wifi_failed_connect_message,
Toast.LENGTH_SHORT).show();
updateConnectedButton(STATE_ENABLE_WIFI_FAILED);
}
// Do not break here for disconnected event.
case STATE_CONNECTED:
if (state == STATE_DISCONNECTED) {
Log.d(TAG, "disconnected");
// reset state
state = STATE_NONE;
updateConnectedButton(STATE_DISCONNECTED);
refreshPage();
// clear for getting MAC Address from saved configuration
mWifiInfo = null;
}
break;
case STATE_CONNECTING:
if (state == STATE_CONNECTED) {
Log.d(TAG, "connected");
stopTimer();
updateConnectedButton(STATE_CONNECTED);
Toast.makeText(activity,
mContext.getString(R.string.wifi_connected_to_message,
mAccessPoint.getTitle()),
Toast.LENGTH_SHORT).show();
refreshPage();
} else if (state == STATE_NOT_IN_RANGE) {
Log.d(TAG, "AP not in range");
stopTimer();
// reset state
state = STATE_NONE;
Toast.makeText(activity,
R.string.wifi_not_in_range_message,
Toast.LENGTH_SHORT).show();
updateConnectedButton(STATE_NOT_IN_RANGE);
} else if (state == STATE_FAILED) {
Log.d(TAG, "failed");
stopTimer();
// reset state
state = STATE_NONE;
Toast.makeText(activity,
R.string.wifi_failed_connect_message,
Toast.LENGTH_SHORT).show();
updateConnectedButton(STATE_FAILED);
}
break;
default:
Log.e(TAG, "Invalid state : " + mConnectingState);
// don't update invalid state
return;
}
mConnectingState = state;
}
private void updateConnectedButton(int state) {
switch (state) {
case STATE_ENABLE_WIFI:
case STATE_CONNECTING:
mButtonsPref.setButton3Text(R.string.wifi_connecting)
.setButton3Enabled(false);
break;
case STATE_CONNECTED:
// init button state and set as invisible
mButtonsPref.setButton3Text(R.string.wifi_connect)
.setButton3Icon(R.drawable.ic_settings_wireless)
.setButton3Enabled(true)
.setButton3Visible(false);
break;
case STATE_DISCONNECTED:
case STATE_NOT_IN_RANGE:
case STATE_FAILED:
case STATE_ENABLE_WIFI_FAILED:
if (isPasspointConfigurationR1Expired()) {
// Hide Connect button.
mButtonsPref.setButton3Visible(false);
} else {
mButtonsPref.setButton3Text(R.string.wifi_connect)
.setButton3Icon(R.drawable.ic_settings_wireless)
.setButton3Enabled(true)
.setButton3Visible(true);
}
break;
default:
Log.e(TAG, "Invalid connect button state : " + state);
break;
}
}
private void startTimer() {
if (sTimer != null) {
stopTimer();
}
sTimer = new CountDownTimer(TIMEOUT, TIMEOUT + 1) {
@Override
public void onTick(long millisUntilFinished) {
// Do nothing
}
@Override
public void onFinish() {
if (mFragment == null || mFragment.getActivity() == null) {
Log.d(TAG, "Ignore timeout since activity not exist!");
return;
}
Log.e(TAG, "Timeout for state:" + mConnectingState);
if (mConnectingState == STATE_ENABLE_WIFI) {
updateConnectingState(STATE_ENABLE_WIFI_FAILED);
} else if (mConnectingState == STATE_CONNECTING) {
updateAccessPointFromScannedList();
if (mIsOutOfRange) {
updateConnectingState(STATE_NOT_IN_RANGE);
} else {
updateConnectingState(STATE_FAILED);
}
}
}
};
sTimer.start();
}
private void stopTimer() {
if (sTimer == null) return;
sTimer.cancel();
sTimer = null;
// TODO(b/143326832): What to do with WifiManager#isWifiEnabled() false case?
mButtonsPref.setButton3Text(R.string.wifi_connecting).setButton3Enabled(false);
mWifiEntry.connect();
}
private void refreshMacTitle() {
if (mWifiConfig == null) {
if (!mWifiEntry.isSaved()) {
return;
}
// For saved Passpoint network, framework doesn't have the field to keep the MAC choice
// persistently, so Passpoint network will always use the default value so far, which is
// randomized MAC address, so don't need to modify title.
if (mAccessPoint.isPasspoint() || mAccessPoint.isPasspointConfig()) {
if (WifiEntryShell.isPasspoint(mWifiEntry)) {
return;
}
mMacAddressPref.setTitle(
(mWifiConfig.macRandomizationSetting
== WifiConfiguration.RANDOMIZATION_PERSISTENT)
(mWifiEntry.getPrivacy() == WifiEntry.PRIVACY_RANDOMIZED_MAC)
? R.string.wifi_advanced_randomized_mac_address_title
: R.string.wifi_advanced_device_mac_address_title);
}
/**
* Indicates the state of the WifiEntry has changed and clients may retrieve updates through
* the WifiEntry getter methods.
*/
@Override
public void onUpdated() {
refreshPage();
}
/**
* Result of the connect request indicated by the CONNECT_STATUS constants.
*/
@Override
public void onConnectResult(@ConnectStatus int status) {
if (status == WifiEntryCallback.CONNECT_STATUS_SUCCESS) {
Toast.makeText(mContext,
mContext.getString(R.string.wifi_connected_to_message, mWifiEntry.getTitle()),
Toast.LENGTH_SHORT).show();
updateNetworkInfo();
refreshPage();
} else if (mWifiEntry.getLevel() == WifiEntry.WIFI_LEVEL_UNREACHABLE) {
Toast.makeText(mContext,
R.string.wifi_not_in_range_message,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext,
R.string.wifi_failed_connect_message,
Toast.LENGTH_SHORT).show();
}
mButtonsPref.setButton3Text(R.string.wifi_connect)
.setButton3Icon(R.drawable.ic_settings_wireless)
.setButton3Enabled(true)
.setButton3Visible(true);
}
/**
* Result of the disconnect request indicated by the DISCONNECT_STATUS constants.
*/
@Override
public void onDisconnectResult(@DisconnectStatus int status) {
if (status != WifiEntryCallback.DISCONNECT_STATUS_SUCCESS) {
Log.e(TAG, "Disconnect Wi-Fi network failed");
}
updateNetworkInfo();
refreshPage();
}
/**
* Result of the forget request indicated by the FORGET_STATUS constants.
*/
@Override
public void onForgetResult(@ForgetStatus int status) {
if (status != WifiEntryCallback.FORGET_STATUS_SUCCESS) {
Log.e(TAG, "Forget Wi-Fi network failed");
}
mMetricsFeatureProvider.action(mFragment.getActivity(), SettingsEnums.ACTION_WIFI_FORGET);
mFragment.getActivity().finish();
}
/**
* Result of the sign-in request indicated by the SIGNIN_STATUS constants.
*/
@Override
public void onSignInResult(@SignInStatus int status) {
refreshPage();
}
}

View File

@@ -18,8 +18,6 @@ package com.android.settings.wifi.details2;
import android.app.backup.BackupManager;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import androidx.annotation.VisibleForTesting;
import androidx.preference.DropDownPreference;
@@ -29,6 +27,7 @@ import androidx.preference.PreferenceScreen;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.wifi.WifiDialog;
import com.android.settingslib.core.AbstractPreferenceController;
import com.android.wifitrackerlib.WifiEntry;
/**
* {@link AbstractPreferenceController} that controls whether the wifi network is metered or not
@@ -37,14 +36,12 @@ public class WifiMeteredPreferenceController2 extends BasePreferenceController i
Preference.OnPreferenceChangeListener, WifiDialog.WifiDialogListener {
private static final String KEY_WIFI_METERED = "metered";
private WifiConfiguration mWifiConfiguration;
private WifiManager mWifiManager;
private WifiEntry mWifiEntry;
private Preference mPreference;
public WifiMeteredPreferenceController2(Context context, WifiConfiguration wifiConfiguration) {
public WifiMeteredPreferenceController2(Context context, WifiEntry wifiEntry) {
super(context, KEY_WIFI_METERED);
mWifiConfiguration = wifiConfiguration;
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
mWifiEntry = wifiEntry;
}
@Override
@@ -62,10 +59,10 @@ public class WifiMeteredPreferenceController2 extends BasePreferenceController i
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (mWifiConfiguration != null) {
mWifiConfiguration.meteredOverride = Integer.parseInt((String) newValue);
if (mWifiEntry.isSaved()) {
mWifiEntry.setMeteredChoice(Integer.parseInt((String) newValue));
}
mWifiManager.updateNetwork(mWifiConfiguration);
// Stage the backup of the SettingsProvider package which backs this up
BackupManager.dataChanged("com.android.providers.settings");
updateSummary((DropDownPreference) preference, getMeteredOverride());
@@ -74,11 +71,11 @@ public class WifiMeteredPreferenceController2 extends BasePreferenceController i
@VisibleForTesting
int getMeteredOverride() {
if (mWifiConfiguration != null) {
if (mWifiEntry.isSaved()) {
// Wrap the meteredOverride since robolectric cannot recognize it
return mWifiConfiguration.meteredOverride;
return mWifiEntry.getMeteredChoice();
}
return WifiConfiguration.METERED_OVERRIDE_NONE;
return WifiEntry.METERED_CHOICE_AUTO;
}
private void updateSummary(DropDownPreference preference, int meteredOverride) {
@@ -93,16 +90,17 @@ public class WifiMeteredPreferenceController2 extends BasePreferenceController i
@Override
public void onSubmit(WifiDialog dialog) {
if (dialog.getController() != null) {
final WifiConfiguration newConfig = dialog.getController().getConfig();
if (newConfig == null || mWifiConfiguration == null) {
return;
}
if (newConfig.meteredOverride != mWifiConfiguration.meteredOverride) {
mWifiConfiguration = newConfig;
onPreferenceChange(mPreference, String.valueOf(newConfig.meteredOverride));
}
}
// TODO(b/143326832): Create WifiDialog2 and let it work for WifiEntry.
//if (dialog.getController() != null) {
// final WifiConfiguration newConfig = dialog.getController().getConfig();
// if (newConfig == null || mWifiConfiguration == null) {
// return;
// }
//
// if (newConfig.meteredOverride != mWifiConfiguration.meteredOverride) {
// mWifiConfiguration = newConfig;
// onPreferenceChange(mPreference, String.valueOf(newConfig.meteredOverride));
// }
//}
}
}

View File

@@ -21,45 +21,59 @@ import android.app.Dialog;
import android.app.settings.SettingsEnums;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkScoreManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Process;
import android.os.SimpleClock;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.android.settings.R;
import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.wifi.WifiConfigUiBase;
import com.android.settings.wifi.WifiDialog;
import com.android.settings.wifi.savedaccesspoints2.SavedAccessPointsWifiSettings2;
import com.android.settingslib.RestrictedLockUtils;
import com.android.settingslib.RestrictedLockUtilsInternal;
import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.wifi.AccessPoint;
import com.android.wifitrackerlib.NetworkDetailsTracker;
import com.android.wifitrackerlib.WifiEntry;
import java.time.Clock;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
/**
* Detail page for the currently connected wifi network.
*
* <p>The AccessPoint should be saved to the intent Extras when launching this class via
* {@link AccessPoint#saveWifiState(Bundle)} in order to properly render this page.
* <p>The key of {@link WifiEntry} should be saved to the intent Extras when launching this class
* in order to properly render this page.
*/
public class WifiNetworkDetailsFragment2 extends DashboardFragment implements
WifiDialog.WifiDialogListener {
private static final String TAG = "WifiNetworkDetailsFrg2";
private AccessPoint mAccessPoint;
// Max age of tracked WifiEntries
private static final long MAX_SCAN_AGE_MILLIS = 15_000;
// Interval between initiating SavedNetworkTracker scans
private static final long SCAN_INTERVAL_MILLIS = 10_000;
private NetworkDetailsTracker mNetworkDetailsTracker;
private HandlerThread mWorkerThread;
private WifiDetailPreferenceController2 mWifiDetailPreferenceController2;
private List<WifiDialog.WifiDialogListener> mWifiDialogListeners = new ArrayList<>();
@Override
public void onAttach(Context context) {
mAccessPoint = new AccessPoint(context, getArguments());
super.onAttach(context);
public void onDestroy() {
mWorkerThread.quit();
super.onDestroy();
}
@Override
@@ -87,15 +101,15 @@ public class WifiNetworkDetailsFragment2 extends DashboardFragment implements
@Override
public Dialog onCreateDialog(int dialogId) {
if (getActivity() == null || mWifiDetailPreferenceController2 == null
|| mAccessPoint == null) {
if (getActivity() == null || mWifiDetailPreferenceController2 == null) {
return null;
}
return WifiDialog.createModal(getActivity(), this, mAccessPoint,
WifiConfigUiBase.MODE_MODIFY);
// TODO(b/143326832): Replace it with WifiEntry.
return null;
//return WifiDialog.createModal(getActivity(), this, mAccessPoint,
// WifiConfigUiBase.MODE_MODIFY);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuItem item = menu.add(0, Menu.FIRST, 0, R.string.wifi_modify);
@@ -124,9 +138,11 @@ public class WifiNetworkDetailsFragment2 extends DashboardFragment implements
protected List<AbstractPreferenceController> createPreferenceControllers(Context context) {
final List<AbstractPreferenceController> controllers = new ArrayList<>();
final ConnectivityManager cm = context.getSystemService(ConnectivityManager.class);
setupNetworksDetailTracker();
final WifiEntry wifiEntry = mNetworkDetailsTracker.getWifiEntry();
mWifiDetailPreferenceController2 = WifiDetailPreferenceController2.newInstance(
mAccessPoint,
wifiEntry,
cm,
context,
this,
@@ -134,20 +150,20 @@ public class WifiNetworkDetailsFragment2 extends DashboardFragment implements
getSettingsLifecycle(),
context.getSystemService(WifiManager.class),
mMetricsFeatureProvider);
controllers.add(mWifiDetailPreferenceController2);
controllers.add(new AddDevicePreferenceController2(context).init(mAccessPoint));
final AddDevicePreferenceController2 addDevicePreferenceController2 =
new AddDevicePreferenceController2(context);
addDevicePreferenceController2.setWifiEntry(wifiEntry);
controllers.add(addDevicePreferenceController2);
final WifiMeteredPreferenceController2 meteredPreferenceController2 =
new WifiMeteredPreferenceController2(context, mAccessPoint.getConfig());
new WifiMeteredPreferenceController2(context, wifiEntry);
controllers.add(meteredPreferenceController2);
final WifiPrivacyPreferenceController2 privacyController2 =
new WifiPrivacyPreferenceController2(context);
privacyController2.setWifiConfiguration(mAccessPoint.getConfig());
privacyController2.setIsEphemeral(mAccessPoint.isEphemeral());
privacyController2.setIsPasspoint(
mAccessPoint.isPasspoint() || mAccessPoint.isPasspointConfig());
privacyController2.setWifiEntry(wifiEntry);
controllers.add(privacyController2);
// Sets callback listener for wifi dialog.
@@ -164,4 +180,35 @@ public class WifiNetworkDetailsFragment2 extends DashboardFragment implements
listener.onSubmit(dialog);
}
}
private void setupNetworksDetailTracker() {
if (mNetworkDetailsTracker != null) {
return;
}
final Context context = getContext();
mWorkerThread = new HandlerThread(TAG
+ "{" + Integer.toHexString(System.identityHashCode(this)) + "}",
Process.THREAD_PRIORITY_BACKGROUND);
mWorkerThread.start();
final Clock elapsedRealtimeClock = new SimpleClock(ZoneOffset.UTC) {
@Override
public long millis() {
return SystemClock.elapsedRealtime();
}
};
mNetworkDetailsTracker = NetworkDetailsTracker.createNetworkDetailsTracker(
getSettingsLifecycle(),
context,
context.getSystemService(WifiManager.class),
context.getSystemService(ConnectivityManager.class),
context.getSystemService(NetworkScoreManager.class),
new Handler(Looper.getMainLooper()),
mWorkerThread.getThreadHandler(),
elapsedRealtimeClock,
MAX_SCAN_AGE_MILLIS,
SCAN_INTERVAL_MILLIS,
getArguments().getString(SavedAccessPointsWifiSettings2.KEY_KEY));
}
}

View File

@@ -17,8 +17,6 @@
package com.android.settings.wifi.details2;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import androidx.annotation.VisibleForTesting;
@@ -30,6 +28,7 @@ import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.wifi.WifiDialog;
import com.android.settingslib.core.AbstractPreferenceController;
import com.android.wifitrackerlib.WifiEntry;
/**
* {@link AbstractPreferenceController} that controls whether the wifi network is mac randomized
@@ -39,28 +38,18 @@ public class WifiPrivacyPreferenceController2 extends BasePreferenceController i
Preference.OnPreferenceChangeListener, WifiDialog.WifiDialogListener {
private static final String KEY_WIFI_PRIVACY = "privacy";
private WifiConfiguration mWifiConfiguration;
private WifiManager mWifiManager;
private boolean mIsEphemeral = false;
private boolean mIsPasspoint = false;
private WifiEntry mWifiEntry;
private Preference mPreference;
public WifiPrivacyPreferenceController2(Context context) {
super(context, KEY_WIFI_PRIVACY);
mWifiConfiguration = null;
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}
public void setWifiConfiguration(WifiConfiguration wifiConfiguration) {
mWifiConfiguration = wifiConfiguration;
}
public void setIsEphemeral(boolean isEphemeral) {
mIsEphemeral = isEphemeral;
}
public void setIsPasspoint(boolean isPasspoint) {
mIsPasspoint = isPasspoint;
public void setWifiEntry(WifiEntry wifiEntry) {
mWifiEntry = wifiEntry;
}
@Override
@@ -83,7 +72,7 @@ public class WifiPrivacyPreferenceController2 extends BasePreferenceController i
updateSummary(dropDownPreference, randomizationLevel);
// Makes preference not selectable, when this is a ephemeral network.
if (mIsEphemeral || mIsPasspoint) {
if (!mWifiEntry.canSetPrivacy()) {
preference.setSelectable(false);
dropDownPreference.setSummary(R.string.wifi_privacy_settings_ephemeral_summary);
}
@@ -91,27 +80,26 @@ public class WifiPrivacyPreferenceController2 extends BasePreferenceController i
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (mWifiConfiguration != null) {
mWifiConfiguration.macRandomizationSetting = Integer.parseInt((String) newValue);
mWifiManager.updateNetwork(mWifiConfiguration);
final int privacy = Integer.parseInt((String) newValue);
if (mWifiEntry.isSaved()) {
mWifiEntry.setPrivacy(privacy);
// To activate changing, we need to reconnect network. WiFi will auto connect to
// current network after disconnect(). Only needed when this is connected network.
final WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
if (wifiInfo != null && wifiInfo.getNetworkId() == mWifiConfiguration.networkId) {
mWifiManager.disconnect();
if (mWifiEntry.getConnectedState() == WifiEntry.CONNECTED_STATE_CONNECTED) {
mWifiEntry.disconnect();
}
}
updateSummary((DropDownPreference) preference, Integer.parseInt((String) newValue));
updateSummary((DropDownPreference) preference, privacy);
return true;
}
@VisibleForTesting
int getRandomizationValue() {
if (mWifiConfiguration != null) {
return mWifiConfiguration.macRandomizationSetting;
if (mWifiEntry.isSaved()) {
return mWifiEntry.getPrivacy();
}
return WifiConfiguration.RANDOMIZATION_PERSISTENT;
return WifiEntry.PRIVACY_RANDOMIZED_MAC;
}
private static final int PREF_RANDOMIZATION_PERSISTENT = 0;
@@ -124,7 +112,7 @@ public class WifiPrivacyPreferenceController2 extends BasePreferenceController i
* @return index value of preference
*/
public static int translateMacRandomizedValueToPrefValue(int macRandomized) {
return (macRandomized == WifiConfiguration.RANDOMIZATION_PERSISTENT)
return (macRandomized == WifiEntry.PRIVACY_RANDOMIZED_MAC)
? PREF_RANDOMIZATION_PERSISTENT : PREF_RANDOMIZATION_NONE;
}
@@ -136,7 +124,7 @@ public class WifiPrivacyPreferenceController2 extends BasePreferenceController i
*/
public static int translatePrefValueToMacRandomizedValue(int prefMacRandomized) {
return (prefMacRandomized == PREF_RANDOMIZATION_PERSISTENT)
? WifiConfiguration.RANDOMIZATION_PERSISTENT : WifiConfiguration.RANDOMIZATION_NONE;
? WifiEntry.PRIVACY_RANDOMIZED_MAC : WifiEntry.PRIVACY_DEVICE_MAC;
}
private void updateSummary(DropDownPreference preference, int macRandomized) {
@@ -147,16 +135,17 @@ public class WifiPrivacyPreferenceController2 extends BasePreferenceController i
@Override
public void onSubmit(WifiDialog dialog) {
if (dialog.getController() != null) {
final WifiConfiguration newConfig = dialog.getController().getConfig();
if (newConfig == null || mWifiConfiguration == null) {
return;
}
if (newConfig.macRandomizationSetting != mWifiConfiguration.macRandomizationSetting) {
mWifiConfiguration = newConfig;
onPreferenceChange(mPreference, String.valueOf(newConfig.macRandomizationSetting));
}
}
// TODO(b/143326832): Create WifiDialog2 and let it work for WifiEntry.
//if (dialog.getController() != null) {
// final WifiConfiguration newConfig = dialog.getController().getConfig();
// if (newConfig == null || mWifiConfiguration == null) {
// return;
// }
//
// if (newConfig.macRandomizationSetting != mWifiConfiguration.macRandomizationSetting) {
// mWifiConfiguration = newConfig;
// onPreferenceChange(mPreference, String.valueOf(newConfig.macRandomizationSetting));
// }
//}
}
}

View File

@@ -32,7 +32,9 @@ import android.os.Vibrator;
import android.text.TextUtils;
import com.android.settings.R;
import com.android.settings.wifi.WifiEntryShell;
import com.android.settingslib.wifi.AccessPoint;
import com.android.wifitrackerlib.WifiEntry;
import java.time.Duration;
import java.util.List;
@@ -148,6 +150,24 @@ public class WifiDppUtils {
return wifiConfiguration.preSharedKey;
}
private static String getPresharedKey(WifiManager wifiManager, WifiEntry wifiEntry) {
final List<WifiConfiguration> privilegedWifiConfigurations =
wifiManager.getPrivilegedConfiguredNetworks();
for (WifiConfiguration privilegedWifiConfiguration : privilegedWifiConfigurations) {
if (privilegedWifiConfiguration.networkId == WifiEntryShell.getNetworkId(wifiEntry)) {
// WEP uses a shared key hence the AuthAlgorithm.SHARED is used to identify it.
if (wifiEntry.getSecurity() == WifiEntry.SECURITY_WEP) {
return privilegedWifiConfiguration
.wepKeys[privilegedWifiConfiguration.wepTxKeyIndex];
} else {
return privilegedWifiConfiguration.preSharedKey;
}
}
}
return "";
}
private static String removeFirstAndLastDoubleQuotes(String str) {
if (TextUtils.isEmpty(str)) {
return str;
@@ -179,6 +199,22 @@ public class WifiDppUtils {
WifiQrCode.SECURITY_NO_PASSWORD : WifiQrCode.SECURITY_WEP;
}
static String getSecurityString(WifiEntry wifiEntry) {
final int security = wifiEntry.getSecurity();
switch (security) {
case WifiEntry.SECURITY_SAE:
return WifiQrCode.SECURITY_SAE;
case WifiEntry.SECURITY_PSK:
return WifiQrCode.SECURITY_WPA_PSK;
case WifiEntry.SECURITY_WEP:
return WifiQrCode.SECURITY_WEP;
case WifiEntry.SECURITY_OWE:
case WifiEntry.SECURITY_NONE:
default:
return WifiQrCode.SECURITY_NO_PASSWORD;
}
}
/**
* Returns an intent to launch QR code generator. It may return null if the security is not
* supported by QR code generator.
@@ -211,6 +247,37 @@ public class WifiDppUtils {
return intent;
}
/**
* Returns an intent to launch QR code generator. It may return null if the security is not
* supported by QR code generator.
*
* Do not use this method for Wi-Fi hotspot network, use
* {@code getHotspotConfiguratorIntentOrNull} instead.
*
* @param context The context to use for the content resolver
* @param wifiManager An instance of {@link WifiManager}
* @param wifiEntry An instance of {@link WifiEntry}
* @return Intent for launching QR code generator
*/
public static Intent getConfiguratorQrCodeGeneratorIntentOrNull(Context context,
WifiManager wifiManager, WifiEntry wifiEntry) {
final Intent intent = new Intent(context, WifiDppConfiguratorActivity.class);
if (wifiEntry.canShare()) {
intent.setAction(WifiDppConfiguratorActivity.ACTION_CONFIGURATOR_QR_CODE_GENERATOR);
} else {
return null;
}
setConfiguratorIntentExtra(intent, wifiManager, wifiEntry);
// For a transition mode Wi-Fi AP, creates a QR code that's compatible with more devices
if (wifiEntry.getSecurity() == WifiEntry.SECURITY_PSK_SAE_TRANSITION) {
intent.putExtra(EXTRA_WIFI_SECURITY, WifiQrCode.SECURITY_WPA_PSK);
}
return intent;
}
/**
* Returns an intent to launch QR code scanner. It may return null if the security is not
* supported by QR code scanner.
@@ -241,6 +308,36 @@ public class WifiDppUtils {
return intent;
}
/**
* Returns an intent to launch QR code scanner. It may return null if the security is not
* supported by QR code scanner.
*
* @param context The context to use for the content resolver
* @param wifiManager An instance of {@link WifiManager}
* @param wifiEntry An instance of {@link WifiEntry}
* @return Intent for launching QR code scanner
*/
public static Intent getConfiguratorQrCodeScannerIntentOrNull(Context context,
WifiManager wifiManager, WifiEntry wifiEntry) {
final Intent intent = new Intent(context, WifiDppConfiguratorActivity.class);
if (isSupportConfiguratorQrCodeScanner(context, wifiEntry)) {
intent.setAction(WifiDppConfiguratorActivity.ACTION_CONFIGURATOR_QR_CODE_SCANNER);
} else {
return null;
}
setConfiguratorIntentExtra(intent, wifiManager, wifiEntry);
final int networkId = WifiEntryShell.getNetworkId(wifiEntry);
if (networkId == WifiConfiguration.INVALID_NETWORK_ID) {
throw new IllegalArgumentException("Invalid network ID");
} else {
intent.putExtra(EXTRA_WIFI_NETWORK_ID, networkId);
}
return intent;
}
/**
* Returns an intent to launch QR code generator for the Wi-Fi hotspot. It may return null if
* the security is not supported by QR code generator.
@@ -320,6 +417,28 @@ public class WifiDppUtils {
intent.putExtra(EXTRA_WIFI_HIDDEN_SSID, wifiConfiguration.hiddenSSID);
}
private static void setConfiguratorIntentExtra(Intent intent, WifiManager wifiManager,
WifiEntry wifiEntry) {
final String ssid = removeFirstAndLastDoubleQuotes(wifiEntry.getTitle());
final String security = getSecurityString(wifiEntry);
// When the value of this key is read, the actual key is not returned, just a "*".
// Call privileged system API to obtain actual key.
final String preSharedKey = removeFirstAndLastDoubleQuotes(getPresharedKey(wifiManager,
wifiEntry));
if (!TextUtils.isEmpty(ssid)) {
intent.putExtra(EXTRA_WIFI_SSID, ssid);
}
if (!TextUtils.isEmpty(security)) {
intent.putExtra(EXTRA_WIFI_SECURITY, security);
}
if (!TextUtils.isEmpty(preSharedKey)) {
intent.putExtra(EXTRA_WIFI_PRE_SHARED_KEY, preSharedKey);
}
intent.putExtra(EXTRA_WIFI_HIDDEN_SSID, WifiEntryShell.hiddenSSID(wifiEntry));
}
/**
* Shows authentication screen to confirm credentials (pin, pattern or password) for the current
* user of the device.
@@ -378,6 +497,19 @@ public class WifiDppUtils {
return isSupportWifiDpp(context, accessPoint.getSecurity());
}
/**
* Checks if QR code scanner supports to config other devices with the Wi-Fi network
*
* @param context The context to use for {@link WifiManager#isEasyConnectSupported()}
* @param wifiEntry The {@link WifiEntry} of the Wi-Fi network
*/
public static boolean isSupportConfiguratorQrCodeScanner(Context context, WifiEntry wifiEntry) {
if (WifiEntryShell.isPasspoint(wifiEntry)) {
return false;
}
return isSupportWifiDpp(context, wifiEntry.getSecurity());
}
/**
* Checks if QR code generator supports to config other devices with the Wi-Fi network
*

View File

@@ -53,7 +53,7 @@ public class SavedAccessPointsWifiSettings2 extends DashboardFragment
private static final String TAG = "SavedAccessPoints2";
// Key of a Bundle to save/restore the selected WifiEntry
static final String KEY_KEY = "key_key";
public static final String KEY_KEY = "key_key";
// Max age of tracked WifiEntries
private static final long MAX_SCAN_AGE_MILLIS = 15_000;

View File

@@ -22,7 +22,6 @@ import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -77,11 +76,11 @@ import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.widget.ActionButtonsPreference;
import com.android.settingslib.widget.LayoutPreference;
import com.android.settingslib.wifi.AccessPoint;
import com.android.settingslib.wifi.WifiTracker;
import com.android.settingslib.wifi.WifiTrackerFactory;
import com.android.wifitrackerlib.NetworkDetailsTracker;
import com.android.wifitrackerlib.WifiEntry;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
@@ -99,10 +98,12 @@ import org.robolectric.shadows.ShadowToast;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
// TODO(b/143326832): Should add test cases for connect button.
// TODO(b/143326832): WifiEntry is not mature, should remove @Ignore after it's constructed.
@Ignore
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowDevicePolicyManager.class, ShadowEntityHeaderController.class})
public class WifiDetailPreferenceController2Test {
@@ -115,14 +116,15 @@ public class WifiDetailPreferenceController2Test {
private static final String MAC_ADDRESS = "01:23:45:67:89:ab";
private static final String RANDOMIZED_MAC_ADDRESS = "RANDOMIZED_MAC_ADDRESS";
private static final String FACTORY_MAC_ADDRESS = "FACTORY_MAC_ADDRESS";
private static final String SECURITY = "None";
// TODO(b/143326832): Add WifiEntry#getSecurityString
//private static final String SECURITY = "None";
private static final String FQDN = "fqdn";
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private PreferenceScreen mMockScreen;
@Mock
private AccessPoint mMockAccessPoint;
private WifiEntry mMockWifiEntry;
@Mock
private FragmentActivity mMockActivity;
@Mock
@@ -140,7 +142,7 @@ public class WifiDetailPreferenceController2Test {
@Mock
private WifiManager mMockWifiManager;
@Mock
private WifiTracker mMockWifiTracker;
private NetworkDetailsTracker mMockNetworkDetailsTracker;
@Mock
private MetricsFeatureProvider mMockMetricsFeatureProvider;
@Mock
@@ -258,10 +260,10 @@ public class WifiDetailPreferenceController2Test {
mLifecycle = new Lifecycle(mLifecycleOwner);
when(mContext.getPackageManager()).thenReturn(mMockPackageManager);
when(mMockAccessPoint.getConfig()).thenReturn(mMockWifiConfig);
when(mMockAccessPoint.getLevel()).thenReturn(LEVEL);
when(mMockAccessPoint.getSecurityString(false)).thenReturn(SECURITY);
when(mMockAccessPoint.getSsidStr()).thenReturn(SSID);
when(mMockWifiEntry.getLevel()).thenReturn(LEVEL);
// TODO(b/143326832): Add WifiEntry#getSecurityString
//when(mMockWifiEntry.getSecurityString(false)).thenReturn(SECURITY);
when(mMockWifiEntry.getTitle()).thenReturn(SSID);
when(mMockConnectivityManager.getNetworkInfo(any(Network.class)))
.thenReturn(mMockNetworkInfo);
doNothing().when(mMockConnectivityManager).registerNetworkCallback(
@@ -293,44 +295,30 @@ public class WifiDetailPreferenceController2Test {
}
private void setUpForConnectedNetwork() {
when(mMockAccessPoint.isActive()).thenReturn(true);
ArrayList list = new ArrayList<>();
list.add(mMockAccessPoint);
when(mMockWifiTracker.getAccessPoints()).thenReturn(list);
WifiTrackerFactory.setTestingWifiTracker(mMockWifiTracker);
when(mMockAccessPoint.matches(any(AccessPoint.class))).thenReturn(true);
when(mMockAccessPoint.isReachable()).thenReturn(true);
when(mMockNetworkDetailsTracker.getWifiEntry()).thenReturn(mMockWifiEntry);
when(mMockWifiEntry.getConnectedState()).thenReturn(WifiEntry.CONNECTED_STATE_CONNECTED);
mController = newWifiDetailPreferenceController2();
}
private void setUpForDisconnectedNetwork() {
when(mMockAccessPoint.isActive()).thenReturn(false);
ArrayList list = new ArrayList<>();
list.add(mMockAccessPoint);
when(mMockWifiTracker.getAccessPoints()).thenReturn(list);
WifiTrackerFactory.setTestingWifiTracker(mMockWifiTracker);
when(mMockAccessPoint.matches(any(AccessPoint.class))).thenReturn(true);
when(mMockAccessPoint.isReachable()).thenReturn(true);
when(mMockNetworkDetailsTracker.getWifiEntry()).thenReturn(mMockWifiEntry);
when(mMockWifiEntry.getConnectedState()).thenReturn(WifiEntry.CONNECTED_STATE_DISCONNECTED);
mController = newWifiDetailPreferenceController2();
}
private void setUpForNotInRangeNetwork() {
when(mMockAccessPoint.isActive()).thenReturn(false);
ArrayList list = new ArrayList<>();
list.add(mMockAccessPoint);
when(mMockWifiTracker.getAccessPoints()).thenReturn(list);
WifiTrackerFactory.setTestingWifiTracker(mMockWifiTracker);
when(mMockAccessPoint.matches(any(AccessPoint.class))).thenReturn(false);
when(mMockAccessPoint.isReachable()).thenReturn(false);
when(mMockWifiEntry.getConnectedState()).thenReturn(WifiEntry.CONNECTED_STATE_DISCONNECTED);
when(mMockNetworkDetailsTracker.getWifiEntry()).thenReturn(mMockWifiEntry);
when(mMockWifiEntry.getLevel()).thenReturn(WifiEntry.WIFI_LEVEL_UNREACHABLE);
mController = newWifiDetailPreferenceController2();
}
private WifiDetailPreferenceController2 newWifiDetailPreferenceController2() {
return new WifiDetailPreferenceController2(
mMockAccessPoint,
return spy(new WifiDetailPreferenceController2(
mMockWifiEntry,
mMockConnectivityManager,
mContext,
mMockFragment,
@@ -338,7 +326,7 @@ public class WifiDetailPreferenceController2Test {
mLifecycle,
mMockWifiManager,
mMockMetricsFeatureProvider,
mMockIconInjector);
mMockIconInjector));
}
private void setupMockedPreferenceScreen() {
@@ -392,6 +380,7 @@ public class WifiDetailPreferenceController2Test {
assertThat(mController.isAvailable()).isTrue();
}
/* TODO(b/143326832): Add WifiEntry#getSecurityString
@Test
public void securityPreference_stringShouldBeSet() {
setUpForConnectedNetwork();
@@ -399,6 +388,7 @@ public class WifiDetailPreferenceController2Test {
verify(mMockSecurityPref).setSummary(SECURITY);
}
*/
@Test
public void latestWifiInfo_shouldBeFetchedInDisplayPreferenceForConnectedNetwork() {
@@ -506,7 +496,7 @@ public class WifiDetailPreferenceController2Test {
public void entityHeader_shouldHaveLabelSetToTitle() {
setUpForConnectedNetwork();
String label = "title";
when(mMockAccessPoint.getTitle()).thenReturn(label);
when(mMockWifiEntry.getTitle()).thenReturn(label);
displayAndResume();
@@ -517,8 +507,7 @@ public class WifiDetailPreferenceController2Test {
public void entityHeader_shouldHaveSummarySet() {
setUpForConnectedNetwork();
String summary = "summary";
when(mMockAccessPoint.getSettingsSummary(true /*convertSavedAsDisconnected*/))
.thenReturn(summary);
when(mMockWifiEntry.getSummary()).thenReturn(summary);
displayAndResume();
@@ -531,7 +520,7 @@ public class WifiDetailPreferenceController2Test {
displayAndResume();
verify(mMockAccessPoint, times(1)).getSettingsSummary(true /*convertSavedAsDisconnected*/);
verify(mMockWifiEntry, times(1)).getSummary();
}
@Test
@@ -674,6 +663,7 @@ public class WifiDetailPreferenceController2Test {
verify(mMockRxLinkSpeedPref, never()).setSummary(any(String.class));
}
/* TODO(b/143326832): Support Passpoint test cases while WifiTracker2 supports it.
@Test
public void ssidPref_shouldHaveDetailTextSetForPasspointR1() {
setUpForConnectedNetwork();
@@ -708,6 +698,7 @@ public class WifiDetailPreferenceController2Test {
verify(mMockSsidPref).setVisible(false);
}
*/
@Test
public void macAddressPref_shouldVisibleForConnectedNetwork() {
@@ -958,8 +949,7 @@ public class WifiDetailPreferenceController2Test {
.thenReturn(new NetworkCapabilities(nc));
String summary = "Connected, no Internet";
when(mMockAccessPoint.getSettingsSummary(true /*convertSavedAsDisconnected*/))
.thenReturn(summary);
when(mMockWifiEntry.getSummary()).thenReturn(summary);
InOrder inOrder = inOrder(mMockHeaderController);
displayAndResume();
@@ -968,8 +958,7 @@ public class WifiDetailPreferenceController2Test {
// Check that an irrelevant capability update does not update the access point summary, as
// doing so could cause unnecessary jank...
summary = "Connected";
when(mMockAccessPoint.getSettingsSummary(true /*convertSavedAsDisconnected*/))
.thenReturn(summary);
when(mMockWifiEntry.getSummary()).thenReturn(summary);
updateNetworkCapabilities(nc);
inOrder.verify(mMockHeaderController, never()).setSummary(any(CharSequence.class));
@@ -979,8 +968,7 @@ public class WifiDetailPreferenceController2Test {
inOrder.verify(mMockHeaderController).setSummary(summary);
summary = "Connected, no Internet";
when(mMockAccessPoint.getSettingsSummary(true /*convertSavedAsDisconnected*/))
.thenReturn(summary);
when(mMockWifiEntry.getSummary()).thenReturn(summary);
// Another irrelevant update won't cause the UI to refresh...
updateNetworkCapabilities(nc);
@@ -993,16 +981,14 @@ public class WifiDetailPreferenceController2Test {
// UI will be refreshed when private DNS is broken.
summary = "Private DNS server cannot be accessed";
when(mMockAccessPoint.getSettingsSummary(true /* convertSavedAsDisconnected */))
.thenReturn(summary);
when(mMockWifiEntry.getSummary()).thenReturn(summary);
nc.setPrivateDnsBroken(true);
updateNetworkCapabilities(nc);
inOrder.verify(mMockHeaderController).setSummary(summary);
// UI will be refreshed when device connects to a partial connectivity network.
summary = "Limited connection";
when(mMockAccessPoint.getSettingsSummary(true /*convertSavedAsDisconnected*/))
.thenReturn(summary);
when(mMockWifiEntry.getSummary()).thenReturn(summary);
nc.addCapability(NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY);
updateNetworkCapabilities(nc);
inOrder.verify(mMockHeaderController).setSummary(summary);
@@ -1017,7 +1003,7 @@ public class WifiDetailPreferenceController2Test {
@Test
public void canForgetNetwork_shouldInvisibleIfWithoutConfiguration() {
setUpForConnectedNetwork();
when(mMockAccessPoint.getConfig()).thenReturn(null);
when(mMockWifiEntry.isSaved()).thenReturn(false);
mController = newWifiDetailPreferenceController2();
displayAndResume();
@@ -1029,7 +1015,7 @@ public class WifiDetailPreferenceController2Test {
public void canForgetNetwork_ephemeral() {
setUpForConnectedNetwork();
when(mMockWifiInfo.isEphemeral()).thenReturn(true);
when(mMockAccessPoint.getConfig()).thenReturn(null);
when(mMockWifiEntry.isSaved()).thenReturn(false);
displayAndResume();
@@ -1057,7 +1043,7 @@ public class WifiDetailPreferenceController2Test {
@Test
public void canShareNetwork_shouldInvisibleIfWithoutConfiguration() {
setUpForConnectedNetwork();
when(mMockAccessPoint.getConfig()).thenReturn(null);
when(mMockWifiEntry.isSaved()).thenReturn(false);
displayAndResume();
@@ -1129,6 +1115,7 @@ public class WifiDetailPreferenceController2Test {
.action(mMockActivity, MetricsProto.MetricsEvent.ACTION_WIFI_FORGET);
}
/* TODO(b/143326832): Support Passpoint test cases while WifiTracker2 supports it.
@Test
public void forgetNetwork_shouldShowDialog() {
setUpForConnectedNetwork();
@@ -1146,6 +1133,7 @@ public class WifiDetailPreferenceController2Test {
.action(mMockActivity, MetricsProto.MetricsEvent.ACTION_WIFI_FORGET);
verify(spyController).showConfirmForgetDialog();
}
*/
@Test
public void networkStateChangedIntent_shouldRefetchInfo() {
@@ -1344,7 +1332,7 @@ public class WifiDetailPreferenceController2Test {
when(mMockWifiManager.isWifiEnabled()).thenReturn(true);
InOrder inOrder = inOrder(mMockButtonsPref);
String label = "title";
when(mMockAccessPoint.getTitle()).thenReturn(label);
when(mMockWifiEntry.getTitle()).thenReturn(label);
setUpForToast();
displayAndResume();
@@ -1360,8 +1348,7 @@ public class WifiDetailPreferenceController2Test {
verifyConnectBtnSetUpAsConnecting(inOrder);
// update as connected
when(mMockAccessPoint.isActive()).thenReturn(true);
mController.updateAccessPoint();
when(mMockWifiEntry.getConnectedState()).thenReturn(WifiEntry.CONNECTED_STATE_CONNECTED);
// check connect button invisible, be init as default state and toast success message
verifyConnectBtnBeInitAsDefault(inOrder);
@@ -1419,364 +1406,21 @@ public class WifiDetailPreferenceController2Test {
}
@Test
public void testConnectButton_clickConnectButTimeout_displayFailMessage() {
setUpForDisconnectedNetwork();
when(mMockWifiManager.isWifiEnabled()).thenReturn(true);
InOrder inOrder = inOrder(mMockButtonsPref);
setUpForToast();
displayAndResume();
// check connect button exist
verifyConnectBtnSetUpAsVisible(inOrder);
// click connect button
mController.connectNetwork();
// check display button as connecting
verify(mMockWifiManager, times(1)).connect(anyInt(), any(WifiManager.ActionListener.class));
verifyConnectBtnSetUpAsConnecting(inOrder);
// update as failed
mController.sTimer.onFinish();
// check connect button visible, be init as default and toast failed message
verifyConnectBtnBeInitAsDefault(inOrder);
inOrder.verify(mMockButtonsPref, times(1)).setButton3Visible(true);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_failed_connect_message));
}
@Test
public void testConnectButton_clickConnectButTimeout_displayNotInRangeMessage() {
setUpForNotInRangeNetwork();
when(mMockWifiManager.isWifiEnabled()).thenReturn(true);
InOrder inOrder = inOrder(mMockButtonsPref);
setUpForToast();
displayAndResume();
// check connect button exist
verifyConnectBtnSetUpAsVisible(inOrder);
// click connect button
mController.connectNetwork();
// check display button as connecting
verify(mMockWifiManager, times(1)).connect(anyInt(), any(WifiManager.ActionListener.class));
verifyConnectBtnSetUpAsConnecting(inOrder);
// update as failed
mController.sTimer.onFinish();
// check connect button visible, be init as default and toast failed message
verifyConnectBtnBeInitAsDefault(inOrder);
inOrder.verify(mMockButtonsPref, times(1)).setButton3Visible(true);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_not_in_range_message));
}
@Test
public void testConnectButton_clickConnectWhenWiFiDisabled_displaySuccessMessage() {
setUpForDisconnectedNetwork();
when(mMockWifiManager.isWifiEnabled()).thenReturn(false); // wifi disabled
InOrder inOrder = inOrder(mMockButtonsPref);
String label = "title";
when(mMockAccessPoint.getTitle()).thenReturn(label);
setUpForToast();
displayAndResume();
// check connect button exist
verifyConnectBtnSetUpAsVisible(inOrder);
// click connect button
mController.connectNetwork();
// check turn on Wi-Fi, display button as connecting and toast turn on Wi-Fi message
verify(mMockWifiManager, times(1)).setWifiEnabled(true);
verifyConnectBtnSetUpAsConnecting(inOrder);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_turned_on_message));
// notify Wi-Fi enabled
mController.mWifiListener.onWifiStateChanged(WifiManager.WIFI_STATE_ENABLED);
// check had connect network and icon display as expected
verify(mMockWifiManager, times(1)).connect(anyInt(), any(WifiManager.ActionListener.class));
verifyConnectBtnSetUpAsConnecting(inOrder);
// update as connected
when(mMockAccessPoint.isActive()).thenReturn(true);
mController.updateAccessPoint();
// check connect button invisible, be init as default state and toast success message
verifyConnectBtnBeInitAsDefault(inOrder);
inOrder.verify(mMockButtonsPref, times(1)).setButton3Visible(false);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_connected_to_message, label));
}
@Test
public void testConnectButton_clickConnectWhenWiFiDisabled_failedToConnectWiFi() {
setUpForDisconnectedNetwork();
when(mMockWifiManager.isWifiEnabled()).thenReturn(false); // wifi disabled
InOrder inOrder = inOrder(mMockButtonsPref);
setUpForToast();
displayAndResume();
// check connect button exist
verifyConnectBtnSetUpAsVisible(inOrder);
// click connect button
mController.connectNetwork();
// check turn on Wi-Fi, display button as connecting and toast turn on Wi-Fi message
verify(mMockWifiManager, times(1)).setWifiEnabled(true);
verifyConnectBtnSetUpAsConnecting(inOrder);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_turned_on_message));
// notify Wi-Fi enabled
mController.mWifiListener.onWifiStateChanged(WifiManager.WIFI_STATE_ENABLED);
// check had connect network and icon display as expected
verify(mMockWifiManager, times(1)).connect(anyInt(), any(WifiManager.ActionListener.class));
verifyConnectBtnSetUpAsConnecting(inOrder);
// update as failed
mController.sTimer.onFinish();
// check connect button visible, be init as default and toast failed message
verifyConnectBtnBeInitAsDefault(inOrder);
inOrder.verify(mMockButtonsPref, times(1)).setButton3Visible(true);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_failed_connect_message));
}
@Test
public void
testConnectButton_clickConnectWhenWiFiDisabled_failedToConnectWifiBecauseNotInRange() {
setUpForNotInRangeNetwork();
when(mMockWifiManager.isWifiEnabled()).thenReturn(false); // wifi disabled
InOrder inOrder = inOrder(mMockButtonsPref);
setUpForToast();
displayAndResume();
// check connect button exist
verifyConnectBtnSetUpAsVisible(inOrder);
// click connect button
mController.connectNetwork();
// check turn on Wi-Fi, display button as connecting and toast turn on Wi-Fi message
verify(mMockWifiManager, times(1)).setWifiEnabled(true);
verifyConnectBtnSetUpAsConnecting(inOrder);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_turned_on_message));
// notify Wi-Fi enabled
mController.mWifiListener.onWifiStateChanged(WifiManager.WIFI_STATE_ENABLED);
// check had connect network and icon display as expected
verify(mMockWifiManager, times(1)).connect(anyInt(), any(WifiManager.ActionListener.class));
verifyConnectBtnSetUpAsConnecting(inOrder);
// update as failed
mController.sTimer.onFinish();
// check connect button visible, be init as default and toast failed message
verifyConnectBtnBeInitAsDefault(inOrder);
inOrder.verify(mMockButtonsPref, times(1)).setButton3Visible(true);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_not_in_range_message));
}
@Test
public void testConnectButton_clickConnectWhenWiFiDisabled_failedToEnableWifi() {
setUpForDisconnectedNetwork();
when(mMockWifiManager.isWifiEnabled()).thenReturn(false); // wifi disabled
InOrder inOrder = inOrder(mMockButtonsPref);
setUpForToast();
displayAndResume();
// check connect button exist
verifyConnectBtnSetUpAsVisible(inOrder);
// click connect button
mController.connectNetwork();
// check turn on Wi-Fi, display button as connecting and toast turn on Wi-Fi message
verify(mMockWifiManager, times(1)).setWifiEnabled(true);
verifyConnectBtnSetUpAsConnecting(inOrder);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_turned_on_message));
// notify turn on Wi-Fi failed
mController.sTimer.onFinish();
// check connect button visible, be init as default and toast failed message
verifyConnectBtnBeInitAsDefault(inOrder);
inOrder.verify(mMockButtonsPref, times(1)).setButton3Visible(true);
assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo(
mContext.getString(R.string.wifi_failed_connect_message));
}
@Test
public void testConnectButton_clickConnectAndBackKey_ignoreTimeoutEvent() {
setUpForDisconnectedNetwork();
when(mMockWifiManager.isWifiEnabled()).thenReturn(true);
InOrder inOrder = inOrder(mMockButtonsPref);
setUpForToast();
displayAndResume();
// check connect button exist
verifyConnectBtnSetUpAsVisible(inOrder);
// click connect button
mController.connectNetwork();
// check display button as connecting
verify(mMockWifiManager, times(1)).connect(anyInt(), any(WifiManager.ActionListener.class));
verifyConnectBtnSetUpAsConnecting(inOrder);
// leave detail page
when(mMockFragment.getActivity()).thenReturn(null);
// timeout happened
mController.sTimer.onFinish();
// check connect button visible, be init as default and toast failed message
inOrder.verify(mMockButtonsPref, never()).setButton3Text(R.string.wifi_connect);
inOrder.verify(mMockButtonsPref, never()).setButton3Icon(R.drawable.ic_settings_wireless);
inOrder.verify(mMockButtonsPref, never()).setButton3Enabled(true);
inOrder.verify(mMockButtonsPref, never()).setButton3Visible(true);
assertThat(ShadowToast.shownToastCount()).isEqualTo(0);
}
@Test
public void updateAccessPoint_returnFalseForNothingChanged() {
setUpForDisconnectedNetwork();
displayAndResume();
boolean changed = mController.updateAccessPoint();
assertThat(changed).isFalse();
}
@Test
public void updateAccessPoint_returnTrueForSignalLevelChanged() {
setUpForDisconnectedNetwork();
displayAndResume();
// Level changed
when(mMockAccessPoint.getLevel()).thenReturn(LEVEL + 1);
boolean changed = mController.updateAccessPoint();
assertThat(changed).isTrue();
}
@Test
public void updateAccessPoint_returnTrueForChangeAsNotInRange() {
setUpForDisconnectedNetwork();
displayAndResume();
// change as not in range
when(mMockAccessPoint.matches(any(AccessPoint.class))).thenReturn(false);
boolean changed = mController.updateAccessPoint();
assertThat(changed).isTrue();
}
@Test
public void updateAccessPoint_returnTrueForChangeAsInRange() {
setUpForNotInRangeNetwork();
displayAndResume();
// change as in range
when(mMockAccessPoint.matches(any(AccessPoint.class))).thenReturn(true);
boolean changed = mController.updateAccessPoint();
assertThat(changed).isTrue();
}
@Test
public void updateAccessPoint_returnTrueForChangeAsConnected() {
setUpForDisconnectedNetwork();
displayAndResume();
// change as connected
when(mMockAccessPoint.isActive()).thenReturn(true);
boolean changed = mController.updateAccessPoint();
assertThat(changed).isTrue();
}
@Test
public void updateAccessPoint_returnTrueForChangeAsDisconnected() {
setUpForConnectedNetwork();
displayAndResume();
// change as disconnected
when(mMockAccessPoint.isActive()).thenReturn(false);
boolean changed = mController.updateAccessPoint();
assertThat(changed).isTrue();
}
@Test
public void updateAccessPoint_returnTrueForAccessPointUpdated() {
setUpForConnectedNetwork();
displayAndResume();
// change as disconnected
when(mMockAccessPoint.update(mMockWifiConfig, mMockWifiInfo, mMockNetworkInfo))
.thenReturn(true);
boolean changed = mController.updateAccessPoint();
assertThat(changed).isTrue();
}
@Test
public void testRefreshRssiViews_shouldNotUpdateIfLevelIsSameForConnectedNetwork() {
public void testRefreshRssiViews_shouldOnUpdated() {
setUpForConnectedNetwork();
displayAndResume();
mContext.sendBroadcast(new Intent(WifiManager.RSSI_CHANGED_ACTION));
verify(mMockAccessPoint, times(3)).getLevel();
verify(mMockIconInjector, times(1)).getIcon(anyInt());
}
@Test
public void testRefreshRssiViews_shouldUpdateOnLevelChangeForConnectedNetwork() {
setUpForConnectedNetwork();
displayAndResume();
when(mMockAccessPoint.getLevel()).thenReturn(0);
mContext.sendBroadcast(new Intent(WifiManager.RSSI_CHANGED_ACTION));
verify(mMockAccessPoint, times(4)).getLevel();
verify(mMockIconInjector, times(2)).getIcon(anyInt());
verify(mController).onUpdated();
}
@Test
public void testRefreshRssiViews_shouldNotUpdateForNotInRangeNetwork() {
setUpForNotInRangeNetwork();
displayAndResume();
when(mMockAccessPoint.getLevel()).thenReturn(0);
when(mMockWifiEntry.getLevel()).thenReturn(0);
mContext.sendBroadcast(new Intent(WifiManager.RSSI_CHANGED_ACTION));
verify(mMockSignalStrengthPref, times(2)).setVisible(false);
@@ -1858,6 +1502,7 @@ public class WifiDetailPreferenceController2Test {
verify(mMockMacAddressPref).setTitle(R.string.wifi_advanced_device_mac_address_title);
}
/* TODO(b/143326832): Support Passpoint test cases while WifiTracker2 supports it.
@Test
public void entityHeader_expiredPasspointR1_shouldHandleExpiration() {
when(mMockAccessPoint.isPasspoint()).thenReturn(true);
@@ -1872,6 +1517,7 @@ public class WifiDetailPreferenceController2Test {
verify(mMockButtonsPref, atLeastOnce()).setButton3Visible(false);
verify(mMockHeaderController).setSummary(expireSummary);
}
*/
private ActionButtonsPreference createMock() {
final ActionButtonsPreference pref = mock(ActionButtonsPreference.class);

View File

@@ -21,11 +21,11 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import androidx.preference.DropDownPreference;
import com.android.settings.R;
import com.android.wifitrackerlib.WifiEntry;
import org.junit.Before;
import org.junit.Test;
@@ -42,7 +42,7 @@ public class WifiMeteredPreferenceController2Test {
private static final int METERED_OVERRIDE_NOT_METERED = 2;
@Mock
private WifiConfiguration mWifiConfiguration;
private WifiEntry mWifiEntry;
private WifiMeteredPreferenceController2 mPreferenceController;
private Context mContext;
@@ -53,7 +53,7 @@ public class WifiMeteredPreferenceController2Test {
mContext = RuntimeEnvironment.application;
mPreferenceController = spy(
new WifiMeteredPreferenceController2(mContext, mWifiConfiguration));
new WifiMeteredPreferenceController2(mContext, mWifiEntry));
mDropDownPreference = new DropDownPreference(mContext);
mDropDownPreference.setEntries(R.array.wifi_metered_entries);
mDropDownPreference.setEntryValues(R.array.wifi_metered_values);

View File

@@ -20,13 +20,14 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import androidx.preference.DropDownPreference;
import com.android.settings.R;
import com.android.wifitrackerlib.WifiEntry;
import org.junit.Before;
import org.junit.Test;
@@ -38,11 +39,11 @@ import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class WifiPrivacyPreferenceController2Test {
private static final int PRIVACY_RANDOMIZED = WifiConfiguration.RANDOMIZATION_PERSISTENT;
private static final int PRIVACY_TRUSTED = WifiConfiguration.RANDOMIZATION_NONE;
private static final int PRIVACY_RANDOMIZED = WifiEntry.PRIVACY_RANDOMIZED_MAC;
private static final int PRIVACY_TRUSTED = WifiEntry.PRIVACY_DEVICE_MAC;
@Mock
private WifiConfiguration mWifiConfiguration;
private WifiEntry mWifiEntry;
private WifiPrivacyPreferenceController2 mPreferenceController;
private Context mContext;
@@ -55,7 +56,7 @@ public class WifiPrivacyPreferenceController2Test {
WifiPrivacyPreferenceController2 preferenceController =
new WifiPrivacyPreferenceController2(mContext);
preferenceController.setWifiConfiguration(mWifiConfiguration);
preferenceController.setWifiEntry(mWifiEntry);
mPreferenceController = spy(preferenceController);
mDropDownPreference = new DropDownPreference(mContext);
mDropDownPreference.setEntries(R.array.wifi_privacy_entries);
@@ -89,38 +90,23 @@ public class WifiPrivacyPreferenceController2Test {
@Test
public void testController_resilientToNullConfig() {
mPreferenceController = spy(new WifiPrivacyPreferenceController2(mContext));
mPreferenceController.setWifiEntry(mWifiEntry);
mPreferenceController.getRandomizationValue();
mPreferenceController.onPreferenceChange(mDropDownPreference, "1");
}
@Test
public void testUpdateState_isNotEphemeralNetwork_shouldBeSelectable() {
mPreferenceController.setIsEphemeral(false);
public void testUpdateState_canSetPrivacy_shouldBeSelectable() {
when(mWifiEntry.canSetPrivacy()).thenReturn(true);
mPreferenceController.updateState(mDropDownPreference);
assertThat(mDropDownPreference.isSelectable()).isTrue();
}
@Test
public void testUpdateState_isEphemeralNetwork_shouldNotSelectable() {
mPreferenceController.setIsEphemeral(true);
mPreferenceController.updateState(mDropDownPreference);
assertThat(mDropDownPreference.isSelectable()).isFalse();
}
@Test
public void testUpdateState_isNotPasspointNetwork_shouldBeSelectable() {
mPreferenceController.setIsPasspoint(false);
mPreferenceController.updateState(mDropDownPreference);
assertThat(mDropDownPreference.isSelectable()).isTrue();
}
@Test
public void testUpdateState_isPasspointNetwork_shouldNotSelectable() {
mPreferenceController.setIsPasspoint(true);
public void testUpdateState_canNotSetPrivacy_shouldNotSelectable() {
when(mWifiEntry.canSetPrivacy()).thenReturn(false);
mPreferenceController.updateState(mDropDownPreference);
assertThat(mDropDownPreference.isSelectable()).isFalse();