Merge "[Wi-Fi] Apply WifiTrackerLib objects in NetworkRequestDialogFragment"

This commit is contained in:
Arc Wang
2020-06-21 14:25:18 +00:00
committed by Android (Google) Code Review
5 changed files with 267 additions and 387 deletions

View File

@@ -194,8 +194,7 @@ public class NetworkRequestDialogActivity extends FragmentActivity implements
if (mIsSpecifiedSsid) {
// Prevent from throwing same dialog, because onMatch() will be called many times.
if (mMatchedConfig == null) {
mMatchedConfig = WifiUtils.getWifiConfig(
null /* accesspoint */, scanResults.get(0), null /* password */);
mMatchedConfig = WifiUtils.getWifiConfig(null /* wifiEntry */, scanResults.get(0));
showSingleSsidRequestDialog(
WifiInfo.sanitizeSsid(mMatchedConfig.SSID), false /* isTryAgain */);
}

View File

@@ -16,15 +16,28 @@
package com.android.settings.wifi;
import static com.android.settings.wifi.WifiUtils.getWifiEntrySecurity;
import static java.util.stream.Collectors.toList;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkScoreManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.NetworkRequestMatchCallback;
import android.net.wifi.WifiManager.NetworkRequestUserSelectionCallback;
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.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
@@ -42,11 +55,11 @@ import androidx.preference.internal.PreferenceImageView;
import com.android.settings.R;
import com.android.settingslib.Utils;
import com.android.settingslib.core.lifecycle.Lifecycle;
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.WifiPickerTracker;
import java.time.Clock;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
@@ -56,7 +69,9 @@ import java.util.List;
* happens, {@link NetworkRequestErrorDialogFragment} will be called to display error message.
*/
public class NetworkRequestDialogFragment extends NetworkRequestDialogBaseFragment implements
DialogInterface.OnClickListener{
DialogInterface.OnClickListener, WifiPickerTracker.WifiPickerTrackerCallback {
private static final String TAG = "NetworkRequestDialogFragment";
/**
* Spec defines there should be 5 wifi ap on the list at most or just show all if {@code
@@ -65,17 +80,51 @@ public class NetworkRequestDialogFragment extends NetworkRequestDialogBaseFragme
private static final int MAX_NUMBER_LIST_ITEM = 5;
private boolean mShowLimitedItem = true;
private List<AccessPoint> mAccessPointList;
@VisibleForTesting
FilterWifiTracker mFilterWifiTracker;
private AccessPointAdapter mDialogAdapter;
@VisibleForTesting List<WifiEntry> mFilteredWifiEntries = new ArrayList<>();
@VisibleForTesting List<ScanResult> mMatchedScanResults = new ArrayList<>();
private WifiEntryAdapter mDialogAdapter;
private NetworkRequestUserSelectionCallback mUserSelectionCallback;
@VisibleForTesting WifiPickerTracker mWifiPickerTracker;
// Worker thread used for WifiPickerTracker work.
private HandlerThread mWorkerThread;
// Max age of tracked WifiEntries.
private static final long MAX_SCAN_AGE_MILLIS = 15_000;
// Interval between initiating WifiPickerTracker scans.
private static final long SCAN_INTERVAL_MILLIS = 10_000;
public static NetworkRequestDialogFragment newInstance() {
NetworkRequestDialogFragment dialogFragment = new NetworkRequestDialogFragment();
return dialogFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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();
}
};
final Context context = getContext();
mWifiPickerTracker = new WifiPickerTracker(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,
this);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getContext();
@@ -94,8 +143,8 @@ public class NetworkRequestDialogFragment extends NetworkRequestDialogBaseFragme
progressBar.setVisibility(View.VISIBLE);
// Prepares adapter.
mDialogAdapter = new AccessPointAdapter(context,
R.layout.preference_access_point, getAccessPointList());
mDialogAdapter = new WifiEntryAdapter(context,
R.layout.preference_access_point, mFilteredWifiEntries);
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setCustomTitle(customTitle)
@@ -107,9 +156,8 @@ public class NetworkRequestDialogFragment extends NetworkRequestDialogBaseFragme
// Clicking list item is to connect wifi ap.
final AlertDialog dialog = builder.create();
dialog.getListView()
.setOnItemClickListener(
(parent, view, position, id) -> this.onClick(dialog, position));
dialog.getListView().setOnItemClickListener(
(parent, view, position, id) -> this.onClick(dialog, position));
// Don't dismiss dialog when touching outside. User reports it is easy to touch outside.
// This causes dialog to close.
@@ -121,76 +169,49 @@ public class NetworkRequestDialogFragment extends NetworkRequestDialogBaseFragme
neutralBtn.setVisibility(View.GONE);
neutralBtn.setOnClickListener(v -> {
mShowLimitedItem = false;
renewAccessPointList(null /* scanResults */);
notifyAdapterRefresh();
updateWifiEntries();
updateUi();
neutralBtn.setVisibility(View.GONE);
});
});
return dialog;
}
@NonNull
List<AccessPoint> getAccessPointList() {
// Initials list for adapter, in case of display crashing.
if (mAccessPointList == null) {
mAccessPointList = new ArrayList<>();
}
return mAccessPointList;
}
private BaseAdapter getDialogAdapter() {
return mDialogAdapter;
}
@Override
public void onClick(DialogInterface dialog, int which) {
final List<AccessPoint> accessPointList = getAccessPointList();
if (accessPointList.size() == 0) {
if (mFilteredWifiEntries.size() == 0 || which >= mFilteredWifiEntries.size()) {
return; // Invalid values.
}
if (mUserSelectionCallback == null) {
return; // Callback is missing or not ready.
}
if (which < accessPointList.size()) {
final AccessPoint selectedAccessPoint = accessPointList.get(which);
WifiConfiguration wifiConfig = selectedAccessPoint.getConfig();
if (wifiConfig == null) {
wifiConfig = WifiUtils.getWifiConfig(selectedAccessPoint, /* scanResult */
null, /* password */ null);
}
if (wifiConfig != null) {
mUserSelectionCallback.select(wifiConfig);
}
final WifiEntry wifiEntry = mFilteredWifiEntries.get(which);
WifiConfiguration config = wifiEntry.getWifiConfiguration();
if (config == null) {
config = WifiUtils.getWifiConfig(wifiEntry, null /* scanResult */);
}
mUserSelectionCallback.select(config);
}
@Override
public void onCancel(@NonNull DialogInterface dialog) {
super.onCancel(dialog);
if (mUserSelectionCallback != null) {
mUserSelectionCallback.reject();
}
}
@Override
public void onPause() {
super.onPause();
if (mFilterWifiTracker != null) {
mFilterWifiTracker.onPause();
}
}
@Override
public void onDestroy() {
super.onDestroy();
mWorkerThread.quit();
if (mFilterWifiTracker != null) {
mFilterWifiTracker.onDestroy();
mFilterWifiTracker = null;
}
super.onDestroy();
}
private void showAllButton() {
@@ -217,22 +238,65 @@ public class NetworkRequestDialogFragment extends NetworkRequestDialogBaseFragme
}
}
/** Called when the state of Wifi has changed. */
@Override
public void onResume() {
super.onResume();
if (mFilterWifiTracker == null) {
mFilterWifiTracker = new FilterWifiTracker(getContext(), getSettingsLifecycle());
public void onWifiStateChanged() {
if (mMatchedScanResults.size() == 0) {
return;
}
mFilterWifiTracker.onResume();
updateWifiEntries();
updateUi();
}
private class AccessPointAdapter extends ArrayAdapter<AccessPoint> {
/**
* Update the results when data changes
*/
@Override
public void onWifiEntriesChanged() {
if (mMatchedScanResults.size() == 0) {
return;
}
updateWifiEntries();
updateUi();
}
@Override
public void onNumSavedSubscriptionsChanged() {
// Do nothing.
}
@Override
public void onNumSavedNetworksChanged() {
// Do nothing.
}
@VisibleForTesting
void updateWifiEntries() {
final List<WifiEntry> wifiEntries = new ArrayList<>();
if (mWifiPickerTracker.getConnectedWifiEntry() != null) {
wifiEntries.add(mWifiPickerTracker.getConnectedWifiEntry());
}
wifiEntries.addAll(mWifiPickerTracker.getWifiEntries());
mFilteredWifiEntries.clear();
mFilteredWifiEntries.addAll(wifiEntries.stream().filter(entry -> {
for (ScanResult matchedScanResult : mMatchedScanResults) {
if (TextUtils.equals(entry.getSsid(), matchedScanResult.SSID)
&& entry.getSecurity() == getWifiEntrySecurity(matchedScanResult)) {
return true;
}
}
return false;
}).limit(mShowLimitedItem ? MAX_NUMBER_LIST_ITEM : Long.MAX_VALUE)
.collect(toList()));
}
private class WifiEntryAdapter extends ArrayAdapter<WifiEntry> {
private final int mResourceId;
private final LayoutInflater mInflater;
public AccessPointAdapter(Context context, int resourceId, List<AccessPoint> objects) {
WifiEntryAdapter(Context context, int resourceId, List<WifiEntry> objects) {
super(context, resourceId, objects);
mResourceId = resourceId;
mInflater = LayoutInflater.from(context);
@@ -248,18 +312,18 @@ public class NetworkRequestDialogFragment extends NetworkRequestDialogBaseFragme
divider.setVisibility(View.GONE);
}
final AccessPoint accessPoint = getItem(position);
final WifiEntry wifiEntry = getItem(position);
final TextView titleView = view.findViewById(android.R.id.title);
if (titleView != null) {
// Shows whole SSID for better UX.
titleView.setSingleLine(false);
titleView.setText(accessPoint.getTitle());
titleView.setText(wifiEntry.getTitle());
}
final TextView summary = view.findViewById(android.R.id.summary);
if (summary != null) {
final String summaryString = accessPoint.getSettingsSummary();
final String summaryString = wifiEntry.getSummary();
if (TextUtils.isEmpty(summaryString)) {
summary.setVisibility(View.GONE);
} else {
@@ -269,7 +333,7 @@ public class NetworkRequestDialogFragment extends NetworkRequestDialogBaseFragme
}
final PreferenceImageView imageView = view.findViewById(android.R.id.icon);
final int level = accessPoint.getLevel();
final int level = wifiEntry.getLevel();
if (imageView != null) {
final Drawable drawable = getContext().getDrawable(
Utils.getWifiIconResource(level));
@@ -290,137 +354,23 @@ public class NetworkRequestDialogFragment extends NetworkRequestDialogBaseFragme
@Override
public void onMatch(List<ScanResult> scanResults) {
// Shouldn't need to renew cached list, since input result is empty.
if (scanResults != null && scanResults.size() > 0) {
renewAccessPointList(scanResults);
notifyAdapterRefresh();
}
}
// Updates internal AccessPoint list from WifiTracker. scanResults are used to update key list
// of AccessPoint, and could be null if there is no necessary to update key list.
private void renewAccessPointList(List<ScanResult> scanResults) {
if (mFilterWifiTracker == null) {
return;
}
// TODO(b/119846365): Checks if we could escalate the converting effort.
// Updates keys of scanResults into FilterWifiTracker for updating matched AccessPoints.
if (scanResults != null) {
mFilterWifiTracker.updateKeys(scanResults);
}
// Re-gets matched AccessPoints from WifiTracker.
final List<AccessPoint> list = getAccessPointList();
list.clear();
list.addAll(mFilterWifiTracker.getAccessPoints());
mMatchedScanResults = scanResults;
updateWifiEntries();
updateUi();
}
@VisibleForTesting
void notifyAdapterRefresh() {
void updateUi() {
// Update related UI buttons
if (mShowLimitedItem && mFilteredWifiEntries.size() >= MAX_NUMBER_LIST_ITEM) {
showAllButton();
}
if (mFilteredWifiEntries.size() > 0) {
hideProgressIcon();
}
if (getDialogAdapter() != null) {
getDialogAdapter().notifyDataSetChanged();
}
}
@VisibleForTesting
final class FilterWifiTracker {
private final List<String> mAccessPointKeys;
private final WifiTracker mWifiTracker;
private final Context mContext;
public FilterWifiTracker(Context context, Lifecycle lifecycle) {
mWifiTracker = WifiTrackerFactory.create(context, mWifiListener,
lifecycle, /* includeSaved */ true, /* includeScans */ true);
mAccessPointKeys = new ArrayList<>();
mContext = context;
}
/**
* Updates key list from input. {@code onMatch()} may be called in multi-times according
* wifi scanning result, so needs patchwork here.
*/
public void updateKeys(List<ScanResult> scanResults) {
for (ScanResult scanResult : scanResults) {
final String key = AccessPoint.getKey(mContext, scanResult);
if (!mAccessPointKeys.contains(key)) {
mAccessPointKeys.add(key);
}
}
}
/**
* Returns only AccessPoints whose key is in {@code mAccessPointKeys}.
*
* @return List of matched AccessPoints.
*/
public List<AccessPoint> getAccessPoints() {
final List<AccessPoint> allAccessPoints = mWifiTracker.getAccessPoints();
final List<AccessPoint> result = new ArrayList<>();
// The order should be kept, because order means wifi score (sorting in WifiTracker).
int count = 0;
for (AccessPoint accessPoint : allAccessPoints) {
final String key = accessPoint.getKey();
if (mAccessPointKeys.contains(key)) {
result.add(accessPoint);
count++;
// Limits how many count of items could show.
if (mShowLimitedItem && count >= MAX_NUMBER_LIST_ITEM) {
break;
}
}
}
// Update related UI buttons
if (mShowLimitedItem && (count >= MAX_NUMBER_LIST_ITEM)) {
showAllButton();
}
if (count > 0) {
hideProgressIcon();
}
return result;
}
@VisibleForTesting
WifiTracker.WifiListener mWifiListener = new WifiTracker.WifiListener() {
@Override
public void onWifiStateChanged(int state) {
notifyAdapterRefresh();
}
@Override
public void onConnectedChanged() {
notifyAdapterRefresh();
}
@Override
public void onAccessPointsChanged() {
renewAccessPointList(null /* scanResults */);
notifyAdapterRefresh();
}
};
public void onDestroy() {
if (mWifiTracker != null) {
mWifiTracker.onDestroy();
}
}
public void onResume() {
if (mWifiTracker != null) {
mWifiTracker.onStart();
}
}
public void onPause() {
if (mWifiTracker != null) {
mWifiTracker.onStop();
}
}
}
}

View File

@@ -31,6 +31,7 @@ import android.text.TextUtils;
import com.android.settings.Utils;
import com.android.settingslib.wifi.AccessPoint;
import com.android.wifitrackerlib.WifiEntry;
import java.nio.charset.StandardCharsets;
@@ -132,136 +133,102 @@ public class WifiUtils {
/**
* Provides a simple way to generate a new {@link WifiConfiguration} obj from
* {@link ScanResult} or {@link AccessPoint}. Either {@code accessPoint} or {@code scanResult
* {@link ScanResult} or {@link WifiEntry}. Either {@code wifiEntry} or {@code scanResult
* } input should be not null for retrieving information, otherwise will throw
* IllegalArgumentException.
* This method prefers to take {@link AccessPoint} input in priority. Therefore this method
* will take {@link AccessPoint} input as preferred data extraction source when you input
* both {@link AccessPoint} and {@link ScanResult}, and ignore {@link ScanResult} input.
* This method prefers to take {@link WifiEntry} input in priority. Therefore this method
* will take {@link WifiEntry} input as preferred data extraction source when you input
* both {@link WifiEntry} and {@link ScanResult}, and ignore {@link ScanResult} input.
*
* Duplicated and simplified method from {@link WifiConfigController#getConfig()}.
* TODO(b/120827021): Should be removed if the there is have a common one in shared place (e.g.
* SettingsLib).
*
* @param accessPoint Input data for retrieving WifiConfiguration.
* @param wifiEntry Input data for retrieving WifiConfiguration.
* @param scanResult Input data for retrieving WifiConfiguration.
* @return WifiConfiguration obj based on input.
*/
public static WifiConfiguration getWifiConfig(AccessPoint accessPoint, ScanResult scanResult,
String password) {
if (accessPoint == null && scanResult == null) {
public static WifiConfiguration getWifiConfig(WifiEntry wifiEntry, ScanResult scanResult) {
if (wifiEntry == null && scanResult == null) {
throw new IllegalArgumentException(
"At least one of AccessPoint and ScanResult input is required.");
"At least one of WifiEntry and ScanResult input is required.");
}
final WifiConfiguration config = new WifiConfiguration();
final int security;
if (accessPoint == null) {
if (wifiEntry == null) {
config.SSID = AccessPoint.convertToQuotedString(scanResult.SSID);
security = getAccessPointSecurity(scanResult);
security = getWifiEntrySecurity(scanResult);
} else {
if (!accessPoint.isSaved()) {
config.SSID = AccessPoint.convertToQuotedString(
accessPoint.getSsidStr());
if (wifiEntry.getWifiConfiguration() == null) {
config.SSID = AccessPoint.convertToQuotedString(wifiEntry.getSsid());
} else {
config.networkId = accessPoint.getConfig().networkId;
config.hiddenSSID = accessPoint.getConfig().hiddenSSID;
config.networkId = wifiEntry.getWifiConfiguration().networkId;
config.hiddenSSID = wifiEntry.getWifiConfiguration().hiddenSSID;
}
security = accessPoint.getSecurity();
security = wifiEntry.getSecurity();
}
switch (security) {
case AccessPoint.SECURITY_NONE:
case WifiEntry.SECURITY_NONE:
config.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OPEN);
break;
case AccessPoint.SECURITY_WEP:
case WifiEntry.SECURITY_WEP:
config.setSecurityParams(WifiConfiguration.SECURITY_TYPE_WEP);
if (!TextUtils.isEmpty(password)) {
int length = password.length();
// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
if ((length == 10 || length == 26 || length == 58)
&& password.matches("[0-9A-Fa-f]*")) {
config.wepKeys[0] = password;
} else {
config.wepKeys[0] = '"' + password + '"';
}
}
break;
case AccessPoint.SECURITY_PSK:
case WifiEntry.SECURITY_PSK:
config.setSecurityParams(WifiConfiguration.SECURITY_TYPE_PSK);
if (!TextUtils.isEmpty(password)) {
if (password.matches("[0-9A-Fa-f]{64}")) {
config.preSharedKey = password;
} else {
config.preSharedKey = '"' + password + '"';
}
}
break;
case AccessPoint.SECURITY_EAP:
case AccessPoint.SECURITY_EAP_SUITE_B:
if (security == AccessPoint.SECURITY_EAP_SUITE_B) {
// allowedSuiteBCiphers will be set according to certificate type
config.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP_SUITE_B);
} else {
config.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP);
}
if (!TextUtils.isEmpty(password)) {
config.enterpriseConfig.setPassword(password);
}
case WifiEntry.SECURITY_EAP_SUITE_B:
config.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP_SUITE_B);
break;
case AccessPoint.SECURITY_SAE:
case WifiEntry.SECURITY_EAP:
config.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP);
break;
case WifiEntry.SECURITY_SAE:
config.setSecurityParams(WifiConfiguration.SECURITY_TYPE_SAE);
if (!TextUtils.isEmpty(password)) {
config.preSharedKey = '"' + password + '"';
}
break;
case AccessPoint.SECURITY_OWE:
case WifiEntry.SECURITY_OWE:
config.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OWE);
break;
default:
break;
}
return config;
}
/**
* Gets security value from ScanResult.
*
* Duplicated method from {@link AccessPoint#getSecurity(ScanResult)}.
* TODO(b/120827021): Should be removed if the there is have a common one in shared place (e.g.
* SettingsLib).
*
* @param result ScanResult
* @return Related security value based on {@link AccessPoint}.
* @return Related security value based on {@link WifiEntry}.
*/
public static int getAccessPointSecurity(ScanResult result) {
public static int getWifiEntrySecurity(ScanResult result) {
if (result.capabilities.contains("WEP")) {
return AccessPoint.SECURITY_WEP;
return WifiEntry.SECURITY_WEP;
} else if (result.capabilities.contains("SAE")) {
return AccessPoint.SECURITY_SAE;
return WifiEntry.SECURITY_SAE;
} else if (result.capabilities.contains("PSK")) {
return AccessPoint.SECURITY_PSK;
return WifiEntry.SECURITY_PSK;
} else if (result.capabilities.contains("EAP_SUITE_B_192")) {
return AccessPoint.SECURITY_EAP_SUITE_B;
return WifiEntry.SECURITY_EAP_SUITE_B;
} else if (result.capabilities.contains("EAP")) {
return AccessPoint.SECURITY_EAP;
return WifiEntry.SECURITY_EAP;
} else if (result.capabilities.contains("OWE")) {
return AccessPoint.SECURITY_OWE;
return WifiEntry.SECURITY_OWE;
}
return AccessPoint.SECURITY_NONE;
return WifiEntry.SECURITY_NONE;
}
public static final int CONNECT_TYPE_OTHERS = 0;
public static final int CONNECT_TYPE_OPEN_NETWORK = 1;
public static final int CONNECT_TYPE_SAVED_NETWORK = 2;