results) {
- RttResult[] legacyResults = new RttResult[results.size()];
- int i = 0;
- for (RangingResult result : results) {
- legacyResults[i] = new RttResult();
- legacyResults[i].status = result.getStatus();
- legacyResults[i].bssid = result.getMacAddress().toString();
- if (result.getStatus() == RangingResult.STATUS_SUCCESS) {
- legacyResults[i].distance = result.getDistanceMm() / 10;
- legacyResults[i].distanceStandardDeviation =
- result.getDistanceStdDevMm() / 10;
- legacyResults[i].rssi = result.getRssi() * -2;
- legacyResults[i].ts = result.getRangingTimestampMillis() * 1000;
- legacyResults[i].measurementFrameNumber =
- result.getNumAttemptedMeasurements();
- legacyResults[i].successMeasurementFrameNumber =
- result.getNumSuccessfulMeasurements();
- } else {
- // just in case legacy API needed some relatively real timestamp
- legacyResults[i].ts = SystemClock.elapsedRealtime() * 1000;
- }
- i++;
- }
- listener.onSuccess(legacyResults);
- }
- });
- } catch (IllegalArgumentException e) {
- Log.e(TAG, "startRanging: invalid arguments - " + e);
- listener.onFailure(REASON_INVALID_REQUEST, e.getMessage());
- } catch (SecurityException e) {
- Log.e(TAG, "startRanging: security exception - " + e);
- listener.onFailure(REASON_PERMISSION_DENIED, e.getMessage());
- }
- }
-
- /**
- * This method is deprecated and performs no function. Please use the {@link WifiRttManager}
- * API.
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void stopRanging(RttListener listener) {
- Log.e(TAG, "stopRanging: unsupported operation - nop");
- }
-
- /**
- * Callbacks for responder operations.
- *
- * A {@link ResponderCallback} is the handle to the calling client. {@link RttManager} will keep
- * a reference to the callback for the entire period when responder is enabled. The same
- * callback as used in enabling responder needs to be passed for disabling responder.
- * The client can freely destroy or reuse the callback after {@link RttManager#disableResponder}
- * is called.
- */
- @Deprecated
- public abstract static class ResponderCallback {
- /** Callback when responder is enabled. */
- public abstract void onResponderEnabled(ResponderConfig config);
- /** Callback when enabling responder failed. */
- public abstract void onResponderEnableFailure(int reason);
- // TODO: consider adding onResponderAborted once it's supported.
- }
-
- /**
- * Enable Wi-Fi RTT responder mode on the device. The enabling result will be delivered via
- * {@code callback}.
- *
- * Note calling this method with the same callback when the responder is already enabled won't
- * change the responder state, a cached {@link ResponderConfig} from the last enabling will be
- * returned through the callback.
- *
- * This method is deprecated and will throw an {@link UnsupportedOperationException}
- * exception. Please use the {@link WifiRttManager} API to perform a Wi-Fi Aware peer-to-peer
- * ranging.
- *
- * @param callback Callback for responder enabling/disabling result.
- * @throws IllegalArgumentException If {@code callback} is null.
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void enableResponder(ResponderCallback callback) {
- throw new UnsupportedOperationException(
- "enableResponder is not supported in the adaptation layer");
- }
-
- /**
- * Disable Wi-Fi RTT responder mode on the device. The {@code callback} needs to be the
- * same one used in {@link #enableResponder(ResponderCallback)}.
- *
- * Calling this method when responder isn't enabled won't have any effect. The callback can be
- * reused for enabling responder after this method is called.
- *
- * This method is deprecated and will throw an {@link UnsupportedOperationException}
- * exception. Please use the {@link WifiRttManager} API to perform a Wi-Fi Aware peer-to-peer
- * ranging.
- *
- * @param callback The same callback used for enabling responder.
- * @throws IllegalArgumentException If {@code callback} is null.
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void disableResponder(ResponderCallback callback) {
- throw new UnsupportedOperationException(
- "disableResponder is not supported in the adaptation layer");
- }
-
- /**
- * Configuration used for RTT responder mode. The configuration information can be used by a
- * peer device to range the responder.
- *
- * @see ScanResult
- */
- @Deprecated
- public static class ResponderConfig implements Parcelable {
-
- // TODO: make all fields final once we can get mac address from responder HAL APIs.
- /**
- * Wi-Fi mac address used for responder mode.
- */
- public String macAddress = "";
-
- /**
- * The primary 20 MHz frequency (in MHz) of the channel where responder is enabled.
- * @see ScanResult#frequency
- */
- public int frequency;
-
- /**
- * Center frequency of the channel where responder is enabled on. Only in use when channel
- * width is at least 40MHz.
- * @see ScanResult#centerFreq0
- */
- public int centerFreq0;
-
- /**
- * Center frequency of the second segment when channel width is 80 + 80 MHz.
- * @see ScanResult#centerFreq1
- */
- public int centerFreq1;
-
- /**
- * Width of the channel where responder is enabled on.
- * @see ScanResult#channelWidth
- */
- public int channelWidth;
-
- /**
- * Preamble supported by responder.
- */
- public int preamble;
-
- @NonNull
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("macAddress = ").append(macAddress)
- .append(" frequency = ").append(frequency)
- .append(" centerFreq0 = ").append(centerFreq0)
- .append(" centerFreq1 = ").append(centerFreq1)
- .append(" channelWidth = ").append(channelWidth)
- .append(" preamble = ").append(preamble);
- return builder.toString();
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(macAddress);
- dest.writeInt(frequency);
- dest.writeInt(centerFreq0);
- dest.writeInt(centerFreq1);
- dest.writeInt(channelWidth);
- dest.writeInt(preamble);
- }
-
- /** Implement {@link Parcelable} interface */
- public static final @android.annotation.NonNull Parcelable.Creator CREATOR =
- new Parcelable.Creator() {
- @Override
- public ResponderConfig createFromParcel(Parcel in) {
- ResponderConfig config = new ResponderConfig();
- config.macAddress = in.readString();
- config.frequency = in.readInt();
- config.centerFreq0 = in.readInt();
- config.centerFreq1 = in.readInt();
- config.channelWidth = in.readInt();
- config.preamble = in.readInt();
- return config;
- }
-
- @Override
- public ResponderConfig[] newArray(int size) {
- return new ResponderConfig[size];
- }
- };
-
- }
-
- /* private methods */
- public static final int BASE = Protocol.BASE_WIFI_RTT_MANAGER;
-
- public static final int CMD_OP_START_RANGING = BASE + 0;
- public static final int CMD_OP_STOP_RANGING = BASE + 1;
- public static final int CMD_OP_FAILED = BASE + 2;
- public static final int CMD_OP_SUCCEEDED = BASE + 3;
- public static final int CMD_OP_ABORTED = BASE + 4;
- public static final int CMD_OP_ENABLE_RESPONDER = BASE + 5;
- public static final int CMD_OP_DISABLE_RESPONDER = BASE + 6;
- public static final int
- CMD_OP_ENALBE_RESPONDER_SUCCEEDED = BASE + 7;
- public static final int
- CMD_OP_ENALBE_RESPONDER_FAILED = BASE + 8;
- /** @hide */
- public static final int CMD_OP_REG_BINDER = BASE + 9;
-
- private final WifiRttManager mNewService;
- private final Context mContext;
- private RttCapabilities mRttCapabilities;
-
- /**
- * Create a new WifiScanner instance.
- * Applications will almost always want to use
- * {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve
- * the standard {@link android.content.Context#WIFI_RTT_SERVICE Context.WIFI_RTT_SERVICE}.
- * @param service the new WifiRttManager service
- *
- * @hide
- */
- public RttManager(@NonNull Context context, @NonNull WifiRttManager service) {
- mNewService = service;
- mContext = context;
-
- boolean rttSupported = context.getPackageManager().hasSystemFeature(
- PackageManager.FEATURE_WIFI_RTT);
-
- mRttCapabilities = new RttCapabilities();
- mRttCapabilities.oneSidedRttSupported = rttSupported;
- mRttCapabilities.twoSided11McRttSupported = rttSupported;
- mRttCapabilities.lciSupported = false;
- mRttCapabilities.lcrSupported = false;
- mRttCapabilities.preambleSupported = PREAMBLE_HT | PREAMBLE_VHT;
- mRttCapabilities.bwSupported = RTT_BW_40_SUPPORT | RTT_BW_80_SUPPORT;
- mRttCapabilities.responderSupported = false;
- mRttCapabilities.secureRttSupported = false;
- }
-}
-
diff --git a/wifi/java/android/net/wifi/ScanResult.java b/wifi/java/android/net/wifi/ScanResult.java
deleted file mode 100644
index 9f8ecf14175df..0000000000000
--- a/wifi/java/android/net/wifi/ScanResult.java
+++ /dev/null
@@ -1,1223 +0,0 @@
-/*
- * Copyright (C) 2008 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 android.net.wifi;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.net.wifi.WifiAnnotations.ChannelWidth;
-import android.net.wifi.WifiAnnotations.WifiStandard;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * Describes information about a detected access point. In addition
- * to the attributes described here, the supplicant keeps track of
- * {@code quality}, {@code noise}, and {@code maxbitrate} attributes,
- * but does not currently report them to external clients.
- */
-public final class ScanResult implements Parcelable {
- /**
- * The network name.
- */
- public String SSID;
-
- /**
- * Ascii encoded SSID. This will replace SSID when we deprecate it. @hide
- */
- @UnsupportedAppUsage
- public WifiSsid wifiSsid;
-
- /**
- * The address of the access point.
- */
- public String BSSID;
-
- /**
- * The HESSID from the beacon.
- * @hide
- */
- @UnsupportedAppUsage
- public long hessid;
-
- /**
- * The ANQP Domain ID from the Hotspot 2.0 Indication element, if present.
- * @hide
- */
- @UnsupportedAppUsage
- public int anqpDomainId;
-
- /*
- * This field is equivalent to the |flags|, rather than the |capabilities| field
- * of the per-BSS scan results returned by WPA supplicant. See the definition of
- * |struct wpa_bss| in wpa_supplicant/bss.h for more details.
- */
- /**
- * Describes the authentication, key management, and encryption schemes
- * supported by the access point.
- */
- public String capabilities;
-
- /**
- * The interface name on which the scan result was received.
- * @hide
- */
- public String ifaceName;
-
- /**
- * @hide
- * No security protocol.
- */
- @SystemApi
- public static final int PROTOCOL_NONE = 0;
- /**
- * @hide
- * Security protocol type: WPA version 1.
- */
- @SystemApi
- public static final int PROTOCOL_WPA = 1;
- /**
- * @hide
- * Security protocol type: RSN, for WPA version 2, and version 3.
- */
- @SystemApi
- public static final int PROTOCOL_RSN = 2;
- /**
- * @hide
- * Security protocol type:
- * OSU Server-only authenticated layer 2 Encryption Network.
- * Used for Hotspot 2.0.
- */
- @SystemApi
- public static final int PROTOCOL_OSEN = 3;
-
- /**
- * @hide
- * Security protocol type: WAPI.
- */
- @SystemApi
- public static final int PROTOCOL_WAPI = 4;
-
- /**
- * @hide
- * No security key management scheme.
- */
- @SystemApi
- public static final int KEY_MGMT_NONE = 0;
- /**
- * @hide
- * Security key management scheme: PSK.
- */
- @SystemApi
- public static final int KEY_MGMT_PSK = 1;
- /**
- * @hide
- * Security key management scheme: EAP.
- */
- @SystemApi
- public static final int KEY_MGMT_EAP = 2;
- /**
- * @hide
- * Security key management scheme: FT_PSK.
- */
- @SystemApi
- public static final int KEY_MGMT_FT_PSK = 3;
- /**
- * @hide
- * Security key management scheme: FT_EAP.
- */
- @SystemApi
- public static final int KEY_MGMT_FT_EAP = 4;
- /**
- * @hide
- * Security key management scheme: PSK_SHA256
- */
- @SystemApi
- public static final int KEY_MGMT_PSK_SHA256 = 5;
- /**
- * @hide
- * Security key management scheme: EAP_SHA256.
- */
- @SystemApi
- public static final int KEY_MGMT_EAP_SHA256 = 6;
- /**
- * @hide
- * Security key management scheme: OSEN.
- * Used for Hotspot 2.0.
- */
- @SystemApi
- public static final int KEY_MGMT_OSEN = 7;
- /**
- * @hide
- * Security key management scheme: SAE.
- */
- @SystemApi
- public static final int KEY_MGMT_SAE = 8;
- /**
- * @hide
- * Security key management scheme: OWE.
- */
- @SystemApi
- public static final int KEY_MGMT_OWE = 9;
- /**
- * @hide
- * Security key management scheme: SUITE_B_192.
- */
- @SystemApi
- public static final int KEY_MGMT_EAP_SUITE_B_192 = 10;
- /**
- * @hide
- * Security key management scheme: FT_SAE.
- */
- @SystemApi
- public static final int KEY_MGMT_FT_SAE = 11;
- /**
- * @hide
- * Security key management scheme: OWE in transition mode.
- */
- @SystemApi
- public static final int KEY_MGMT_OWE_TRANSITION = 12;
- /**
- * @hide
- * Security key management scheme: WAPI_PSK.
- */
- @SystemApi
- public static final int KEY_MGMT_WAPI_PSK = 13;
- /**
- * @hide
- * Security key management scheme: WAPI_CERT.
- */
- @SystemApi
- public static final int KEY_MGMT_WAPI_CERT = 14;
-
- /**
- * @hide
- * Security key management scheme: FILS_SHA256.
- */
- public static final int KEY_MGMT_FILS_SHA256 = 15;
- /**
- * @hide
- * Security key management scheme: FILS_SHA384.
- */
- public static final int KEY_MGMT_FILS_SHA384 = 16;
- /**
- * @hide
- * No cipher suite.
- */
- @SystemApi
- public static final int CIPHER_NONE = 0;
- /**
- * @hide
- * No group addressed, only used for group data cipher.
- */
- @SystemApi
- public static final int CIPHER_NO_GROUP_ADDRESSED = 1;
- /**
- * @hide
- * Cipher suite: TKIP
- */
- @SystemApi
- public static final int CIPHER_TKIP = 2;
- /**
- * @hide
- * Cipher suite: CCMP
- */
- @SystemApi
- public static final int CIPHER_CCMP = 3;
- /**
- * @hide
- * Cipher suite: GCMP
- */
- @SystemApi
- public static final int CIPHER_GCMP_256 = 4;
- /**
- * @hide
- * Cipher suite: SMS4
- */
- @SystemApi
- public static final int CIPHER_SMS4 = 5;
-
- /**
- * The detected signal level in dBm, also known as the RSSI.
- *
- * Use {@link android.net.wifi.WifiManager#calculateSignalLevel} to convert this number into
- * an absolute signal level which can be displayed to a user.
- */
- public int level;
- /**
- * The primary 20 MHz frequency (in MHz) of the channel over which the client is communicating
- * with the access point.
- */
- public int frequency;
-
- /**
- * AP Channel bandwidth is 20 MHZ
- */
- public static final int CHANNEL_WIDTH_20MHZ = 0;
- /**
- * AP Channel bandwidth is 40 MHZ
- */
- public static final int CHANNEL_WIDTH_40MHZ = 1;
- /**
- * AP Channel bandwidth is 80 MHZ
- */
- public static final int CHANNEL_WIDTH_80MHZ = 2;
- /**
- * AP Channel bandwidth is 160 MHZ
- */
- public static final int CHANNEL_WIDTH_160MHZ = 3;
- /**
- * AP Channel bandwidth is 160 MHZ, but 80MHZ + 80MHZ
- */
- public static final int CHANNEL_WIDTH_80MHZ_PLUS_MHZ = 4;
-
- /**
- * Wi-Fi unknown standard
- */
- public static final int WIFI_STANDARD_UNKNOWN = 0;
-
- /**
- * Wi-Fi 802.11a/b/g
- */
- public static final int WIFI_STANDARD_LEGACY = 1;
-
- /**
- * Wi-Fi 802.11n
- */
- public static final int WIFI_STANDARD_11N = 4;
-
- /**
- * Wi-Fi 802.11ac
- */
- public static final int WIFI_STANDARD_11AC = 5;
-
- /**
- * Wi-Fi 802.11ax
- */
- public static final int WIFI_STANDARD_11AX = 6;
-
- /**
- * Wi-Fi 802.11ad/ay
- */
- public static final int WIFI_STANDARD_11AD = 7;
-
- /**
- * AP wifi standard.
- */
- private @WifiStandard int mWifiStandard;
-
- /**
- * return the AP wifi standard.
- */
- public @WifiStandard int getWifiStandard() {
- return mWifiStandard;
- }
-
- /**
- * sets the AP wifi standard.
- * @hide
- */
- public void setWifiStandard(@WifiStandard int standard) {
- mWifiStandard = standard;
- }
-
- /**
- * Convert Wi-Fi standard to string
- */
- private static @Nullable String wifiStandardToString(@WifiStandard int standard) {
- switch(standard) {
- case WIFI_STANDARD_LEGACY:
- return "legacy";
- case WIFI_STANDARD_11N:
- return "11n";
- case WIFI_STANDARD_11AC:
- return "11ac";
- case WIFI_STANDARD_11AX:
- return "11ax";
- case WIFI_STANDARD_11AD:
- return "11ad";
- case WIFI_STANDARD_UNKNOWN:
- return "unknown";
- }
- return null;
- }
-
- /**
- * AP Channel bandwidth; one of {@link #CHANNEL_WIDTH_20MHZ}, {@link #CHANNEL_WIDTH_40MHZ},
- * {@link #CHANNEL_WIDTH_80MHZ}, {@link #CHANNEL_WIDTH_160MHZ}
- * or {@link #CHANNEL_WIDTH_80MHZ_PLUS_MHZ}.
- */
- public @ChannelWidth int channelWidth;
-
- /**
- * Not used if the AP bandwidth is 20 MHz
- * If the AP use 40, 80 or 160 MHz, this is the center frequency (in MHz)
- * if the AP use 80 + 80 MHz, this is the center frequency of the first segment (in MHz)
- */
- public int centerFreq0;
-
- /**
- * Only used if the AP bandwidth is 80 + 80 MHz
- * if the AP use 80 + 80 MHz, this is the center frequency of the second segment (in MHz)
- */
- public int centerFreq1;
-
- /**
- * @deprecated use is80211mcResponder() instead
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public boolean is80211McRTTResponder;
-
- /**
- * timestamp in microseconds (since boot) when
- * this result was last seen.
- */
- public long timestamp;
-
- /**
- * Timestamp representing date when this result was last seen, in milliseconds from 1970
- * {@hide}
- */
- @UnsupportedAppUsage
- public long seen;
-
- /**
- * On devices with multiple hardware radio chains, this class provides metadata about
- * each radio chain that was used to receive this scan result (probe response or beacon).
- * {@hide}
- */
- public static class RadioChainInfo {
- /** Vendor defined id for a radio chain. */
- public int id;
- /** Detected signal level in dBm (also known as the RSSI) on this radio chain. */
- public int level;
-
- @Override
- public String toString() {
- return "RadioChainInfo: id=" + id + ", level=" + level;
- }
-
- @Override
- public boolean equals(Object otherObj) {
- if (this == otherObj) {
- return true;
- }
- if (!(otherObj instanceof RadioChainInfo)) {
- return false;
- }
- RadioChainInfo other = (RadioChainInfo) otherObj;
- return id == other.id && level == other.level;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(id, level);
- }
- };
-
- /**
- * Information about the list of the radio chains used to receive this scan result
- * (probe response or beacon).
- *
- * For Example: On devices with 2 hardware radio chains, this list could hold 1 or 2
- * entries based on whether this scan result was received using one or both the chains.
- * {@hide}
- */
- public RadioChainInfo[] radioChainInfos;
-
- /**
- * Status indicating the scan result does not correspond to a user's saved configuration
- * @hide
- * @removed
- */
- @SystemApi
- public boolean untrusted;
-
- /**
- * Number of time autojoin used it
- * @hide
- */
- @UnsupportedAppUsage
- public int numUsage;
-
- /**
- * The approximate distance to the AP in centimeter, if available. Else
- * {@link UNSPECIFIED}.
- * {@hide}
- */
- @UnsupportedAppUsage
- public int distanceCm;
-
- /**
- * The standard deviation of the distance to the access point, if available.
- * Else {@link UNSPECIFIED}.
- * {@hide}
- */
- @UnsupportedAppUsage
- public int distanceSdCm;
-
- /** {@hide} */
- public static final long FLAG_PASSPOINT_NETWORK = 0x0000000000000001;
-
- /** {@hide} */
- public static final long FLAG_80211mc_RESPONDER = 0x0000000000000002;
-
- /*
- * These flags are specific to the ScanResult class, and are not related to the |flags|
- * field of the per-BSS scan results from WPA supplicant.
- */
- /**
- * Defines flags; such as {@link #FLAG_PASSPOINT_NETWORK}.
- * {@hide}
- */
- @UnsupportedAppUsage
- public long flags;
-
- /**
- * sets a flag in {@link #flags} field
- * @param flag flag to set
- * @hide
- */
- public void setFlag(long flag) {
- flags |= flag;
- }
-
- /**
- * clears a flag in {@link #flags} field
- * @param flag flag to set
- * @hide
- */
- public void clearFlag(long flag) {
- flags &= ~flag;
- }
-
- public boolean is80211mcResponder() {
- return (flags & FLAG_80211mc_RESPONDER) != 0;
- }
-
- public boolean isPasspointNetwork() {
- return (flags & FLAG_PASSPOINT_NETWORK) != 0;
- }
-
- /**
- * Indicates venue name (such as 'San Francisco Airport') published by access point; only
- * available on Passpoint network and if published by access point.
- */
- public CharSequence venueName;
-
- /**
- * Indicates Passpoint operator name published by access point.
- */
- public CharSequence operatorFriendlyName;
-
- /**
- * {@hide}
- */
- public final static int UNSPECIFIED = -1;
-
- /**
- * 2.4 GHz band first channel number
- * @hide
- */
- public static final int BAND_24_GHZ_FIRST_CH_NUM = 1;
- /**
- * 2.4 GHz band last channel number
- * @hide
- */
- public static final int BAND_24_GHZ_LAST_CH_NUM = 14;
- /**
- * 2.4 GHz band frequency of first channel in MHz
- * @hide
- */
- public static final int BAND_24_GHZ_START_FREQ_MHZ = 2412;
- /**
- * 2.4 GHz band frequency of last channel in MHz
- * @hide
- */
- public static final int BAND_24_GHZ_END_FREQ_MHZ = 2484;
-
- /**
- * 5 GHz band first channel number
- * @hide
- */
- public static final int BAND_5_GHZ_FIRST_CH_NUM = 32;
- /**
- * 5 GHz band last channel number
- * @hide
- */
- public static final int BAND_5_GHZ_LAST_CH_NUM = 173;
- /**
- * 5 GHz band frequency of first channel in MHz
- * @hide
- */
- public static final int BAND_5_GHZ_START_FREQ_MHZ = 5160;
- /**
- * 5 GHz band frequency of last channel in MHz
- * @hide
- */
- public static final int BAND_5_GHZ_END_FREQ_MHZ = 5865;
-
- /**
- * 6 GHz band first channel number
- * @hide
- */
- public static final int BAND_6_GHZ_FIRST_CH_NUM = 1;
- /**
- * 6 GHz band last channel number
- * @hide
- */
- public static final int BAND_6_GHZ_LAST_CH_NUM = 233;
- /**
- * 6 GHz band frequency of first channel in MHz
- * @hide
- */
- public static final int BAND_6_GHZ_START_FREQ_MHZ = 5955;
- /**
- * 6 GHz band frequency of last channel in MHz
- * @hide
- */
- public static final int BAND_6_GHZ_END_FREQ_MHZ = 7115;
-
- /**
- * 6 GHz band operating class 136 channel 2 center frequency in MHz
- * @hide
- */
- public static final int BAND_6_GHZ_OP_CLASS_136_CH_2_FREQ_MHZ = 5935;
-
- /**
- * 60 GHz band first channel number
- * @hide
- */
- public static final int BAND_60_GHZ_FIRST_CH_NUM = 1;
- /**
- * 60 GHz band last channel number
- * @hide
- */
- public static final int BAND_60_GHZ_LAST_CH_NUM = 6;
- /**
- * 60 GHz band frequency of first channel in MHz
- * @hide
- */
- public static final int BAND_60_GHZ_START_FREQ_MHZ = 58320;
- /**
- * 60 GHz band frequency of last channel in MHz
- * @hide
- */
- public static final int BAND_60_GHZ_END_FREQ_MHZ = 70200;
-
- /**
- * Utility function to check if a frequency within 2.4 GHz band
- * @param freqMhz frequency in MHz
- * @return true if within 2.4GHz, false otherwise
- *
- * @hide
- */
- public static boolean is24GHz(int freqMhz) {
- return freqMhz >= BAND_24_GHZ_START_FREQ_MHZ && freqMhz <= BAND_24_GHZ_END_FREQ_MHZ;
- }
-
- /**
- * Utility function to check if a frequency within 5 GHz band
- * @param freqMhz frequency in MHz
- * @return true if within 5GHz, false otherwise
- *
- * @hide
- */
- public static boolean is5GHz(int freqMhz) {
- return freqMhz >= BAND_5_GHZ_START_FREQ_MHZ && freqMhz <= BAND_5_GHZ_END_FREQ_MHZ;
- }
-
- /**
- * Utility function to check if a frequency within 6 GHz band
- * @param freqMhz
- * @return true if within 6GHz, false otherwise
- *
- * @hide
- */
- public static boolean is6GHz(int freqMhz) {
- if (freqMhz == BAND_6_GHZ_OP_CLASS_136_CH_2_FREQ_MHZ) {
- return true;
- }
- return (freqMhz >= BAND_6_GHZ_START_FREQ_MHZ && freqMhz <= BAND_6_GHZ_END_FREQ_MHZ);
- }
-
- /**
- * Utility function to check if a frequency within 60 GHz band
- * @param freqMhz
- * @return true if within 60GHz, false otherwise
- *
- * @hide
- */
- public static boolean is60GHz(int freqMhz) {
- return freqMhz >= BAND_60_GHZ_START_FREQ_MHZ && freqMhz <= BAND_60_GHZ_END_FREQ_MHZ;
- }
-
- /**
- * Utility function to convert channel number/band to frequency in MHz
- * @param channel number to convert
- * @param band of channel to convert
- * @return center frequency in Mhz of the channel, {@link UNSPECIFIED} if no match
- *
- * @hide
- */
- public static int convertChannelToFrequencyMhz(int channel, @WifiScanner.WifiBand int band) {
- if (band == WifiScanner.WIFI_BAND_24_GHZ) {
- // Special case
- if (channel == 14) {
- return 2484;
- } else if (channel >= BAND_24_GHZ_FIRST_CH_NUM && channel <= BAND_24_GHZ_LAST_CH_NUM) {
- return ((channel - BAND_24_GHZ_FIRST_CH_NUM) * 5) + BAND_24_GHZ_START_FREQ_MHZ;
- } else {
- return UNSPECIFIED;
- }
- }
- if (band == WifiScanner.WIFI_BAND_5_GHZ) {
- if (channel >= BAND_5_GHZ_FIRST_CH_NUM && channel <= BAND_5_GHZ_LAST_CH_NUM) {
- return ((channel - BAND_5_GHZ_FIRST_CH_NUM) * 5) + BAND_5_GHZ_START_FREQ_MHZ;
- } else {
- return UNSPECIFIED;
- }
- }
- if (band == WifiScanner.WIFI_BAND_6_GHZ) {
- if (channel >= BAND_6_GHZ_FIRST_CH_NUM && channel <= BAND_6_GHZ_LAST_CH_NUM) {
- if (channel == 2) {
- return BAND_6_GHZ_OP_CLASS_136_CH_2_FREQ_MHZ;
- }
- return ((channel - BAND_6_GHZ_FIRST_CH_NUM) * 5) + BAND_6_GHZ_START_FREQ_MHZ;
- } else {
- return UNSPECIFIED;
- }
- }
- if (band == WifiScanner.WIFI_BAND_60_GHZ) {
- if (channel >= BAND_60_GHZ_FIRST_CH_NUM && channel <= BAND_60_GHZ_LAST_CH_NUM) {
- return ((channel - BAND_60_GHZ_FIRST_CH_NUM) * 2160) + BAND_60_GHZ_START_FREQ_MHZ;
- } else {
- return UNSPECIFIED;
- }
- }
- return UNSPECIFIED;
- }
-
- /**
- * Utility function to convert frequency in MHz to channel number
- * @param freqMhz frequency in MHz
- * @return channel number associated with given frequency, {@link UNSPECIFIED} if no match
- *
- * @hide
- */
- public static int convertFrequencyMhzToChannel(int freqMhz) {
- // Special case
- if (freqMhz == 2484) {
- return 14;
- } else if (is24GHz(freqMhz)) {
- return (freqMhz - BAND_24_GHZ_START_FREQ_MHZ) / 5 + BAND_24_GHZ_FIRST_CH_NUM;
- } else if (is5GHz(freqMhz)) {
- return ((freqMhz - BAND_5_GHZ_START_FREQ_MHZ) / 5) + BAND_5_GHZ_FIRST_CH_NUM;
- } else if (is6GHz(freqMhz)) {
- if (freqMhz == BAND_6_GHZ_OP_CLASS_136_CH_2_FREQ_MHZ) {
- return 2;
- }
- return ((freqMhz - BAND_6_GHZ_START_FREQ_MHZ) / 5) + BAND_6_GHZ_FIRST_CH_NUM;
- }
-
- return UNSPECIFIED;
- }
-
- /**
- * @hide
- */
- public boolean is24GHz() {
- return ScanResult.is24GHz(frequency);
- }
-
- /**
- * @hide
- */
- public boolean is5GHz() {
- return ScanResult.is5GHz(frequency);
- }
-
- /**
- * @hide
- */
- public boolean is6GHz() {
- return ScanResult.is6GHz(frequency);
- }
-
- /**
- * @hide
- */
- public boolean is60GHz() {
- return ScanResult.is60GHz(frequency);
- }
-
- /**
- * @hide
- * anqp lines from supplicant BSS response
- */
- @UnsupportedAppUsage
- public List anqpLines;
-
- /**
- * information elements from beacon.
- */
- public static class InformationElement {
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_SSID = 0;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_SUPPORTED_RATES = 1;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_TIM = 5;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_BSS_LOAD = 11;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_ERP = 42;
- /** @hide */
- public static final int EID_HT_CAPABILITIES = 45;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_RSN = 48;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_EXTENDED_SUPPORTED_RATES = 50;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_HT_OPERATION = 61;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_INTERWORKING = 107;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_ROAMING_CONSORTIUM = 111;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_EXTENDED_CAPS = 127;
- /** @hide */
- public static final int EID_VHT_CAPABILITIES = 191;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_VHT_OPERATION = 192;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_VSA = 221;
- /** @hide */
- public static final int EID_EXTENSION_PRESENT = 255;
-
- // Extension IDs
- /** @hide */
- public static final int EID_EXT_HE_CAPABILITIES = 35;
- /** @hide */
- public static final int EID_EXT_HE_OPERATION = 36;
-
- /** @hide */
- @UnsupportedAppUsage
- public int id;
- /** @hide */
- public int idExt;
-
- /** @hide */
- @UnsupportedAppUsage
- public byte[] bytes;
-
- /** @hide */
- public InformationElement() {
- }
-
- public InformationElement(@NonNull InformationElement rhs) {
- this.id = rhs.id;
- this.idExt = rhs.idExt;
- this.bytes = rhs.bytes.clone();
- }
-
- /**
- * The element ID of the information element. Defined in the IEEE 802.11-2016 spec
- * Table 9-77.
- */
- public int getId() {
- return id;
- }
-
- /**
- * The element ID Extension of the information element. Defined in the IEEE 802.11-2016 spec
- * Table 9-77.
- */
- public int getIdExt() {
- return idExt;
- }
-
- /**
- * Get the specific content of the information element.
- */
- @NonNull
- public ByteBuffer getBytes() {
- return ByteBuffer.wrap(bytes).asReadOnlyBuffer();
- }
- }
-
- /**
- * information elements found in the beacon.
- * @hide
- */
- @UnsupportedAppUsage
- public InformationElement[] informationElements;
- /**
- * Get all information elements found in the beacon.
- */
- @NonNull
- public List getInformationElements() {
- return Collections.unmodifiableList(Arrays.asList(informationElements));
- }
-
- /** ANQP response elements.
- * @hide
- */
- public AnqpInformationElement[] anqpElements;
-
- /** {@hide} */
- public ScanResult(WifiSsid wifiSsid, String BSSID, long hessid, int anqpDomainId,
- byte[] osuProviders, String caps, int level, int frequency, long tsf) {
- this.wifiSsid = wifiSsid;
- this.SSID = (wifiSsid != null) ? wifiSsid.toString() : WifiManager.UNKNOWN_SSID;
- this.BSSID = BSSID;
- this.hessid = hessid;
- this.anqpDomainId = anqpDomainId;
- if (osuProviders != null) {
- this.anqpElements = new AnqpInformationElement[1];
- this.anqpElements[0] =
- new AnqpInformationElement(AnqpInformationElement.HOTSPOT20_VENDOR_ID,
- AnqpInformationElement.HS_OSU_PROVIDERS, osuProviders);
- }
- this.capabilities = caps;
- this.level = level;
- this.frequency = frequency;
- this.timestamp = tsf;
- this.distanceCm = UNSPECIFIED;
- this.distanceSdCm = UNSPECIFIED;
- this.channelWidth = UNSPECIFIED;
- this.centerFreq0 = UNSPECIFIED;
- this.centerFreq1 = UNSPECIFIED;
- this.flags = 0;
- this.radioChainInfos = null;
- this.mWifiStandard = WIFI_STANDARD_UNKNOWN;
- }
-
- /** {@hide} */
- public ScanResult(WifiSsid wifiSsid, String BSSID, String caps, int level, int frequency,
- long tsf, int distCm, int distSdCm) {
- this.wifiSsid = wifiSsid;
- this.SSID = (wifiSsid != null) ? wifiSsid.toString() : WifiManager.UNKNOWN_SSID;
- this.BSSID = BSSID;
- this.capabilities = caps;
- this.level = level;
- this.frequency = frequency;
- this.timestamp = tsf;
- this.distanceCm = distCm;
- this.distanceSdCm = distSdCm;
- this.channelWidth = UNSPECIFIED;
- this.centerFreq0 = UNSPECIFIED;
- this.centerFreq1 = UNSPECIFIED;
- this.flags = 0;
- this.radioChainInfos = null;
- this.mWifiStandard = WIFI_STANDARD_UNKNOWN;
- }
-
- /** {@hide} */
- public ScanResult(String Ssid, String BSSID, long hessid, int anqpDomainId, String caps,
- int level, int frequency,
- long tsf, int distCm, int distSdCm, int channelWidth, int centerFreq0, int centerFreq1,
- boolean is80211McRTTResponder) {
- this.SSID = Ssid;
- this.BSSID = BSSID;
- this.hessid = hessid;
- this.anqpDomainId = anqpDomainId;
- this.capabilities = caps;
- this.level = level;
- this.frequency = frequency;
- this.timestamp = tsf;
- this.distanceCm = distCm;
- this.distanceSdCm = distSdCm;
- this.channelWidth = channelWidth;
- this.centerFreq0 = centerFreq0;
- this.centerFreq1 = centerFreq1;
- if (is80211McRTTResponder) {
- this.flags = FLAG_80211mc_RESPONDER;
- } else {
- this.flags = 0;
- }
- this.radioChainInfos = null;
- this.mWifiStandard = WIFI_STANDARD_UNKNOWN;
- }
-
- /** {@hide} */
- public ScanResult(WifiSsid wifiSsid, String Ssid, String BSSID, long hessid, int anqpDomainId,
- String caps, int level,
- int frequency, long tsf, int distCm, int distSdCm, int channelWidth,
- int centerFreq0, int centerFreq1, boolean is80211McRTTResponder) {
- this(Ssid, BSSID, hessid, anqpDomainId, caps, level, frequency, tsf, distCm,
- distSdCm, channelWidth, centerFreq0, centerFreq1, is80211McRTTResponder);
- this.wifiSsid = wifiSsid;
- }
-
- /** copy constructor */
- public ScanResult(@NonNull ScanResult source) {
- if (source != null) {
- wifiSsid = source.wifiSsid;
- SSID = source.SSID;
- BSSID = source.BSSID;
- hessid = source.hessid;
- anqpDomainId = source.anqpDomainId;
- informationElements = source.informationElements;
- anqpElements = source.anqpElements;
- capabilities = source.capabilities;
- level = source.level;
- frequency = source.frequency;
- channelWidth = source.channelWidth;
- centerFreq0 = source.centerFreq0;
- centerFreq1 = source.centerFreq1;
- timestamp = source.timestamp;
- distanceCm = source.distanceCm;
- distanceSdCm = source.distanceSdCm;
- seen = source.seen;
- untrusted = source.untrusted;
- numUsage = source.numUsage;
- venueName = source.venueName;
- operatorFriendlyName = source.operatorFriendlyName;
- flags = source.flags;
- radioChainInfos = source.radioChainInfos;
- this.mWifiStandard = source.mWifiStandard;
- this.ifaceName = source.ifaceName;
- }
- }
-
- /** Construct an empty scan result. */
- public ScanResult() {
- }
-
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- String none = "";
-
- sb.append("SSID: ")
- .append(wifiSsid == null ? WifiManager.UNKNOWN_SSID : wifiSsid)
- .append(", BSSID: ")
- .append(BSSID == null ? none : BSSID)
- .append(", capabilities: ")
- .append(capabilities == null ? none : capabilities)
- .append(", level: ")
- .append(level)
- .append(", frequency: ")
- .append(frequency)
- .append(", timestamp: ")
- .append(timestamp);
- sb.append(", distance: ").append((distanceCm != UNSPECIFIED ? distanceCm : "?")).
- append("(cm)");
- sb.append(", distanceSd: ").append((distanceSdCm != UNSPECIFIED ? distanceSdCm : "?")).
- append("(cm)");
-
- sb.append(", passpoint: ");
- sb.append(((flags & FLAG_PASSPOINT_NETWORK) != 0) ? "yes" : "no");
- sb.append(", ChannelBandwidth: ").append(channelWidth);
- sb.append(", centerFreq0: ").append(centerFreq0);
- sb.append(", centerFreq1: ").append(centerFreq1);
- sb.append(", standard: ").append(wifiStandardToString(mWifiStandard));
- sb.append(", 80211mcResponder: ");
- sb.append(((flags & FLAG_80211mc_RESPONDER) != 0) ? "is supported" : "is not supported");
- sb.append(", Radio Chain Infos: ").append(Arrays.toString(radioChainInfos));
- sb.append(", interface name: ").append(ifaceName);
- return sb.toString();
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- if (wifiSsid != null) {
- dest.writeInt(1);
- wifiSsid.writeToParcel(dest, flags);
- } else {
- dest.writeInt(0);
- }
- dest.writeString(SSID);
- dest.writeString(BSSID);
- dest.writeLong(hessid);
- dest.writeInt(anqpDomainId);
- dest.writeString(capabilities);
- dest.writeInt(level);
- dest.writeInt(frequency);
- dest.writeLong(timestamp);
- dest.writeInt(distanceCm);
- dest.writeInt(distanceSdCm);
- dest.writeInt(channelWidth);
- dest.writeInt(centerFreq0);
- dest.writeInt(centerFreq1);
- dest.writeInt(mWifiStandard);
- dest.writeLong(seen);
- dest.writeInt(untrusted ? 1 : 0);
- dest.writeInt(numUsage);
- dest.writeString((venueName != null) ? venueName.toString() : "");
- dest.writeString((operatorFriendlyName != null) ? operatorFriendlyName.toString() : "");
- dest.writeLong(this.flags);
-
- if (informationElements != null) {
- dest.writeInt(informationElements.length);
- for (int i = 0; i < informationElements.length; i++) {
- dest.writeInt(informationElements[i].id);
- dest.writeInt(informationElements[i].idExt);
- dest.writeInt(informationElements[i].bytes.length);
- dest.writeByteArray(informationElements[i].bytes);
- }
- } else {
- dest.writeInt(0);
- }
-
- if (anqpLines != null) {
- dest.writeInt(anqpLines.size());
- for (int i = 0; i < anqpLines.size(); i++) {
- dest.writeString(anqpLines.get(i));
- }
- }
- else {
- dest.writeInt(0);
- }
- if (anqpElements != null) {
- dest.writeInt(anqpElements.length);
- for (AnqpInformationElement element : anqpElements) {
- dest.writeInt(element.getVendorId());
- dest.writeInt(element.getElementId());
- dest.writeInt(element.getPayload().length);
- dest.writeByteArray(element.getPayload());
- }
- } else {
- dest.writeInt(0);
- }
-
- if (radioChainInfos != null) {
- dest.writeInt(radioChainInfos.length);
- for (int i = 0; i < radioChainInfos.length; i++) {
- dest.writeInt(radioChainInfos[i].id);
- dest.writeInt(radioChainInfos[i].level);
- }
- } else {
- dest.writeInt(0);
- }
- dest.writeString((ifaceName != null) ? ifaceName.toString() : "");
- }
-
- /** Implement the Parcelable interface */
- public static final @NonNull Creator CREATOR =
- new Creator() {
- public ScanResult createFromParcel(Parcel in) {
- WifiSsid wifiSsid = null;
- if (in.readInt() == 1) {
- wifiSsid = WifiSsid.CREATOR.createFromParcel(in);
- }
- ScanResult sr = new ScanResult(
- wifiSsid,
- in.readString(), /* SSID */
- in.readString(), /* BSSID */
- in.readLong(), /* HESSID */
- in.readInt(), /* ANQP Domain ID */
- in.readString(), /* capabilities */
- in.readInt(), /* level */
- in.readInt(), /* frequency */
- in.readLong(), /* timestamp */
- in.readInt(), /* distanceCm */
- in.readInt(), /* distanceSdCm */
- in.readInt(), /* channelWidth */
- in.readInt(), /* centerFreq0 */
- in.readInt(), /* centerFreq1 */
- false /* rtt responder,
- fixed with flags below */
- );
-
- sr.mWifiStandard = in.readInt();
- sr.seen = in.readLong();
- sr.untrusted = in.readInt() != 0;
- sr.numUsage = in.readInt();
- sr.venueName = in.readString();
- sr.operatorFriendlyName = in.readString();
- sr.flags = in.readLong();
- int n = in.readInt();
- if (n != 0) {
- sr.informationElements = new InformationElement[n];
- for (int i = 0; i < n; i++) {
- sr.informationElements[i] = new InformationElement();
- sr.informationElements[i].id = in.readInt();
- sr.informationElements[i].idExt = in.readInt();
- int len = in.readInt();
- sr.informationElements[i].bytes = new byte[len];
- in.readByteArray(sr.informationElements[i].bytes);
- }
- }
-
- n = in.readInt();
- if (n != 0) {
- sr.anqpLines = new ArrayList();
- for (int i = 0; i < n; i++) {
- sr.anqpLines.add(in.readString());
- }
- }
- n = in.readInt();
- if (n != 0) {
- sr.anqpElements = new AnqpInformationElement[n];
- for (int i = 0; i < n; i++) {
- int vendorId = in.readInt();
- int elementId = in.readInt();
- int len = in.readInt();
- byte[] payload = new byte[len];
- in.readByteArray(payload);
- sr.anqpElements[i] =
- new AnqpInformationElement(vendorId, elementId, payload);
- }
- }
- n = in.readInt();
- if (n != 0) {
- sr.radioChainInfos = new RadioChainInfo[n];
- for (int i = 0; i < n; i++) {
- sr.radioChainInfos[i] = new RadioChainInfo();
- sr.radioChainInfos[i].id = in.readInt();
- sr.radioChainInfos[i].level = in.readInt();
- }
- }
- sr.ifaceName = in.readString();
- return sr;
- }
-
- public ScanResult[] newArray(int size) {
- return new ScanResult[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/SecurityParams.java b/wifi/java/android/net/wifi/SecurityParams.java
deleted file mode 100644
index 8ee2ea046cfba..0000000000000
--- a/wifi/java/android/net/wifi/SecurityParams.java
+++ /dev/null
@@ -1,888 +0,0 @@
-/*
- * Copyright (C) 2020 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 android.net.wifi;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.net.wifi.WifiConfiguration.AuthAlgorithm;
-import android.net.wifi.WifiConfiguration.GroupCipher;
-import android.net.wifi.WifiConfiguration.GroupMgmtCipher;
-import android.net.wifi.WifiConfiguration.KeyMgmt;
-import android.net.wifi.WifiConfiguration.PairwiseCipher;
-import android.net.wifi.WifiConfiguration.Protocol;
-import android.net.wifi.WifiConfiguration.SecurityType;
-import android.net.wifi.WifiConfiguration.SuiteBCipher;
-import android.os.Parcel;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.BitSet;
-import java.util.Objects;
-
-/**
- * A class representing a security configuration.
- * @hide
- */
-public class SecurityParams {
- private static final String TAG = "SecurityParams";
-
- /** Passpoint Release 1 */
- public static final int PASSPOINT_R1 = 1;
-
- /** Passpoint Release 2 */
- public static final int PASSPOINT_R2 = 2;
-
- /** Passpoint Release 3 */
- public static final int PASSPOINT_R3 = 3;
-
- @IntDef(prefix = { "PASSPOINT_" }, value = {
- PASSPOINT_R1,
- PASSPOINT_R2,
- PASSPOINT_R3,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface PasspointRelease {}
-
- private @SecurityType int mSecurityType = WifiConfiguration.SECURITY_TYPE_PSK;
-
- /**
- * This indicates that this security type is enabled or disabled.
- * Ex. While receiving Transition Disable Indication, older
- * security should be disabled.
- */
- private boolean mEnabled = true;
-
- /**
- * The set of key management protocols supported by this configuration.
- * See {@link KeyMgmt} for descriptions of the values.
- * This is set automatically based on the security type.
- */
- private BitSet mAllowedKeyManagement = new BitSet();
-
- /**
- * The set of security protocols supported by this configuration.
- * See {@link Protocol} for descriptions of the values.
- * This is set automatically based on the security type.
- */
- private BitSet mAllowedProtocols = new BitSet();
-
- /**
- * The set of authentication protocols supported by this configuration.
- * See {@link AuthAlgorithm} for descriptions of the values.
- * This is set automatically based on the security type.
- */
- private BitSet mAllowedAuthAlgorithms = new BitSet();
-
- /**
- * The set of pairwise ciphers for WPA supported by this configuration.
- * See {@link PairwiseCipher} for descriptions of the values.
- * This is set automatically based on the security type.
- */
- private BitSet mAllowedPairwiseCiphers = new BitSet();
-
- /**
- * The set of group ciphers supported by this configuration.
- * See {@link GroupCipher} for descriptions of the values.
- * This is set automatically based on the security type.
- */
- private BitSet mAllowedGroupCiphers = new BitSet();
-
- /**
- * The set of group management ciphers supported by this configuration.
- * See {@link GroupMgmtCipher} for descriptions of the values.
- */
- private BitSet mAllowedGroupManagementCiphers = new BitSet();
-
- /**
- * The set of SuiteB ciphers supported by this configuration.
- * To be used for WPA3-Enterprise mode. Set automatically by the framework based on the
- * certificate type that is used in this configuration.
- */
- private BitSet mAllowedSuiteBCiphers = new BitSet();
-
- /**
- * True if the network requires Protected Management Frames (PMF), false otherwise.
- */
- private boolean mRequirePmf = false;
-
- private @PasspointRelease int mPasspointRelease = PASSPOINT_R2;
-
- /** Indicate that this SAE security type only accepts H2E (Hash-to-Element) mode. */
- private boolean mIsSaeH2eOnlyMode = false;
-
- /** Indicate that this SAE security type only accepts PK (Public Key) mode. */
- private boolean mIsSaePkOnlyMode = false;
-
- /** Indicate whether this is added by auto-upgrade or not. */
- private boolean mIsAddedByAutoUpgrade = false;
-
- /** Constructor */
- private SecurityParams() {
- }
-
- /** Copy constructor */
- public SecurityParams(@NonNull SecurityParams source) {
- this.mSecurityType = source.mSecurityType;
- this.mEnabled = source.mEnabled;
- this.mAllowedKeyManagement = (BitSet) source.mAllowedKeyManagement.clone();
- this.mAllowedProtocols = (BitSet) source.mAllowedProtocols.clone();
- this.mAllowedAuthAlgorithms = (BitSet) source.mAllowedAuthAlgorithms.clone();
- this.mAllowedPairwiseCiphers = (BitSet) source.mAllowedPairwiseCiphers.clone();
- this.mAllowedGroupCiphers = (BitSet) source.mAllowedGroupCiphers.clone();
- this.mAllowedGroupManagementCiphers =
- (BitSet) source.mAllowedGroupManagementCiphers.clone();
- this.mAllowedSuiteBCiphers =
- (BitSet) source.mAllowedSuiteBCiphers.clone();
- this.mRequirePmf = source.mRequirePmf;
- this.mIsSaeH2eOnlyMode = source.mIsSaeH2eOnlyMode;
- this.mIsSaePkOnlyMode = source.mIsSaePkOnlyMode;
- this.mIsAddedByAutoUpgrade = source.mIsAddedByAutoUpgrade;
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof SecurityParams)) {
- return false;
- }
- SecurityParams that = (SecurityParams) thatObject;
-
- if (this.mSecurityType != that.mSecurityType) return false;
- if (this.mEnabled != that.mEnabled) return false;
- if (!this.mAllowedKeyManagement.equals(that.mAllowedKeyManagement)) return false;
- if (!this.mAllowedProtocols.equals(that.mAllowedProtocols)) return false;
- if (!this.mAllowedAuthAlgorithms.equals(that.mAllowedAuthAlgorithms)) return false;
- if (!this.mAllowedPairwiseCiphers.equals(that.mAllowedPairwiseCiphers)) return false;
- if (!this.mAllowedGroupCiphers.equals(that.mAllowedGroupCiphers)) return false;
- if (!this.mAllowedGroupManagementCiphers.equals(that.mAllowedGroupManagementCiphers)) {
- return false;
- }
- if (!this.mAllowedSuiteBCiphers.equals(that.mAllowedSuiteBCiphers)) return false;
- if (this.mRequirePmf != that.mRequirePmf) return false;
- if (this.mIsSaeH2eOnlyMode != that.mIsSaeH2eOnlyMode) return false;
- if (this.mIsSaePkOnlyMode != that.mIsSaePkOnlyMode) return false;
- if (this.mIsAddedByAutoUpgrade != that.mIsAddedByAutoUpgrade) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mSecurityType, mEnabled,
- mAllowedKeyManagement, mAllowedProtocols, mAllowedAuthAlgorithms,
- mAllowedPairwiseCiphers, mAllowedGroupCiphers, mAllowedGroupManagementCiphers,
- mAllowedSuiteBCiphers, mRequirePmf,
- mIsSaeH2eOnlyMode, mIsSaePkOnlyMode, mIsAddedByAutoUpgrade);
- }
-
- /**
- * Get the security type of this params.
- *
- * @return The security type defined in {@link WifiConfiguration}.
- */
- public @SecurityType int getSecurityType() {
- return mSecurityType;
- }
-
- /**
- * Check the security type of this params.
- *
- * @param type the testing security type.
- * @return true if this is for the corresponiding type.
- */
- public boolean isSecurityType(@SecurityType int type) {
- return type == mSecurityType;
- }
-
- /**
- * Check whether the security of given params is the same as this one.
- *
- * @param params the testing security params.
- * @return true if their security types are the same.
- */
- public boolean isSameSecurityType(SecurityParams params) {
- return params.mSecurityType == mSecurityType;
- }
-
- /**
- * Update security params to legacy WifiConfiguration object.
- *
- * @param config the target configuration.
- */
- public void updateLegacyWifiConfiguration(WifiConfiguration config) {
- config.allowedKeyManagement = (BitSet) mAllowedKeyManagement.clone();
- config.allowedProtocols = (BitSet) mAllowedProtocols.clone();
- config.allowedAuthAlgorithms = (BitSet) mAllowedAuthAlgorithms.clone();
- config.allowedPairwiseCiphers = (BitSet) mAllowedPairwiseCiphers.clone();
- config.allowedGroupCiphers = (BitSet) mAllowedGroupCiphers.clone();
- config.allowedGroupManagementCiphers = (BitSet) mAllowedGroupManagementCiphers.clone();
- config.allowedSuiteBCiphers = (BitSet) mAllowedSuiteBCiphers.clone();
- config.requirePmf = mRequirePmf;
- }
-
- /**
- * Set this params enabled.
- *
- * @param enable enable a specific security type.
- */
- public void setEnabled(boolean enable) {
- mEnabled = enable;
- }
-
- /**
- * Indicate this params is enabled or not.
- */
- public boolean isEnabled() {
- return mEnabled;
- }
-
- /**
- * Set the supporting Fast Initial Link Set-up (FILS) key management.
- *
- * FILS can be applied to all security types.
- * @param enableFilsSha256 Enable FILS SHA256.
- * @param enableFilsSha384 Enable FILS SHA256.
- */
- public void enableFils(boolean enableFilsSha256, boolean enableFilsSha384) {
- if (enableFilsSha256) {
- mAllowedKeyManagement.set(KeyMgmt.FILS_SHA256);
- }
-
- if (enableFilsSha384) {
- mAllowedKeyManagement.set(KeyMgmt.FILS_SHA384);
- }
- }
-
- /**
- * Get the copy of allowed key management.
- */
- public BitSet getAllowedKeyManagement() {
- return (BitSet) mAllowedKeyManagement.clone();
- }
-
- /**
- * Get the copy of allowed protocols.
- */
- public BitSet getAllowedProtocols() {
- return (BitSet) mAllowedProtocols.clone();
- }
-
- /**
- * Get the copy of allowed auth algorithms.
- */
- public BitSet getAllowedAuthAlgorithms() {
- return (BitSet) mAllowedAuthAlgorithms.clone();
- }
-
- /**
- * Get the copy of allowed pairwise ciphers.
- */
- public BitSet getAllowedPairwiseCiphers() {
- return (BitSet) mAllowedPairwiseCiphers.clone();
- }
-
- /**
- * Get the copy of allowed group ciphers.
- */
- public BitSet getAllowedGroupCiphers() {
- return (BitSet) mAllowedGroupCiphers.clone();
- }
-
- /**
- * Get the copy of allowed group management ciphers.
- */
- public BitSet getAllowedGroupManagementCiphers() {
- return (BitSet) mAllowedGroupManagementCiphers.clone();
- }
-
- /**
- * Enable Suite-B ciphers.
- *
- * @param enableEcdheEcdsa enable Diffie-Hellman with Elliptic Curve ECDSA cipher support.
- * @param enableEcdheRsa enable Diffie-Hellman with RSA cipher support.
- */
- public void enableSuiteBCiphers(boolean enableEcdheEcdsa, boolean enableEcdheRsa) {
- if (enableEcdheEcdsa) {
- mAllowedSuiteBCiphers.set(SuiteBCipher.ECDHE_ECDSA);
- } else {
- mAllowedSuiteBCiphers.clear(SuiteBCipher.ECDHE_ECDSA);
- }
-
- if (enableEcdheRsa) {
- mAllowedSuiteBCiphers.set(SuiteBCipher.ECDHE_RSA);
- } else {
- mAllowedSuiteBCiphers.clear(SuiteBCipher.ECDHE_RSA);
- }
- }
-
- /**
- * Get the copy of allowed suite-b ciphers.
- */
- public BitSet getAllowedSuiteBCiphers() {
- return (BitSet) mAllowedSuiteBCiphers.clone();
- }
-
- /**
- * Indicate PMF is required or not.
- */
- public boolean isRequirePmf() {
- return mRequirePmf;
- }
-
- /**
- * Indicate that this is open security type.
- */
- public boolean isOpenSecurityType() {
- return isSecurityType(WifiConfiguration.SECURITY_TYPE_OPEN)
- || isSecurityType(WifiConfiguration.SECURITY_TYPE_OWE);
- }
-
- /**
- * Indicate that this is enterprise security type.
- */
- public boolean isEnterpriseSecurityType() {
- return mAllowedKeyManagement.get(KeyMgmt.WPA_EAP)
- || mAllowedKeyManagement.get(KeyMgmt.IEEE8021X)
- || mAllowedKeyManagement.get(KeyMgmt.SUITE_B_192)
- || mAllowedKeyManagement.get(KeyMgmt.WAPI_CERT);
- }
-
- /**
- * Enable Hash-to-Element only mode.
- *
- * @param enable set H2E only mode enabled or not.
- */
- public void enableSaeH2eOnlyMode(boolean enable) {
- mIsSaeH2eOnlyMode = enable;
- }
-
- /**
- * Indicate whether this params is H2E only mode.
- *
- * @return true if this is H2E only mode params.
- */
- public boolean isSaeH2eOnlyMode() {
- return mIsSaeH2eOnlyMode;
- }
- /**
- * Enable Pubilc-Key only mode.
- *
- * @param enable set PK only mode enabled or not.
- */
- public void enableSaePkOnlyMode(boolean enable) {
- mIsSaePkOnlyMode = enable;
- }
-
- /**
- * Indicate whether this params is PK only mode.
- *
- * @return true if this is PK only mode params.
- */
- public boolean isSaePkOnlyMode() {
- return mIsSaePkOnlyMode;
- }
-
- /**
- * Set whether this is added by auto-upgrade.
- *
- * @param addedByAutoUpgrade true if added by auto-upgrade.
- */
- public void setIsAddedByAutoUpgrade(boolean addedByAutoUpgrade) {
- mIsAddedByAutoUpgrade = addedByAutoUpgrade;
- }
-
- /**
- * Indicate whether this is added by auto-upgrade or not.
- *
- * @return true if added by auto-upgrade; otherwise, false.
- */
- public boolean isAddedByAutoUpgrade() {
- return mIsAddedByAutoUpgrade;
- }
-
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- sbuf.append("Security Parameters:\n");
- sbuf.append(" Type: ").append(mSecurityType).append("\n");
- sbuf.append(" Enabled: ").append(mEnabled).append("\n");
- sbuf.append(" KeyMgmt:");
- for (int k = 0; k < mAllowedKeyManagement.size(); k++) {
- if (mAllowedKeyManagement.get(k)) {
- sbuf.append(" ");
- if (k < KeyMgmt.strings.length) {
- sbuf.append(KeyMgmt.strings[k]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" Protocols:");
- for (int p = 0; p < mAllowedProtocols.size(); p++) {
- if (mAllowedProtocols.get(p)) {
- sbuf.append(" ");
- if (p < Protocol.strings.length) {
- sbuf.append(Protocol.strings[p]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" AuthAlgorithms:");
- for (int a = 0; a < mAllowedAuthAlgorithms.size(); a++) {
- if (mAllowedAuthAlgorithms.get(a)) {
- sbuf.append(" ");
- if (a < AuthAlgorithm.strings.length) {
- sbuf.append(AuthAlgorithm.strings[a]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" PairwiseCiphers:");
- for (int pc = 0; pc < mAllowedPairwiseCiphers.size(); pc++) {
- if (mAllowedPairwiseCiphers.get(pc)) {
- sbuf.append(" ");
- if (pc < PairwiseCipher.strings.length) {
- sbuf.append(PairwiseCipher.strings[pc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" GroupCiphers:");
- for (int gc = 0; gc < mAllowedGroupCiphers.size(); gc++) {
- if (mAllowedGroupCiphers.get(gc)) {
- sbuf.append(" ");
- if (gc < GroupCipher.strings.length) {
- sbuf.append(GroupCipher.strings[gc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" GroupMgmtCiphers:");
- for (int gmc = 0; gmc < mAllowedGroupManagementCiphers.size(); gmc++) {
- if (mAllowedGroupManagementCiphers.get(gmc)) {
- sbuf.append(" ");
- if (gmc < GroupMgmtCipher.strings.length) {
- sbuf.append(GroupMgmtCipher.strings[gmc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" SuiteBCiphers:");
- for (int sbc = 0; sbc < mAllowedSuiteBCiphers.size(); sbc++) {
- if (mAllowedSuiteBCiphers.get(sbc)) {
- sbuf.append(" ");
- if (sbc < SuiteBCipher.strings.length) {
- sbuf.append(SuiteBCipher.strings[sbc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" RequirePmf: ").append(mRequirePmf).append('\n');
- sbuf.append(" IsAddedByAutoUpgrade: ").append(mIsAddedByAutoUpgrade).append("\n");
- sbuf.append(" IsSaeH2eOnlyMode: ").append(mIsSaeH2eOnlyMode).append("\n");
- sbuf.append(" IsSaePkOnlyMode: ").append(mIsSaePkOnlyMode).append("\n");
- return sbuf.toString();
- }
-
- private static BitSet readBitSet(Parcel src) {
- int cardinality = src.readInt();
-
- BitSet set = new BitSet();
- for (int i = 0; i < cardinality; i++) {
- set.set(src.readInt());
- }
-
- return set;
- }
-
- private static void writeBitSet(Parcel dest, BitSet set) {
- int nextSetBit = -1;
-
- dest.writeInt(set.cardinality());
-
- while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
- dest.writeInt(nextSetBit);
- }
- }
-
- /** Write this object to the parcel. */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mSecurityType);
- dest.writeBoolean(mEnabled);
- writeBitSet(dest, mAllowedKeyManagement);
- writeBitSet(dest, mAllowedProtocols);
- writeBitSet(dest, mAllowedAuthAlgorithms);
- writeBitSet(dest, mAllowedPairwiseCiphers);
- writeBitSet(dest, mAllowedGroupCiphers);
- writeBitSet(dest, mAllowedGroupManagementCiphers);
- writeBitSet(dest, mAllowedSuiteBCiphers);
- dest.writeBoolean(mRequirePmf);
- dest.writeBoolean(mIsAddedByAutoUpgrade);
- dest.writeBoolean(mIsSaeH2eOnlyMode);
- dest.writeBoolean(mIsSaePkOnlyMode);
-
- }
-
- /** Create a SecurityParams object from the parcel. */
- public static final @NonNull SecurityParams createFromParcel(Parcel in) {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = in.readInt();
- params.mEnabled = in.readBoolean();
- params.mAllowedKeyManagement = readBitSet(in);
- params.mAllowedProtocols = readBitSet(in);
- params.mAllowedAuthAlgorithms = readBitSet(in);
- params.mAllowedPairwiseCiphers = readBitSet(in);
- params.mAllowedGroupCiphers = readBitSet(in);
- params.mAllowedGroupManagementCiphers = readBitSet(in);
- params.mAllowedSuiteBCiphers = readBitSet(in);
- params.mRequirePmf = in.readBoolean();
- params.mIsAddedByAutoUpgrade = in.readBoolean();
- params.mIsSaeH2eOnlyMode = in.readBoolean();
- params.mIsSaePkOnlyMode = in.readBoolean();
- return params;
- }
-
- /**
- * Create a params according to the security type.
- *
- * @param securityType One of the following security types:
- * {@link WifiConfiguration#SECURITY_TYPE_OPEN},
- * {@link WifiConfiguration#SECURITY_TYPE_WEP},
- * {@link WifiConfiguration#SECURITY_TYPE_PSK},
- * {@link WifiConfiguration#SECURITY_TYPE_EAP},
- * {@link WifiConfiguration#SECURITY_TYPE_SAE},
- * {@link WifiConfiguration#SECURITY_TYPE_OWE},
- * {@link WifiConfiguration#SECURITY_TYPE_WAPI_PSK},
- * {@link WifiConfiguration#SECURITY_TYPE_WAPI_CERT},
- * {@link WifiConfiguration#SECURITY_TYPE_EAP_WPA3_ENTERPRISE},
- * {@link WifiConfiguration#SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT},
- *
- * @return the corresponding security params if the security type is valid;
- * otherwise, throw IllegalArgumentException.
- */
- public static @NonNull SecurityParams createSecurityParamsBySecurityType(
- @WifiConfiguration.SecurityType int securityType) {
- switch (securityType) {
- case WifiConfiguration.SECURITY_TYPE_OPEN:
- return createOpenParams();
- case WifiConfiguration.SECURITY_TYPE_WEP:
- return createWepParams();
- case WifiConfiguration.SECURITY_TYPE_PSK:
- return createWpaWpa2PersonalParams();
- case WifiConfiguration.SECURITY_TYPE_EAP:
- return createWpaWpa2EnterpriseParams();
- case WifiConfiguration.SECURITY_TYPE_SAE:
- return createWpa3PersonalParams();
- // The value of {@link WifiConfiguration.SECURITY_TYPE_EAP_SUITE_B} is the same as
- // {@link #WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT}, remove it
- // to avoid duplicate case label errors.
- case WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT:
- return createWpa3Enterprise192BitParams();
- case WifiConfiguration.SECURITY_TYPE_OWE:
- return createEnhancedOpenParams();
- case WifiConfiguration.SECURITY_TYPE_WAPI_PSK:
- return createWapiPskParams();
- case WifiConfiguration.SECURITY_TYPE_WAPI_CERT:
- return createWapiCertParams();
- case WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE:
- return createWpa3EnterpriseParams();
- case WifiConfiguration.SECURITY_TYPE_OSEN:
- return createOsenParams();
- case WifiConfiguration.SECURITY_TYPE_PASSPOINT_R1_R2:
- return SecurityParams.createPasspointParams(PASSPOINT_R2);
- case WifiConfiguration.SECURITY_TYPE_PASSPOINT_R3:
- return SecurityParams.createPasspointParams(PASSPOINT_R3);
- default:
- throw new IllegalArgumentException("unknown security type " + securityType);
- }
- }
-
- /**
- * Create EAP security params.
- */
- private static @NonNull SecurityParams createWpaWpa2EnterpriseParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_EAP;
-
- params.mAllowedKeyManagement.set(KeyMgmt.WPA_EAP);
- params.mAllowedKeyManagement.set(KeyMgmt.IEEE8021X);
-
- params.mAllowedProtocols.set(Protocol.RSN);
- params.mAllowedProtocols.set(Protocol.WPA);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.CCMP);
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.TKIP);
-
- params.mAllowedGroupCiphers.set(GroupCipher.CCMP);
- params.mAllowedGroupCiphers.set(GroupCipher.TKIP);
- return params;
- }
-
- /**
- * Create Passpoint security params.
- */
- private static @NonNull SecurityParams createPasspointParams(@PasspointRelease int release) {
- SecurityParams params = new SecurityParams();
- switch (release) {
- case PASSPOINT_R1:
- case PASSPOINT_R2:
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_PASSPOINT_R1_R2;
- break;
- case PASSPOINT_R3:
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_PASSPOINT_R3;
- params.mRequirePmf = true;
- break;
- default:
- throw new IllegalArgumentException("invalid passpoint release " + release);
- }
-
- params.mAllowedKeyManagement.set(KeyMgmt.WPA_EAP);
- params.mAllowedKeyManagement.set(KeyMgmt.IEEE8021X);
-
- params.mAllowedProtocols.set(Protocol.RSN);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.CCMP);
-
- params.mAllowedGroupCiphers.set(GroupCipher.CCMP);
-
- return params;
- }
-
- /**
- * Create Enhanced Open params.
- */
- private static @NonNull SecurityParams createEnhancedOpenParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_OWE;
-
- params.mAllowedKeyManagement.set(KeyMgmt.OWE);
-
- params.mAllowedProtocols.set(Protocol.RSN);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.CCMP);
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.GCMP_128);
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.GCMP_256);
-
- params.mAllowedGroupCiphers.set(GroupCipher.CCMP);
- params.mAllowedGroupCiphers.set(GroupCipher.GCMP_128);
- params.mAllowedGroupCiphers.set(GroupCipher.GCMP_256);
-
- params.mRequirePmf = true;
- return params;
- }
-
- /**
- * Create Open params.
- */
- private static @NonNull SecurityParams createOpenParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_OPEN;
-
- params.mAllowedKeyManagement.set(KeyMgmt.NONE);
-
- params.mAllowedProtocols.set(Protocol.RSN);
- params.mAllowedProtocols.set(Protocol.WPA);
- return params;
- }
-
- /**
- * Create OSEN params.
- */
- private static @NonNull SecurityParams createOsenParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_OSEN;
-
- params.mAllowedKeyManagement.set(KeyMgmt.OSEN);
-
- params.mAllowedProtocols.set(Protocol.OSEN);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.CCMP);
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.TKIP);
-
- params.mAllowedGroupCiphers.set(GroupCipher.CCMP);
- params.mAllowedGroupCiphers.set(GroupCipher.TKIP);
- return params;
- }
-
- /**
- * Create WAPI-CERT params.
- */
- private static @NonNull SecurityParams createWapiCertParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_WAPI_CERT;
-
- params.mAllowedKeyManagement.set(KeyMgmt.WAPI_CERT);
-
- params.mAllowedProtocols.set(Protocol.WAPI);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.SMS4);
-
- params.mAllowedGroupCiphers.set(GroupCipher.SMS4);
- return params;
- }
-
- /**
- * Create WAPI-PSK params.
- */
- private static @NonNull SecurityParams createWapiPskParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_WAPI_PSK;
-
- params.mAllowedKeyManagement.set(KeyMgmt.WAPI_PSK);
-
- params.mAllowedProtocols.set(Protocol.WAPI);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.SMS4);
-
- params.mAllowedGroupCiphers.set(GroupCipher.SMS4);
- return params;
- }
-
- /**
- * Create WEP params.
- */
- private static @NonNull SecurityParams createWepParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_WEP;
-
- params.mAllowedKeyManagement.set(KeyMgmt.NONE);
-
- params.mAllowedProtocols.set(Protocol.RSN);
-
- params.mAllowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
- params.mAllowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.CCMP);
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.TKIP);
-
- params.mAllowedGroupCiphers.set(GroupCipher.CCMP);
- params.mAllowedGroupCiphers.set(GroupCipher.TKIP);
- params.mAllowedGroupCiphers.set(GroupCipher.WEP40);
- params.mAllowedGroupCiphers.set(GroupCipher.WEP104);
- return params;
- }
-
- /**
- * Create WPA3 Enterprise 192-bit params.
- */
- private static @NonNull SecurityParams createWpa3Enterprise192BitParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT;
-
- params.mAllowedKeyManagement.set(KeyMgmt.WPA_EAP);
- params.mAllowedKeyManagement.set(KeyMgmt.IEEE8021X);
- params.mAllowedKeyManagement.set(KeyMgmt.SUITE_B_192);
-
- params.mAllowedProtocols.set(Protocol.RSN);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.GCMP_128);
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.GCMP_256);
-
- params.mAllowedGroupCiphers.set(GroupCipher.GCMP_128);
- params.mAllowedGroupCiphers.set(GroupCipher.GCMP_256);
-
- params.mAllowedGroupManagementCiphers.set(GroupMgmtCipher.BIP_GMAC_256);
-
- // Note: allowedSuiteBCiphers bitset will be set by the service once the
- // certificates are attached to this profile
-
- params.mRequirePmf = true;
- return params;
- }
-
- /**
- * Create WPA3 Enterprise params.
- */
- private static @NonNull SecurityParams createWpa3EnterpriseParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE;
-
- params.mAllowedKeyManagement.set(KeyMgmt.WPA_EAP);
- params.mAllowedKeyManagement.set(KeyMgmt.IEEE8021X);
-
- params.mAllowedProtocols.set(Protocol.RSN);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.CCMP);
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.GCMP_256);
-
- params.mAllowedGroupCiphers.set(GroupCipher.CCMP);
- params.mAllowedGroupCiphers.set(GroupCipher.GCMP_256);
-
- params.mRequirePmf = true;
- return params;
- }
-
- /**
- * Create WPA3 Personal params.
- */
- private static @NonNull SecurityParams createWpa3PersonalParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_SAE;
-
- params.mAllowedKeyManagement.set(KeyMgmt.SAE);
-
- params.mAllowedProtocols.set(Protocol.RSN);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.CCMP);
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.GCMP_128);
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.GCMP_256);
-
- params.mAllowedGroupCiphers.set(GroupCipher.CCMP);
- params.mAllowedGroupCiphers.set(GroupCipher.GCMP_128);
- params.mAllowedGroupCiphers.set(GroupCipher.GCMP_256);
-
- params.mRequirePmf = true;
- return params;
- }
-
- /**
- * Create WPA/WPA2 Personal params.
- */
- private static @NonNull SecurityParams createWpaWpa2PersonalParams() {
- SecurityParams params = new SecurityParams();
- params.mSecurityType = WifiConfiguration.SECURITY_TYPE_PSK;
-
- params.mAllowedKeyManagement.set(KeyMgmt.WPA_PSK);
-
- params.mAllowedProtocols.set(Protocol.RSN);
- params.mAllowedProtocols.set(Protocol.WPA);
-
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.CCMP);
- params.mAllowedPairwiseCiphers.set(PairwiseCipher.TKIP);
-
- params.mAllowedGroupCiphers.set(GroupCipher.CCMP);
- params.mAllowedGroupCiphers.set(GroupCipher.TKIP);
- params.mAllowedGroupCiphers.set(GroupCipher.WEP40);
- params.mAllowedGroupCiphers.set(GroupCipher.WEP104);
- return params;
- }
-}
diff --git a/wifi/java/android/net/wifi/SoftApCapability.java b/wifi/java/android/net/wifi/SoftApCapability.java
deleted file mode 100644
index 6f72f0b58b4bd..0000000000000
--- a/wifi/java/android/net/wifi/SoftApCapability.java
+++ /dev/null
@@ -1,315 +0,0 @@
-/*
- * 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 android.net.wifi;
-
-import android.annotation.LongDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.wifi.SoftApConfiguration.BandType;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import com.android.modules.utils.build.SdkLevel;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Arrays;
-import java.util.Objects;
-
-/**
- * A class representing capability of the SoftAp.
- * {@see WifiManager}
- *
- * @hide
- */
-@SystemApi
-public final class SoftApCapability implements Parcelable {
-
- private static final String TAG = "SoftApCapability";
- private static final int[] EMPTY_INT_ARRAY = new int[0];
- /**
- * Support for automatic channel selection in driver (ACS).
- * Driver will auto select best channel based on interference to optimize performance.
- *
- * flag when {@link R.bool.config_wifi_softap_acs_supported} is true.
- *
- *
- * Use {@link WifiManager.SoftApCallback#onInfoChanged(SoftApInfo)} and
- * {@link SoftApInfo#getFrequency} and {@link SoftApInfo#getBandwidth} to get
- * driver channel selection result.
- */
- public static final long SOFTAP_FEATURE_ACS_OFFLOAD = 1 << 0;
-
- /**
- * Support for client force disconnect.
- * flag when {@link R.bool.config_wifiSofapClientForceDisconnectSupported} is true
- *
- *
- * Several Soft AP client control features, e.g. specifying the maximum number of
- * Soft AP clients, only work when this feature support is present.
- * Check feature support before invoking
- * {@link SoftApConfiguration.Builder#setMaxNumberOfClients(int)}
- */
- public static final long SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT = 1 << 1;
-
- /**
- * Support for WPA3 Simultaneous Authentication of Equals (WPA3-SAE).
- *
- * flag when {@link config_wifi_softap_sae_supported} is true.
- */
- public static final long SOFTAP_FEATURE_WPA3_SAE = 1 << 2;
-
- /**
- * Support for MAC address customization.
- * flag when {@link R.bool.config_wifiSoftapMacAddressCustomizationSupported} is true
- *
- *
- * Check feature support before invoking
- * {@link SoftApConfiguration.Builder#setBssid(MadAddress)} or
- * {@link SoftApConfiguration.Builder#setMacRandomizationSetting(int)} with
- * {@link SoftApConfiguration.RANDOMIZATION_PERSISTENT}
- */
- public static final long SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION = 1 << 3;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @LongDef(flag = true, prefix = { "SOFTAP_FEATURE_" }, value = {
- SOFTAP_FEATURE_ACS_OFFLOAD,
- SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT,
- SOFTAP_FEATURE_WPA3_SAE,
- SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION,
- })
- public @interface HotspotFeatures {}
-
- private @HotspotFeatures long mSupportedFeatures = 0;
-
- private int mMaximumSupportedClientNumber;
-
- /**
- * A list storing supported 2.4G channels.
- */
- private int[] mSupportedChannelListIn24g = EMPTY_INT_ARRAY;
-
- /**
- * A list storing supported 5G channels.
- */
- private int[] mSupportedChannelListIn5g = EMPTY_INT_ARRAY;
-
- /**
- * A list storing supported 6G channels.
- */
- private int[] mSupportedChannelListIn6g = EMPTY_INT_ARRAY;
-
- /**
- * A list storing supported 60G channels.
- */
- private int[] mSupportedChannelListIn60g = EMPTY_INT_ARRAY;
-
- /**
- * Get the maximum supported client numbers which AP resides on.
- */
- public int getMaxSupportedClients() {
- return mMaximumSupportedClientNumber;
- }
-
- /**
- * Set the maximum supported client numbers which AP resides on.
- *
- * @param maxClient maximum supported client numbers for the softap.
- * @hide
- */
- public void setMaxSupportedClients(int maxClient) {
- mMaximumSupportedClientNumber = maxClient;
- }
-
- /**
- * Returns true when all of the queried features are supported, otherwise false.
- *
- * @param features One or combination of the following features:
- * {@link #SOFTAP_FEATURE_ACS_OFFLOAD}, {@link #SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT} or
- * {@link #SOFTAP_FEATURE_WPA3_SAE}.
- */
- public boolean areFeaturesSupported(@HotspotFeatures long features) {
- return (mSupportedFeatures & features) == features;
- }
-
- /**
- * Set supported channel list in target band type.
- *
- * @param band One of the following band types:
- * {@link SoftApConfiguation#BAND_2GHZ}, {@link SoftApConfiguation#BAND_5GHZ},
- * {@link SoftApConfiguation#BAND_6GHZ}, or {@link SoftApConfiguation#BAND_60GHZ}.
- * @param supportedChannelList supported channel list in target band
- * @return true if band and supportedChannelList are valid, otherwise false.
- *
- * @throws IllegalArgumentException when band type is invalid.
- * @hide
- */
- public boolean setSupportedChannelList(@BandType int band,
- @Nullable int[] supportedChannelList) {
- if (supportedChannelList == null) return false;
- switch (band) {
- case SoftApConfiguration.BAND_2GHZ:
- mSupportedChannelListIn24g = supportedChannelList;
- break;
- case SoftApConfiguration.BAND_5GHZ:
- mSupportedChannelListIn5g = supportedChannelList;
- break;
- case SoftApConfiguration.BAND_6GHZ:
- mSupportedChannelListIn6g = supportedChannelList;
- break;
- case SoftApConfiguration.BAND_60GHZ:
- mSupportedChannelListIn60g = supportedChannelList;
- break;
- default:
- throw new IllegalArgumentException("Invalid band: " + band);
- }
- return true;
- }
-
- /**
- * Returns a list of the supported channels in the given band.
- * The result depends on the on the country code that has been set.
- * Can be used to set the channel of the AP with the
- * {@link SoftapConfiguration.Builder#setChannel(int, int)} API.
- *
- * @param band One of the following band types:
- * {@link SoftApConfiguation#BAND_2GHZ}, {@link SoftApConfiguation#BAND_5GHZ},
- * {@link SoftApConfiguation#BAND_6GHZ}, {@link SoftApConfiguation#BAND_60GHZ}.
- * @return List of supported channels for the band.
- *
- * @throws IllegalArgumentException when band type is invalid.
- */
- @NonNull
- public int[] getSupportedChannelList(@BandType int band) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- switch (band) {
- case SoftApConfiguration.BAND_2GHZ:
- return mSupportedChannelListIn24g;
- case SoftApConfiguration.BAND_5GHZ:
- return mSupportedChannelListIn5g;
- case SoftApConfiguration.BAND_6GHZ:
- return mSupportedChannelListIn6g;
- case SoftApConfiguration.BAND_60GHZ:
- return mSupportedChannelListIn60g;
- default:
- throw new IllegalArgumentException("Invalid band: " + band);
- }
- }
-
- /**
- * @hide
- */
- public SoftApCapability(@Nullable SoftApCapability source) {
- if (source != null) {
- mSupportedFeatures = source.mSupportedFeatures;
- mMaximumSupportedClientNumber = source.mMaximumSupportedClientNumber;
- mSupportedChannelListIn24g = source.mSupportedChannelListIn24g;
- mSupportedChannelListIn5g = source.mSupportedChannelListIn5g;
- mSupportedChannelListIn6g = source.mSupportedChannelListIn6g;
- mSupportedChannelListIn60g = source.mSupportedChannelListIn60g;
- }
- }
-
- /**
- * Constructor with combination of the feature.
- * Zero to no supported feature.
- *
- * @param features One or combination of the following features:
- * {@link #SOFTAP_FEATURE_ACS_OFFLOAD}, {@link #SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT} or
- * {@link #SOFTAP_FEATURE_WPA3_SAE}.
- * @hide
- */
- public SoftApCapability(@HotspotFeatures long features) {
- mSupportedFeatures = features;
- }
-
- @Override
- /** Implement the Parcelable interface. */
- public int describeContents() {
- return 0;
- }
-
- @Override
- /** Implement the Parcelable interface */
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeLong(mSupportedFeatures);
- dest.writeInt(mMaximumSupportedClientNumber);
- dest.writeIntArray(mSupportedChannelListIn24g);
- dest.writeIntArray(mSupportedChannelListIn5g);
- dest.writeIntArray(mSupportedChannelListIn6g);
- dest.writeIntArray(mSupportedChannelListIn60g);
- }
-
- @NonNull
- /** Implement the Parcelable interface */
- public static final Creator CREATOR = new Creator() {
- public SoftApCapability createFromParcel(Parcel in) {
- SoftApCapability capability = new SoftApCapability(in.readLong());
- capability.mMaximumSupportedClientNumber = in.readInt();
- capability.setSupportedChannelList(SoftApConfiguration.BAND_2GHZ, in.createIntArray());
- capability.setSupportedChannelList(SoftApConfiguration.BAND_5GHZ, in.createIntArray());
- capability.setSupportedChannelList(SoftApConfiguration.BAND_6GHZ, in.createIntArray());
- capability.setSupportedChannelList(SoftApConfiguration.BAND_60GHZ, in.createIntArray());
- return capability;
- }
-
- public SoftApCapability[] newArray(int size) {
- return new SoftApCapability[size];
- }
- };
-
- @NonNull
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- sbuf.append("SupportedFeatures=").append(mSupportedFeatures);
- sbuf.append("MaximumSupportedClientNumber=").append(mMaximumSupportedClientNumber);
- sbuf.append("SupportedChannelListIn24g")
- .append(Arrays.toString(mSupportedChannelListIn24g));
- sbuf.append("SupportedChannelListIn5g").append(Arrays.toString(mSupportedChannelListIn5g));
- sbuf.append("SupportedChannelListIn6g").append(Arrays.toString(mSupportedChannelListIn6g));
- sbuf.append("SupportedChannelListIn60g")
- .append(Arrays.toString(mSupportedChannelListIn60g));
- return sbuf.toString();
- }
-
- @Override
- public boolean equals(@NonNull Object o) {
- if (this == o) return true;
- if (!(o instanceof SoftApCapability)) return false;
- SoftApCapability capability = (SoftApCapability) o;
- return mSupportedFeatures == capability.mSupportedFeatures
- && mMaximumSupportedClientNumber == capability.mMaximumSupportedClientNumber
- && Arrays.equals(mSupportedChannelListIn24g, capability.mSupportedChannelListIn24g)
- && Arrays.equals(mSupportedChannelListIn5g, capability.mSupportedChannelListIn5g)
- && Arrays.equals(mSupportedChannelListIn6g, capability.mSupportedChannelListIn6g)
- && Arrays.equals(mSupportedChannelListIn60g, capability.mSupportedChannelListIn60g);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mSupportedFeatures, mMaximumSupportedClientNumber,
- Arrays.hashCode(mSupportedChannelListIn24g),
- Arrays.hashCode(mSupportedChannelListIn5g),
- Arrays.hashCode(mSupportedChannelListIn6g),
- Arrays.hashCode(mSupportedChannelListIn60g));
- }
-}
diff --git a/wifi/java/android/net/wifi/SoftApConfiguration.java b/wifi/java/android/net/wifi/SoftApConfiguration.java
deleted file mode 100644
index d36acb72ff8ae..0000000000000
--- a/wifi/java/android/net/wifi/SoftApConfiguration.java
+++ /dev/null
@@ -1,1279 +0,0 @@
-/*
- * 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 android.net.wifi;
-
-import android.annotation.IntDef;
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.SparseIntArray;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.Preconditions;
-import com.android.modules.utils.build.SdkLevel;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * Configuration for a soft access point (a.k.a. Soft AP, SAP, Hotspot).
- *
- * This is input for the framework provided by a client app, i.e. it exposes knobs to instruct the
- * framework how it should configure a hotspot.
- *
- * System apps can use this to configure a tethered hotspot using
- * {@code WifiManager#startTetheredHotspot(SoftApConfiguration)} and
- * {@code WifiManager#setSoftApConfiguration(SoftApConfiguration)}
- * or local-only hotspot using
- * {@code WifiManager#startLocalOnlyHotspot(SoftApConfiguration, Executor,
- * WifiManager.LocalOnlyHotspotCallback)}.
- *
- * Instances of this class are immutable; use {@link SoftApConfiguration.Builder} and its methods to
- * create a new instance.
- *
- */
-public final class SoftApConfiguration implements Parcelable {
-
- private static final String TAG = "SoftApConfiguration";
-
- @VisibleForTesting
- static final int PSK_MIN_LEN = 8;
-
- @VisibleForTesting
- static final int PSK_MAX_LEN = 63;
-
- /**
- * 2GHz band.
- * @hide
- */
- @SystemApi
- public static final int BAND_2GHZ = 1 << 0;
-
- /**
- * 5GHz band.
- * @hide
- */
- @SystemApi
- public static final int BAND_5GHZ = 1 << 1;
-
- /**
- * 6GHz band.
- * @hide
- */
- @SystemApi
- public static final int BAND_6GHZ = 1 << 2;
-
- /**
- * 60GHz band.
- * @hide
- */
- @SystemApi
- public static final int BAND_60GHZ = 1 << 3;
-
- /**
- * Device is allowed to choose the optimal band (2Ghz, 5Ghz, 6Ghz) based on device capability,
- * operating country code and current radio conditions.
- * @hide
- *
- * @deprecated The bands are a bit mask - use any combination of {@code BAND_},
- * for instance {@code BAND_2GHZ | BAND_5GHZ | BAND_6GHZ}.
- */
- @SystemApi
- public static final int BAND_ANY = BAND_2GHZ | BAND_5GHZ | BAND_6GHZ;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(flag = true, prefix = { "BAND_TYPE_" }, value = {
- BAND_2GHZ,
- BAND_5GHZ,
- BAND_6GHZ,
- BAND_60GHZ,
- })
- public @interface BandType {}
-
- private static boolean isBandValid(@BandType int band) {
- int bandAny = BAND_2GHZ | BAND_5GHZ | BAND_6GHZ | BAND_60GHZ;
- return ((band != 0) && ((band & ~bandAny) == 0));
- }
-
- private static final int MIN_CH_2G_BAND = 1;
- private static final int MAX_CH_2G_BAND = 14;
- private static final int MIN_CH_5G_BAND = 34;
- private static final int MAX_CH_5G_BAND = 196;
- private static final int MIN_CH_6G_BAND = 1;
- private static final int MAX_CH_6G_BAND = 253;
- private static final int MIN_CH_60G_BAND = 1;
- private static final int MAX_CH_60G_BAND = 6;
-
-
-
- private static boolean isChannelBandPairValid(int channel, @BandType int band) {
- switch (band) {
- case BAND_2GHZ:
- if (channel < MIN_CH_2G_BAND || channel > MAX_CH_2G_BAND) {
- return false;
- }
- break;
-
- case BAND_5GHZ:
- if (channel < MIN_CH_5G_BAND || channel > MAX_CH_5G_BAND) {
- return false;
- }
- break;
-
- case BAND_6GHZ:
- if (channel < MIN_CH_6G_BAND || channel > MAX_CH_6G_BAND) {
- return false;
- }
- break;
-
- case BAND_60GHZ:
- if (channel < MIN_CH_60G_BAND || channel > MAX_CH_60G_BAND) {
- return false;
- }
- break;
-
- default:
- return false;
- }
- return true;
- }
-
- /**
- * SSID for the AP, or null for a framework-determined SSID.
- */
- private final @Nullable String mSsid;
-
- /**
- * BSSID for the AP, or null to use a framework-determined BSSID.
- */
- private final @Nullable MacAddress mBssid;
-
- /**
- * Pre-shared key for WPA2-PSK or WPA3-SAE-Transition or WPA3-SAE encryption which depends on
- * the security type.
- */
- private final @Nullable String mPassphrase;
-
- /**
- * This is a network that does not broadcast its SSID, so an
- * SSID-specific probe request must be used for scans.
- */
- private final boolean mHiddenSsid;
-
- /**
- * The operating channels of the dual APs.
- *
- * The SparseIntArray that consists the band and the channel of matching the band.
- */
- @NonNull
- private final SparseIntArray mChannels;
-
- /**
- * The maximim allowed number of clients that can associate to the AP.
- */
- private final int mMaxNumberOfClients;
-
- /**
- * The operating security type of the AP.
- * One of the following security types:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WPA2_PSK},
- * {@link #SECURITY_TYPE_WPA3_SAE_TRANSITION},
- * {@link #SECURITY_TYPE_WPA3_SAE}
- */
- private final @SecurityType int mSecurityType;
-
- /**
- * The flag to indicate client need to authorize by user
- * when client is connecting to AP.
- */
- private final boolean mClientControlByUser;
-
- /**
- * The list of blocked client that can't associate to the AP.
- */
- private final List mBlockedClientList;
-
- /**
- * The list of allowed client that can associate to the AP.
- */
- private final List mAllowedClientList;
-
- /**
- * Whether auto shutdown of soft AP is enabled or not.
- */
- private final boolean mAutoShutdownEnabled;
-
- /**
- * Delay in milliseconds before shutting down soft AP when
- * there are no connected devices.
- */
- private final long mShutdownTimeoutMillis;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"RANDOMIZATION_"}, value = {
- RANDOMIZATION_NONE,
- RANDOMIZATION_PERSISTENT})
- public @interface MacRandomizationSetting {}
-
- /**
- * Use factory MAC as BSSID for the AP
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_NONE = 0;
- /**
- * Generate a randomized MAC as BSSID for the AP
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_PERSISTENT = 1;
-
- /**
- * Level of MAC randomization for the AP BSSID.
- * @hide
- */
- @MacRandomizationSetting
- private int mMacRandomizationSetting;
-
-
- /**
- * THe definition of security type OPEN.
- */
- public static final int SECURITY_TYPE_OPEN = 0;
-
- /**
- * The definition of security type WPA2-PSK.
- */
- public static final int SECURITY_TYPE_WPA2_PSK = 1;
-
- /**
- * The definition of security type WPA3-SAE Transition mode.
- */
- public static final int SECURITY_TYPE_WPA3_SAE_TRANSITION = 2;
-
- /**
- * The definition of security type WPA3-SAE.
- */
- public static final int SECURITY_TYPE_WPA3_SAE = 3;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = { "SECURITY_TYPE_" }, value = {
- SECURITY_TYPE_OPEN,
- SECURITY_TYPE_WPA2_PSK,
- SECURITY_TYPE_WPA3_SAE_TRANSITION,
- SECURITY_TYPE_WPA3_SAE,
- })
- public @interface SecurityType {}
-
- /** Private constructor for Builder and Parcelable implementation. */
- private SoftApConfiguration(@Nullable String ssid, @Nullable MacAddress bssid,
- @Nullable String passphrase, boolean hiddenSsid, @NonNull SparseIntArray channels,
- @SecurityType int securityType, int maxNumberOfClients, boolean shutdownTimeoutEnabled,
- long shutdownTimeoutMillis, boolean clientControlByUser,
- @NonNull List blockedList, @NonNull List allowedList,
- int macRandomizationSetting) {
- mSsid = ssid;
- mBssid = bssid;
- mPassphrase = passphrase;
- mHiddenSsid = hiddenSsid;
- if (channels.size() != 0) {
- mChannels = channels.clone();
- } else {
- mChannels = new SparseIntArray(1);
- mChannels.put(BAND_2GHZ, 0);
- }
- mSecurityType = securityType;
- mMaxNumberOfClients = maxNumberOfClients;
- mAutoShutdownEnabled = shutdownTimeoutEnabled;
- mShutdownTimeoutMillis = shutdownTimeoutMillis;
- mClientControlByUser = clientControlByUser;
- mBlockedClientList = new ArrayList<>(blockedList);
- mAllowedClientList = new ArrayList<>(allowedList);
- mMacRandomizationSetting = macRandomizationSetting;
- }
-
- @Override
- public boolean equals(Object otherObj) {
- if (this == otherObj) {
- return true;
- }
- if (!(otherObj instanceof SoftApConfiguration)) {
- return false;
- }
- SoftApConfiguration other = (SoftApConfiguration) otherObj;
- return Objects.equals(mSsid, other.mSsid)
- && Objects.equals(mBssid, other.mBssid)
- && Objects.equals(mPassphrase, other.mPassphrase)
- && mHiddenSsid == other.mHiddenSsid
- && mChannels.toString().equals(other.mChannels.toString())
- && mSecurityType == other.mSecurityType
- && mMaxNumberOfClients == other.mMaxNumberOfClients
- && mAutoShutdownEnabled == other.mAutoShutdownEnabled
- && mShutdownTimeoutMillis == other.mShutdownTimeoutMillis
- && mClientControlByUser == other.mClientControlByUser
- && Objects.equals(mBlockedClientList, other.mBlockedClientList)
- && Objects.equals(mAllowedClientList, other.mAllowedClientList)
- && mMacRandomizationSetting == other.mMacRandomizationSetting;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mSsid, mBssid, mPassphrase, mHiddenSsid,
- mChannels.toString(), mSecurityType, mMaxNumberOfClients, mAutoShutdownEnabled,
- mShutdownTimeoutMillis, mClientControlByUser, mBlockedClientList,
- mAllowedClientList, mMacRandomizationSetting);
- }
-
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- sbuf.append("ssid = ").append(mSsid);
- if (mBssid != null) sbuf.append(" \n bssid = ").append(mBssid.toString());
- sbuf.append(" \n Passphrase = ").append(
- TextUtils.isEmpty(mPassphrase) ? "" : "");
- sbuf.append(" \n HiddenSsid = ").append(mHiddenSsid);
- sbuf.append(" \n Channels = ").append(mChannels);
- sbuf.append(" \n SecurityType = ").append(getSecurityType());
- sbuf.append(" \n MaxClient = ").append(mMaxNumberOfClients);
- sbuf.append(" \n AutoShutdownEnabled = ").append(mAutoShutdownEnabled);
- sbuf.append(" \n ShutdownTimeoutMillis = ").append(mShutdownTimeoutMillis);
- sbuf.append(" \n ClientControlByUser = ").append(mClientControlByUser);
- sbuf.append(" \n BlockedClientList = ").append(mBlockedClientList);
- sbuf.append(" \n AllowedClientList= ").append(mAllowedClientList);
- sbuf.append(" \n MacRandomizationSetting = ").append(mMacRandomizationSetting);
- return sbuf.toString();
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeString(mSsid);
- dest.writeParcelable(mBssid, flags);
- dest.writeString(mPassphrase);
- dest.writeBoolean(mHiddenSsid);
- writeSparseIntArray(dest, mChannels);
- dest.writeInt(mSecurityType);
- dest.writeInt(mMaxNumberOfClients);
- dest.writeBoolean(mAutoShutdownEnabled);
- dest.writeLong(mShutdownTimeoutMillis);
- dest.writeBoolean(mClientControlByUser);
- dest.writeTypedList(mBlockedClientList);
- dest.writeTypedList(mAllowedClientList);
- dest.writeInt(mMacRandomizationSetting);
- }
-
- /* Reference from frameworks/base/core/java/android/os/Parcel.java */
- private static void writeSparseIntArray(@NonNull Parcel dest,
- @Nullable SparseIntArray val) {
- if (val == null) {
- dest.writeInt(-1);
- return;
- }
- int n = val.size();
- dest.writeInt(n);
- int i = 0;
- while (i < n) {
- dest.writeInt(val.keyAt(i));
- dest.writeInt(val.valueAt(i));
- i++;
- }
- }
-
-
- /* Reference from frameworks/base/core/java/android/os/Parcel.java */
- @NonNull
- private static SparseIntArray readSparseIntArray(@NonNull Parcel in) {
- int n = in.readInt();
- if (n < 0) {
- return new SparseIntArray();
- }
- SparseIntArray sa = new SparseIntArray(n);
- while (n > 0) {
- int key = in.readInt();
- int value = in.readInt();
- sa.append(key, value);
- n--;
- }
- return sa;
- }
-
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @NonNull
- public static final Creator CREATOR = new Creator() {
- @Override
- public SoftApConfiguration createFromParcel(Parcel in) {
- return new SoftApConfiguration(
- in.readString(),
- in.readParcelable(MacAddress.class.getClassLoader()),
- in.readString(), in.readBoolean(), readSparseIntArray(in), in.readInt(),
- in.readInt(), in.readBoolean(), in.readLong(), in.readBoolean(),
- in.createTypedArrayList(MacAddress.CREATOR),
- in.createTypedArrayList(MacAddress.CREATOR), in.readInt());
- }
-
- @Override
- public SoftApConfiguration[] newArray(int size) {
- return new SoftApConfiguration[size];
- }
- };
-
- /**
- * Return String set to be the SSID for the AP.
- * See also {@link Builder#setSsid(String)}.
- */
- @Nullable
- public String getSsid() {
- return mSsid;
- }
-
- /**
- * Returns MAC address set to be BSSID for the AP.
- * See also {@link Builder#setBssid(MacAddress)}.
- */
- @Nullable
- public MacAddress getBssid() {
- return mBssid;
- }
-
- /**
- * Returns String set to be passphrase for current AP.
- * See also {@link Builder#setPassphrase(String, int)}.
- */
- @Nullable
- public String getPassphrase() {
- return mPassphrase;
- }
-
- /**
- * Returns Boolean set to be indicate hidden (true: doesn't broadcast its SSID) or
- * not (false: broadcasts its SSID) for the AP.
- * See also {@link Builder#setHiddenSsid(boolean)}.
- */
- public boolean isHiddenSsid() {
- return mHiddenSsid;
- }
-
- /**
- * Returns band type set to be the band for the AP.
- *
- * One or combination of {@code BAND_}, for instance
- * {@link #BAND_2GHZ}, {@link #BAND_5GHZ}, or {@code BAND_2GHZ | BAND_5GHZ}.
- *
- * Note: Returns the lowest band when more than one band is set.
- * Use {@link #getBands()} to get dual bands setting.
- *
- * See also {@link Builder#setBand(int)}.
- *
- * @hide
- */
- @SystemApi
- public @BandType int getBand() {
- return mChannels.keyAt(0);
- }
-
- /**
- * Returns a sorted array in ascending order that consists of the configured band types
- * for the APs.
- *
- * The band type is one or combination of {@code BAND_}, for instance
- * {@link #BAND_2GHZ}, {@link #BAND_5GHZ}, or {@code BAND_2GHZ | BAND_5GHZ}.
- *
- * Note: return array may only include one band when current setting is single AP mode.
- * See also {@link Builder#setBands(int[])}.
- *
- * @hide
- */
- @SystemApi
- public @NonNull int[] getBands() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- int[] bands = new int[mChannels.size()];
- for (int i = 0; i < bands.length; i++) {
- bands[i] = mChannels.keyAt(i);
- }
- return bands;
- }
-
- /**
- * Returns Integer set to be the channel for the AP.
- *
- * Note: Returns the channel which associated to the lowest band if more than one channel
- * is set. Use {@link Builder#getChannels()} to get dual channel setting.
- * See also {@link Builder#setChannel(int, int)}.
- *
- * @hide
- */
- @SystemApi
- public int getChannel() {
- return mChannels.valueAt(0);
- }
-
-
- /**
- * Returns SparseIntArray (key: {@code BandType} , value: channel) that consists of
- * the configured bands and channels for the AP(s).
- *
- * Note: return array may only include one channel when current setting is single AP mode.
- * See also {@link Builder#setChannels(SparseIntArray)}.
- *
- * @hide
- */
- @SystemApi
- public @NonNull SparseIntArray getChannels() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mChannels.clone();
- }
-
- /**
- * Get security type params which depends on which security passphrase to set.
- *
- * @return One of:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WPA2_PSK},
- * {@link #SECURITY_TYPE_WPA3_SAE_TRANSITION},
- * {@link #SECURITY_TYPE_WPA3_SAE}
- */
- public @SecurityType int getSecurityType() {
- return mSecurityType;
- }
-
- /**
- * Returns the maximum number of clients that can associate to the AP.
- * See also {@link Builder#setMaxNumberOfClients(int)}.
- *
- * @hide
- */
- @SystemApi
- public int getMaxNumberOfClients() {
- return mMaxNumberOfClients;
- }
-
- /**
- * Returns whether auto shutdown is enabled or not.
- * The Soft AP will shutdown when there are no devices associated to it for
- * the timeout duration. See also {@link Builder#setAutoShutdownEnabled(boolean)}.
- *
- * @hide
- */
- @SystemApi
- public boolean isAutoShutdownEnabled() {
- return mAutoShutdownEnabled;
- }
-
- /**
- * Returns the shutdown timeout in milliseconds.
- * The Soft AP will shutdown when there are no devices associated to it for
- * the timeout duration. See also {@link Builder#setShutdownTimeoutMillis(long)}.
- *
- * @hide
- */
- @SystemApi
- public long getShutdownTimeoutMillis() {
- return mShutdownTimeoutMillis;
- }
-
- /**
- * Returns a flag indicating whether clients need to be pre-approved by the user.
- * (true: authorization required) or not (false: not required).
- * See also {@link Builder#setClientControlByUserEnabled(Boolean)}.
- *
- * @hide
- */
- @SystemApi
- public boolean isClientControlByUserEnabled() {
- return mClientControlByUser;
- }
-
- /**
- * Returns List of clients which aren't allowed to associate to the AP.
- *
- * Clients are configured using {@link Builder#setBlockedClientList(List)}
- *
- * @hide
- */
- @NonNull
- @SystemApi
- public List getBlockedClientList() {
- return mBlockedClientList;
- }
-
- /**
- * List of clients which are allowed to associate to the AP.
- * Clients are configured using {@link Builder#setAllowedClientList(List)}
- *
- * @hide
- */
- @NonNull
- @SystemApi
- public List getAllowedClientList() {
- return mAllowedClientList;
- }
-
- /**
- * Returns the level of MAC randomization for the AP BSSID.
- * See also {@link Builder#setMacRandomizationSetting(int)}.
- *
- * @hide
- */
- @SystemApi
- @MacRandomizationSetting
- public int getMacRandomizationSetting() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mMacRandomizationSetting;
- }
-
- /**
- * Returns a {@link WifiConfiguration} representation of this {@link SoftApConfiguration}.
- * Note that SoftApConfiguration may contain configuration which is cannot be represented
- * by the legacy WifiConfiguration, in such cases a null will be returned.
- *
- * SoftAp band in {@link WifiConfiguration.apBand} only supports
- * 2GHz, 5GHz, 2GHz+5GHz bands, so conversion is limited to these bands.
- *
- * SoftAp security type in {@link WifiConfiguration.KeyMgmt} only supports
- * NONE, WPA2_PSK, so conversion is limited to these security type.
- * @hide
- */
- @Nullable
- @SystemApi
- public WifiConfiguration toWifiConfiguration() {
- WifiConfiguration wifiConfig = new WifiConfiguration();
- wifiConfig.SSID = mSsid;
- wifiConfig.preSharedKey = mPassphrase;
- wifiConfig.hiddenSSID = mHiddenSsid;
- wifiConfig.apChannel = getChannel();
- switch (mSecurityType) {
- case SECURITY_TYPE_OPEN:
- wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
- break;
- case SECURITY_TYPE_WPA2_PSK:
- case SECURITY_TYPE_WPA3_SAE_TRANSITION:
- wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA2_PSK);
- break;
- default:
- Log.e(TAG, "Convert fail, unsupported security type :" + mSecurityType);
- return null;
- }
-
- switch (getBand()) {
- case BAND_2GHZ:
- wifiConfig.apBand = WifiConfiguration.AP_BAND_2GHZ;
- break;
- case BAND_5GHZ:
- wifiConfig.apBand = WifiConfiguration.AP_BAND_5GHZ;
- break;
- case BAND_2GHZ | BAND_5GHZ:
- wifiConfig.apBand = WifiConfiguration.AP_BAND_ANY;
- break;
- case BAND_ANY:
- wifiConfig.apBand = WifiConfiguration.AP_BAND_ANY;
- break;
- default:
- Log.e(TAG, "Convert fail, unsupported band setting :" + getBand());
- return null;
- }
- return wifiConfig;
- }
-
- /**
- * Builds a {@link SoftApConfiguration}, which allows an app to configure various aspects of a
- * Soft AP.
- *
- * All fields are optional. By default, SSID and BSSID are automatically chosen by the
- * framework, and an open network is created.
- *
- * @hide
- */
- @SystemApi
- public static final class Builder {
- private String mSsid;
- private MacAddress mBssid;
- private String mPassphrase;
- private boolean mHiddenSsid;
- private SparseIntArray mChannels;
- private int mMaxNumberOfClients;
- private int mSecurityType;
- private boolean mAutoShutdownEnabled;
- private long mShutdownTimeoutMillis;
- private boolean mClientControlByUser;
- private List mBlockedClientList;
- private List mAllowedClientList;
- private int mMacRandomizationSetting;
-
- /**
- * Constructs a Builder with default values (see {@link Builder}).
- */
- public Builder() {
- mSsid = null;
- mBssid = null;
- mPassphrase = null;
- mHiddenSsid = false;
- mChannels = new SparseIntArray(1);
- mChannels.put(BAND_2GHZ, 0);
- mMaxNumberOfClients = 0;
- mSecurityType = SECURITY_TYPE_OPEN;
- mAutoShutdownEnabled = true; // enabled by default.
- mShutdownTimeoutMillis = 0;
- mClientControlByUser = false;
- mBlockedClientList = new ArrayList<>();
- mAllowedClientList = new ArrayList<>();
- mMacRandomizationSetting = RANDOMIZATION_PERSISTENT;
- }
-
- /**
- * Constructs a Builder initialized from an existing {@link SoftApConfiguration} instance.
- */
- public Builder(@NonNull SoftApConfiguration other) {
- Objects.requireNonNull(other);
-
- mSsid = other.mSsid;
- mBssid = other.mBssid;
- mPassphrase = other.mPassphrase;
- mHiddenSsid = other.mHiddenSsid;
- mChannels = other.mChannels.clone();
- mMaxNumberOfClients = other.mMaxNumberOfClients;
- mSecurityType = other.mSecurityType;
- mAutoShutdownEnabled = other.mAutoShutdownEnabled;
- mShutdownTimeoutMillis = other.mShutdownTimeoutMillis;
- mClientControlByUser = other.mClientControlByUser;
- mBlockedClientList = new ArrayList<>(other.mBlockedClientList);
- mAllowedClientList = new ArrayList<>(other.mAllowedClientList);
- mMacRandomizationSetting = other.mMacRandomizationSetting;
- }
-
- /**
- * Builds the {@link SoftApConfiguration}.
- *
- * @return A new {@link SoftApConfiguration}, as configured by previous method calls.
- */
- @NonNull
- public SoftApConfiguration build() {
- for (MacAddress client : mAllowedClientList) {
- if (mBlockedClientList.contains(client)) {
- throw new IllegalArgumentException("A MacAddress exist in both client list");
- }
- }
- return new SoftApConfiguration(mSsid, mBssid, mPassphrase,
- mHiddenSsid, mChannels, mSecurityType, mMaxNumberOfClients,
- mAutoShutdownEnabled, mShutdownTimeoutMillis, mClientControlByUser,
- mBlockedClientList, mAllowedClientList, mMacRandomizationSetting);
- }
-
- /**
- * Specifies an SSID for the AP.
- *
- * Null SSID only support when configure a local-only hotspot.
- *
- *
If not set, defaults to null.
- *
- * @param ssid SSID of valid Unicode characters, or null to have the SSID automatically
- * chosen by the framework.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when the SSID is empty or not valid Unicode.
- */
- @NonNull
- public Builder setSsid(@Nullable String ssid) {
- if (ssid != null) {
- Preconditions.checkStringNotEmpty(ssid);
- Preconditions.checkArgument(StandardCharsets.UTF_8.newEncoder().canEncode(ssid));
- }
- mSsid = ssid;
- return this;
- }
-
- /**
- * Specifies a BSSID for the AP.
- *
- *
If not set, defaults to null.
- *
- * If multiple bands are requested via {@link #setBands(int[])} or
- * {@link #setChannels(SparseIntArray)}, HAL will derive 2 MAC addresses since framework
- * only sends down 1 MAC address.
- *
- * An example (but different implementation may perform a different mapping):
- * MAC address 1: copy value of MAC address,
- * and set byte 1 = (0xFF - BSSID[1])
- * MAC address 2: copy value of MAC address,
- * and set byte 2 = (0xFF - BSSID[2])
- *
- * Example BSSID argument: e2:38:60:c4:0e:b7
- * Derived MAC address 1: e2:c7:60:c4:0e:b7
- * Derived MAC address 2: e2:38:9f:c4:0e:b7
- *
- *
- * Use {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION} to determine
- * whether or not this feature is supported.
- *
- * @param bssid BSSID, or null to have the BSSID chosen by the framework. The caller is
- * responsible for avoiding collisions.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when the given BSSID is the all-zero
- * , multicast or broadcast MAC address.
- */
- @NonNull
- public Builder setBssid(@Nullable MacAddress bssid) {
- if (bssid != null) {
- Preconditions.checkArgument(!bssid.equals(WifiManager.ALL_ZEROS_MAC_ADDRESS));
- if (bssid.getAddressType() != MacAddress.TYPE_UNICAST) {
- throw new IllegalArgumentException("bssid doesn't support "
- + "multicast or broadcast mac address");
- }
- }
- mBssid = bssid;
- return this;
- }
-
- /**
- * Specifies that this AP should use specific security type with the given ASCII passphrase.
- *
- * @param securityType One of the following security types:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WPA2_PSK},
- * {@link #SECURITY_TYPE_WPA3_SAE_TRANSITION},
- * {@link #SECURITY_TYPE_WPA3_SAE}.
- * @param passphrase The passphrase to use for sepcific {@code securityType} configuration
- * or null with {@link #SECURITY_TYPE_OPEN}.
- *
- * @return Builder for chaining.
- * @throws IllegalArgumentException when the passphrase length is invalid and
- * {@code securityType} is not {@link #SECURITY_TYPE_OPEN}
- * or non-null passphrase and {@code securityType} is
- * {@link #SECURITY_TYPE_OPEN}.
- */
- @NonNull
- public Builder setPassphrase(@Nullable String passphrase, @SecurityType int securityType) {
- if (securityType == SECURITY_TYPE_OPEN) {
- if (passphrase != null) {
- throw new IllegalArgumentException(
- "passphrase should be null when security type is open");
- }
- } else {
- Preconditions.checkStringNotEmpty(passphrase);
- if (securityType == SECURITY_TYPE_WPA2_PSK
- || securityType == SECURITY_TYPE_WPA3_SAE_TRANSITION) {
- if (passphrase.length() < PSK_MIN_LEN || passphrase.length() > PSK_MAX_LEN) {
- throw new IllegalArgumentException(
- "Password size must be at least " + PSK_MIN_LEN
- + " and no more than " + PSK_MAX_LEN
- + " for WPA2_PSK and WPA3_SAE_TRANSITION Mode");
- }
- }
- }
- mSecurityType = securityType;
- mPassphrase = passphrase;
- return this;
- }
-
- /**
- * Specifies whether the AP is hidden (doesn't broadcast its SSID) or
- * not (broadcasts its SSID).
- *
- *
If not set, defaults to false (i.e not a hidden network).
- *
- * @param hiddenSsid true for a hidden SSID, false otherwise.
- * @return Builder for chaining.
- */
- @NonNull
- public Builder setHiddenSsid(boolean hiddenSsid) {
- mHiddenSsid = hiddenSsid;
- return this;
- }
-
- /**
- * Specifies the band for the AP.
- *
- *
If not set, defaults to {@link #BAND_2GHZ}.
- *
- * @param band One or combination of the following band type:
- * {@link #BAND_2GHZ}, {@link #BAND_5GHZ}, {@link #BAND_6GHZ}.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when an invalid band type is provided.
- */
- @NonNull
- public Builder setBand(@BandType int band) {
- if (!isBandValid(band)) {
- throw new IllegalArgumentException("Invalid band type: " + band);
- }
- mChannels = new SparseIntArray(1);
- mChannels.put(band, 0);
- return this;
- }
-
- /**
- * Specifies the bands for the APs.
- * If more than 1 band is set, this will bring up concurrent APs.
- * on the requested bands (if possible).
- *
- *
- * Use {@link WifiManager#isBridgedApConcurrencySupported()} to determine
- * whether or not concurrent APs are supported.
- *
- * @param bands Array of the {@link #BandType}.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when more than 2 bands are set or an invalid band type
- * is provided.
- */
- @NonNull
- public Builder setBands(@NonNull int[] bands) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- if (bands.length == 0 || bands.length > 2) {
- throw new IllegalArgumentException("Unsupported number of bands("
- + bands.length + ") configured");
- }
- SparseIntArray channels = new SparseIntArray(bands.length);
- for (int val : bands) {
- if (!isBandValid(val)) {
- throw new IllegalArgumentException("Invalid band type: " + val);
- }
- channels.put(val, 0);
- }
- mChannels = channels;
- return this;
- }
-
-
- /**
- * Specifies the channel and associated band for the AP.
- *
- * The channel which AP resides on. Valid channels are country dependent.
- * The {@link SoftApCapability#getSupportedChannelList(int)} can be used to obtain
- * valid channels.
- *
- *
- * If not set, the default for the channel is the special value 0 which has the
- * framework auto-select a valid channel from the band configured with
- * {@link #setBand(int)}.
- *
- * The channel auto selection will be offloaded to driver when
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_ACS_OFFLOAD}
- * return true. The driver will auto select the best channel (e.g. best performance)
- * based on environment interference. Check {@link SoftApCapability} for more detail.
- *
- * The API contains (band, channel) input since the 6GHz band uses the same channel
- * numbering scheme as is used in the 2.4GHz and 5GHz band. Therefore, both are needed to
- * uniquely identify individual channels.
- *
- *
- * @param channel operating channel of the AP.
- * @param band containing this channel.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when the invalid channel or band type is configured.
- */
- @NonNull
- public Builder setChannel(int channel, @BandType int band) {
- if (!isChannelBandPairValid(channel, band)) {
- throw new IllegalArgumentException("Invalid channel(" + channel
- + ") & band (" + band + ") configured");
- }
- mChannels = new SparseIntArray(1);
- mChannels.put(band, channel);
- return this;
- }
-
- /**
- * Specifies the channels and associated bands for the APs.
- *
- * When more than 1 channel is set, this will bring up concurrent APs on the requested
- * channels and bands (if possible).
- *
- * Valid channels are country dependent.
- * The {@link SoftApCapability#getSupportedChannelList(int)} can be used to obtain
- * valid channels in each band.
- *
- * Use {@link WifiManager#isBridgedApConcurrencySupported()} to determine
- * whether or not concurrent APs are supported.
- *
- *
- * If not set, the default for the channel is the special value 0 which has the framework
- * auto-select a valid channel from the band configured with {@link #setBands(int[])}.
- *
- * The channel auto selection will be offloaded to driver when
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_ACS_OFFLOAD}
- * returns true. The driver will auto select the best channel (e.g. best performance)
- * based on environment interference. Check {@link SoftApCapability} for more detail.
- *
- * The API contains (band, channel) input since the 6GHz band uses the same channel
- * numbering scheme as is used in the 2.4GHz and 5GHz band. Therefore, both are needed to
- * uniquely identify individual channels.
- *
- *
- * @param channels SparseIntArray (key: {@code #BandType} , value: channel) consists of
- * {@code BAND_} and corresponding channel.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when more than 2 channels are set or the invalid
- * channel or band type is configured.
- */
- @NonNull
- public Builder setChannels(@NonNull SparseIntArray channels) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- if (channels.size() == 0 || channels.size() > 2) {
- throw new IllegalArgumentException("Unsupported number of channels("
- + channels.size() + ") configured");
- }
- for (int i = 0; i < channels.size(); i++) {
- int channel = channels.valueAt(i);
- int band = channels.keyAt(i);
- if (channel == 0) {
- if (!isBandValid(band)) {
- throw new IllegalArgumentException("Invalid band type: " + band);
- }
- } else {
- if (!isChannelBandPairValid(channel, band)) {
- throw new IllegalArgumentException("Invalid channel(" + channel
- + ") & band (" + band + ") configured");
- }
- }
- }
- mChannels = channels.clone();
- return this;
- }
-
-
- /**
- * Specifies the maximum number of clients that can associate to the AP.
- *
- * The maximum number of clients (STAs) which can associate to the AP.
- * The AP will reject association from any clients above this number.
- * Specify a value of 0 to have the framework automatically use the maximum number
- * which the device can support (based on hardware and carrier constraints).
- *
- * Use {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#getMaxSupportedClients} to get the maximum number of clients
- * which the device supports (based on hardware and carrier constraints).
- *
- *
- *
If not set, defaults to 0.
- *
- * This method requires HAL support. If the method is used to set a
- * non-zero {@code maxNumberOfClients} value then
- * {@link WifiManager#startTetheredHotspot} will report error code
- * {@link WifiManager#SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}.
- *
- *
- * Use {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT} to determine whether
- * or not this feature is supported.
- *
- * @param maxNumberOfClients maximum client number of the AP.
- * @return Builder for chaining.
- */
- @NonNull
- public Builder setMaxNumberOfClients(@IntRange(from = 0) int maxNumberOfClients) {
- if (maxNumberOfClients < 0) {
- throw new IllegalArgumentException("maxNumberOfClients should be not negative");
- }
- mMaxNumberOfClients = maxNumberOfClients;
- return this;
- }
-
- /**
- * Specifies whether auto shutdown is enabled or not.
- * The Soft AP will shut down when there are no devices connected to it for
- * the timeout duration.
- *
- *
- *
If not set, defaults to true
- *
- * @param enable true to enable, false to disable.
- * @return Builder for chaining.
- *
- * @see #setShutdownTimeoutMillis(long)
- */
- @NonNull
- public Builder setAutoShutdownEnabled(boolean enable) {
- mAutoShutdownEnabled = enable;
- return this;
- }
-
- /**
- * Specifies the shutdown timeout in milliseconds.
- * The Soft AP will shut down when there are no devices connected to it for
- * the timeout duration.
- *
- * Specify a value of 0 to have the framework automatically use default timeout
- * setting which defined in {@link R.integer.config_wifi_framework_soft_ap_timeout_delay}
- *
- *
- *
If not set, defaults to 0
- * The shut down timeout will apply when {@link #setAutoShutdownEnabled(boolean)} is
- * set to true
- *
- * @param timeoutMillis milliseconds of the timeout delay.
- * @return Builder for chaining.
- *
- * @see #setAutoShutdownEnabled(boolean)
- */
- @NonNull
- public Builder setShutdownTimeoutMillis(@IntRange(from = 0) long timeoutMillis) {
- if (timeoutMillis < 0) {
- throw new IllegalArgumentException("Invalid timeout value");
- }
- mShutdownTimeoutMillis = timeoutMillis;
- return this;
- }
-
- /**
- * Configure the Soft AP to require manual user control of client association.
- * If disabled (the default) then any client which isn't in the blocked list
- * {@link #getBlockedClientList()} can associate to this Soft AP using the
- * correct credentials until the Soft AP capacity is reached (capacity is hardware, carrier,
- * or user limited - using {@link #setMaxNumberOfClients(int)}).
- *
- * If manual user control is enabled then clients will be accepted, rejected, or require
- * a user approval based on the configuration provided by
- * {@link #setBlockedClientList(List)} and {@link #setAllowedClientList(List)}.
- *
- *
- * This method requires HAL support. HAL support can be determined using
- * {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT}
- *
- *
- * If the method is called on a device without HAL support then starting the soft AP
- * using {@link WifiManager#startTetheredHotspot(SoftApConfiguration)} will fail with
- * {@link WifiManager#SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}.
- *
- *
- *
If not set, defaults to false (i.e The authoriztion is not required).
- *
- * @param enabled true for enabling the control by user, false otherwise.
- * @return Builder for chaining.
- */
- @NonNull
- public Builder setClientControlByUserEnabled(boolean enabled) {
- mClientControlByUser = enabled;
- return this;
- }
-
-
- /**
- * This method together with {@link setClientControlByUserEnabled(boolean)} control client
- * connections to the AP. If client control by user is disabled using the above method then
- * this API has no effect and clients are allowed to associate to the AP (within limit of
- * max number of clients).
- *
- * If client control by user is enabled then this API configures the list of clients
- * which are explicitly allowed. These are auto-accepted.
- *
- * All other clients which attempt to associate, whose MAC addresses are on neither list,
- * are:
- *
- * - Rejected
- * - A callback {@link WifiManager.SoftApCallback#onBlockedClientConnecting(WifiClient)}
- * is issued (which allows the user to add them to the allowed client list if desired).
-
- *
- *
- * @param allowedClientList list of clients which are allowed to associate to the AP
- * without user pre-approval.
- * @return Builder for chaining.
- */
- @NonNull
- public Builder setAllowedClientList(@NonNull List allowedClientList) {
- mAllowedClientList = new ArrayList<>(allowedClientList);
- return this;
- }
-
- /**
- * This API configures the list of clients which are blocked and cannot associate
- * to the Soft AP.
- *
- *
- * This method requires HAL support. HAL support can be determined using
- * {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT}
- *
- *
- * If the method is called on a device without HAL support then starting the soft AP
- * using {@link WifiManager#startTetheredHotspot(SoftApConfiguration)} will fail with
- * {@link WifiManager#SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}.
- *
- * @param blockedClientList list of clients which are not allowed to associate to the AP.
- * @return Builder for chaining.
- */
- @NonNull
- public Builder setBlockedClientList(@NonNull List blockedClientList) {
- mBlockedClientList = new ArrayList<>(blockedClientList);
- return this;
- }
-
- /**
- * Specifies the level of MAC randomization for the AP BSSID.
- * The Soft AP BSSID will be randomized only if the BSSID isn't set
- * {@link #setBssid(MacAddress)} and this method is either uncalled
- * or called with {@link #RANDOMIZATION_PERSISTENT}.
- *
- *
- *
If not set, defaults to {@link #RANDOMIZATION_PERSISTENT}
- *
- *
- * Requires HAL support when set to {@link #RANDOMIZATION_PERSISTENT}.
- * Use {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION} to determine
- * whether or not this feature is supported.
- *
- * @param macRandomizationSetting One of the following setting:
- * {@link #RANDOMIZATION_NONE} or {@link #RANDOMIZATION_PERSISTENT}.
- * @return Builder for chaining.
- *
- * @see #setBssid(MacAddress)
- */
- @NonNull
- public Builder setMacRandomizationSetting(
- @MacRandomizationSetting int macRandomizationSetting) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mMacRandomizationSetting = macRandomizationSetting;
- return this;
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/SoftApInfo.java b/wifi/java/android/net/wifi/SoftApInfo.java
deleted file mode 100644
index e42e7868e9449..0000000000000
--- a/wifi/java/android/net/wifi/SoftApInfo.java
+++ /dev/null
@@ -1,328 +0,0 @@
-/*
- * 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 android.net.wifi;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import com.android.internal.util.Preconditions;
-import com.android.modules.utils.build.SdkLevel;
-
-import java.util.Objects;
-
-/**
- * A class representing information about SoftAp.
- * {@see WifiManager}
- *
- * @hide
- */
-@SystemApi
-public final class SoftApInfo implements Parcelable {
-
- /**
- * AP Channel bandwidth is invalid.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_INVALID = 0;
-
- /**
- * AP Channel bandwidth is 20 MHZ but no HT.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_20MHZ_NOHT = 1;
-
- /**
- * AP Channel bandwidth is 20 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_20MHZ = 2;
-
- /**
- * AP Channel bandwidth is 40 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_40MHZ = 3;
-
- /**
- * AP Channel bandwidth is 80 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_80MHZ = 4;
-
- /**
- * AP Channel bandwidth is 160 MHZ, but 80MHZ + 80MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_80MHZ_PLUS_MHZ = 5;
-
- /**
- * AP Channel bandwidth is 160 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_160MHZ = 6;
-
- /**
- * AP Channel bandwidth is 2160 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_2160MHZ = 7;
-
- /**
- * AP Channel bandwidth is 4320 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_4320MHZ = 8;
-
- /**
- * AP Channel bandwidth is 6480 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_6480MHZ = 9;
-
- /**
- * AP Channel bandwidth is 8640 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_8640MHZ = 10;
-
- /** The frequency which AP resides on. */
- private int mFrequency = 0;
-
- @WifiAnnotations.Bandwidth
- private int mBandwidth = CHANNEL_WIDTH_INVALID;
-
- /** The MAC Address which AP resides on. */
- @Nullable
- private MacAddress mBssid;
-
- /** The identifier of the AP instance which AP resides on with current info. */
- @Nullable
- private String mApInstanceIdentifier;
-
- /**
- * The operational mode of the AP.
- */
- private @WifiAnnotations.WifiStandard int mWifiStandard = ScanResult.WIFI_STANDARD_UNKNOWN;
-
- /**
- * Get the frequency which AP resides on.
- */
- public int getFrequency() {
- return mFrequency;
- }
-
- /**
- * Set the frequency which AP resides on.
- * @hide
- */
- public void setFrequency(int freq) {
- mFrequency = freq;
- }
-
- /**
- * Get AP Channel bandwidth.
- *
- * @return One of {@link #CHANNEL_WIDTH_20MHZ}, {@link #CHANNEL_WIDTH_40MHZ},
- * {@link #CHANNEL_WIDTH_80MHZ}, {@link #CHANNEL_WIDTH_160MHZ},
- * {@link #CHANNEL_WIDTH_80MHZ_PLUS_MHZ}, {@link #CHANNEL_WIDTH_2160MHZ},
- * {@link #CHANNEL_WIDTH_4320MHZ}, {@link #CHANNEL_WIDTH_6480MHZ},
- * {@link #CHANNEL_WIDTH_8640MHZ}, or {@link #CHANNEL_WIDTH_INVALID}.
- */
- @WifiAnnotations.Bandwidth
- public int getBandwidth() {
- return mBandwidth;
- }
-
- /**
- * Set AP Channel bandwidth.
- * @hide
- */
- public void setBandwidth(@WifiAnnotations.Bandwidth int bandwidth) {
- mBandwidth = bandwidth;
- }
-
- /**
- * Get the MAC address (BSSID) of the AP. Null when AP disabled.
- */
- @Nullable
- public MacAddress getBssid() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mBssid;
- }
-
- /**
- * Set the MAC address which AP resides on.
- *
- *
If not set, defaults to null.
- * @param bssid BSSID, The caller is responsible for avoiding collisions.
- * @throws IllegalArgumentException when the given BSSID is the all-zero or broadcast MAC
- * address.
- *
- * @hide
- */
- public void setBssid(@Nullable MacAddress bssid) {
- if (bssid != null) {
- Preconditions.checkArgument(!bssid.equals(WifiManager.ALL_ZEROS_MAC_ADDRESS));
- Preconditions.checkArgument(!bssid.equals(MacAddress.BROADCAST_ADDRESS));
- }
- mBssid = bssid;
- }
-
- /**
- * Set the operational mode of the AP.
- *
- * @param wifiStandard values from {@link ScanResult}'s {@code WIFI_STANDARD_}
- * @hide
- */
- public void setWifiStandard(@WifiAnnotations.WifiStandard int wifiStandard) {
- mWifiStandard = wifiStandard;
- }
-
- /**
- * Get the operational mode of the AP.
- * @return valid values from {@link ScanResult}'s {@code WIFI_STANDARD_}
- */
- public @WifiAnnotations.WifiStandard int getWifiStandard() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mWifiStandard;
- }
-
- /**
- * Set the AP instance identifier.
- * @hide
- */
- public void setApInstanceIdentifier(@NonNull String apInstanceIdentifier) {
- mApInstanceIdentifier = apInstanceIdentifier;
- }
-
- /**
- * Get the AP instance identifier.
- *
- * The AP instance identifier is a unique identity which can be used to
- * associate the {@link SoftApInfo} to a specific {@link WifiClient}
- * - see {@link WifiClient#getApInstanceIdentifier()}
- *
- * @hide
- */
- @Nullable
- public String getApInstanceIdentifier() {
- return mApInstanceIdentifier;
- }
-
- /**
- * @hide
- */
- public SoftApInfo(@Nullable SoftApInfo source) {
- if (source != null) {
- mFrequency = source.mFrequency;
- mBandwidth = source.mBandwidth;
- mBssid = source.mBssid;
- mWifiStandard = source.mWifiStandard;
- mApInstanceIdentifier = source.mApInstanceIdentifier;
- }
- }
-
- /**
- * @hide
- */
- public SoftApInfo() {
- }
-
- @Override
- /** Implement the Parcelable interface. */
- public int describeContents() {
- return 0;
- }
-
- @Override
- /** Implement the Parcelable interface */
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeInt(mFrequency);
- dest.writeInt(mBandwidth);
- dest.writeParcelable(mBssid, flags);
- dest.writeInt(mWifiStandard);
- dest.writeString(mApInstanceIdentifier);
- }
-
- @NonNull
- /** Implement the Parcelable interface */
- public static final Creator CREATOR = new Creator() {
- public SoftApInfo createFromParcel(Parcel in) {
- SoftApInfo info = new SoftApInfo();
- info.mFrequency = in.readInt();
- info.mBandwidth = in.readInt();
- info.mBssid = in.readParcelable(MacAddress.class.getClassLoader());
- info.mWifiStandard = in.readInt();
- info.mApInstanceIdentifier = in.readString();
- return info;
- }
-
- public SoftApInfo[] newArray(int size) {
- return new SoftApInfo[size];
- }
- };
-
- @NonNull
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- sbuf.append("SoftApInfo{");
- sbuf.append("bandwidth= ").append(mBandwidth);
- sbuf.append(", frequency= ").append(mFrequency);
- if (mBssid != null) sbuf.append(",bssid=").append(mBssid.toString());
- sbuf.append(", wifiStandard= ").append(mWifiStandard);
- sbuf.append(", mApInstanceIdentifier= ").append(mApInstanceIdentifier);
- sbuf.append("}");
- return sbuf.toString();
- }
-
- @Override
- public boolean equals(@NonNull Object o) {
- if (this == o) return true;
- if (!(o instanceof SoftApInfo)) return false;
- SoftApInfo softApInfo = (SoftApInfo) o;
- return mFrequency == softApInfo.mFrequency
- && mBandwidth == softApInfo.mBandwidth
- && Objects.equals(mBssid, softApInfo.mBssid)
- && mWifiStandard == softApInfo.mWifiStandard
- && Objects.equals(mApInstanceIdentifier, softApInfo.mApInstanceIdentifier);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mFrequency, mBandwidth, mBssid, mWifiStandard, mApInstanceIdentifier);
- }
-}
diff --git a/wifi/java/android/net/wifi/SupplicantState.java b/wifi/java/android/net/wifi/SupplicantState.java
deleted file mode 100644
index de7e2b556be35..0000000000000
--- a/wifi/java/android/net/wifi/SupplicantState.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * Copyright (C) 2008 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 android.net.wifi;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * From defs.h in wpa_supplicant.
- *
- * These enumeration values are used to indicate the current wpa_supplicant
- * state. This is more fine-grained than most users will be interested in.
- * In general, it is better to use
- * {@link android.net.NetworkInfo.State NetworkInfo.State}.
- *
- * Note, the order of these enum constants must match the numerical values of the
- * state constants in defs.h in wpa_supplicant.
- */
-public enum SupplicantState implements Parcelable {
- /**
- * This state indicates that client is not associated, but is likely to
- * start looking for an access point. This state is entered when a
- * connection is lost.
- */
- DISCONNECTED,
-
- /**
- * Interface is disabled
- *
- * This state is entered if the network interface is disabled.
- * wpa_supplicant refuses any new operations that would
- * use the radio until the interface has been enabled.
- */
- INTERFACE_DISABLED,
-
- /**
- * Inactive state (wpa_supplicant disabled).
- *
- * This state is entered if there are no enabled networks in the
- * configuration. wpa_supplicant is not trying to associate with a new
- * network and external interaction (e.g., ctrl_iface call to add or
- * enable a network) is needed to start association.
- */
- INACTIVE,
-
- /**
- * Scanning for a network.
- *
- * This state is entered when wpa_supplicant starts scanning for a
- * network.
- */
- SCANNING,
-
- /**
- * Trying to authenticate with a BSS/SSID
- *
- * This state is entered when wpa_supplicant has found a suitable BSS
- * to authenticate with and the driver is configured to try to
- * authenticate with this BSS.
- */
- AUTHENTICATING,
-
- /**
- * Trying to associate with a BSS/SSID.
- *
- * This state is entered when wpa_supplicant has found a suitable BSS
- * to associate with and the driver is configured to try to associate
- * with this BSS in ap_scan=1 mode. When using ap_scan=2 mode, this
- * state is entered when the driver is configured to try to associate
- * with a network using the configured SSID and security policy.
- */
- ASSOCIATING,
-
- /**
- * Association completed.
- *
- * This state is entered when the driver reports that association has
- * been successfully completed with an AP. If IEEE 802.1X is used
- * (with or without WPA/WPA2), wpa_supplicant remains in this state
- * until the IEEE 802.1X/EAPOL authentication has been completed.
- */
- ASSOCIATED,
-
- /**
- * WPA 4-Way Key Handshake in progress.
- *
- * This state is entered when WPA/WPA2 4-Way Handshake is started. In
- * case of WPA-PSK, this happens when receiving the first EAPOL-Key
- * frame after association. In case of WPA-EAP, this state is entered
- * when the IEEE 802.1X/EAPOL authentication has been completed.
- */
- FOUR_WAY_HANDSHAKE,
-
- /**
- * WPA Group Key Handshake in progress.
- *
- * This state is entered when 4-Way Key Handshake has been completed
- * (i.e., when the supplicant sends out message 4/4) and when Group
- * Key rekeying is started by the AP (i.e., when supplicant receives
- * message 1/2).
- */
- GROUP_HANDSHAKE,
-
- /**
- * All authentication completed.
- *
- * This state is entered when the full authentication process is
- * completed. In case of WPA2, this happens when the 4-Way Handshake is
- * successfully completed. With WPA, this state is entered after the
- * Group Key Handshake; with IEEE 802.1X (non-WPA) connection is
- * completed after dynamic keys are received (or if not used, after
- * the EAP authentication has been completed). With static WEP keys and
- * plaintext connections, this state is entered when an association
- * has been completed.
- *
- * This state indicates that the supplicant has completed its
- * processing for the association phase and that data connection is
- * fully configured. Note, however, that there may not be any IP
- * address associated with the connection yet. Typically, a DHCP
- * request needs to be sent at this point to obtain an address.
- */
- COMPLETED,
-
- /**
- * An Android-added state that is reported when a client issues an
- * explicit DISCONNECT command. In such a case, the supplicant is
- * not only dissociated from the current access point (as for the
- * DISCONNECTED state above), but it also does not attempt to connect
- * to any access point until a RECONNECT or REASSOCIATE command
- * is issued by the client.
- */
- DORMANT,
-
- /**
- * No connection to wpa_supplicant.
- *
- * This is an additional pseudo-state to handle the case where
- * wpa_supplicant is not running and/or we have not been able
- * to establish a connection to it.
- */
- UNINITIALIZED,
-
- /**
- * A pseudo-state that should normally never be seen.
- */
- INVALID;
-
- /**
- * Returns {@code true} if the supplicant state is valid and {@code false}
- * otherwise.
- * @param state The supplicant state
- * @return {@code true} if the supplicant state is valid and {@code false}
- * otherwise.
- */
- public static boolean isValidState(SupplicantState state) {
- return state != UNINITIALIZED && state != INVALID;
- }
-
-
- /** Supplicant associating or authenticating is considered a handshake state {@hide} */
- public static boolean isHandshakeState(SupplicantState state) {
- switch(state) {
- case AUTHENTICATING:
- case ASSOCIATING:
- case ASSOCIATED:
- case FOUR_WAY_HANDSHAKE:
- case GROUP_HANDSHAKE:
- return true;
- case COMPLETED:
- case DISCONNECTED:
- case INTERFACE_DISABLED:
- case INACTIVE:
- case SCANNING:
- case DORMANT:
- case UNINITIALIZED:
- case INVALID:
- return false;
- default:
- throw new IllegalArgumentException("Unknown supplicant state");
- }
- }
-
- /** @hide */
- public static boolean isConnecting(SupplicantState state) {
- switch(state) {
- case AUTHENTICATING:
- case ASSOCIATING:
- case ASSOCIATED:
- case FOUR_WAY_HANDSHAKE:
- case GROUP_HANDSHAKE:
- case COMPLETED:
- return true;
- case DISCONNECTED:
- case INTERFACE_DISABLED:
- case INACTIVE:
- case SCANNING:
- case DORMANT:
- case UNINITIALIZED:
- case INVALID:
- return false;
- default:
- throw new IllegalArgumentException("Unknown supplicant state");
- }
- }
-
- /** @hide */
- public static boolean isDriverActive(SupplicantState state) {
- switch(state) {
- case DISCONNECTED:
- case DORMANT:
- case INACTIVE:
- case AUTHENTICATING:
- case ASSOCIATING:
- case ASSOCIATED:
- case SCANNING:
- case FOUR_WAY_HANDSHAKE:
- case GROUP_HANDSHAKE:
- case COMPLETED:
- return true;
- case INTERFACE_DISABLED:
- case UNINITIALIZED:
- case INVALID:
- return false;
- default:
- throw new IllegalArgumentException("Unknown supplicant state");
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(name());
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @android.annotation.NonNull Creator CREATOR =
- new Creator() {
- public SupplicantState createFromParcel(Parcel in) {
- return SupplicantState.valueOf(in.readString());
- }
-
- public SupplicantState[] newArray(int size) {
- return new SupplicantState[size];
- }
- };
-
-}
diff --git a/wifi/java/android/net/wifi/SynchronousExecutor.java b/wifi/java/android/net/wifi/SynchronousExecutor.java
deleted file mode 100644
index 9926b1b5f7dce..0000000000000
--- a/wifi/java/android/net/wifi/SynchronousExecutor.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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 android.net.wifi;
-
-import java.util.concurrent.Executor;
-
-/**
- * An executor implementation that runs synchronously on the current thread.
- * @hide
- */
-public class SynchronousExecutor implements Executor {
- @Override
- public void execute(Runnable r) {
- r.run();
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiAnnotations.java b/wifi/java/android/net/wifi/WifiAnnotations.java
deleted file mode 100644
index 807b40b5722c7..0000000000000
--- a/wifi/java/android/net/wifi/WifiAnnotations.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * 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 android.net.wifi;
-
-import android.annotation.IntDef;
-import android.annotation.StringDef;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-/**
- * Wifi annotations meant to be statically linked into client modules, since they cannot be
- * exposed as @SystemApi.
- *
- * e.g. {@link IntDef}, {@link StringDef}
- *
- * @hide
- */
-public final class WifiAnnotations {
- private WifiAnnotations() {}
-
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"SCAN_TYPE_"}, value = {
- WifiScanner.SCAN_TYPE_LOW_LATENCY,
- WifiScanner.SCAN_TYPE_LOW_POWER,
- WifiScanner.SCAN_TYPE_HIGH_ACCURACY})
- public @interface ScanType {}
-
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"WIFI_BAND_"}, value = {
- WifiScanner.WIFI_BAND_UNSPECIFIED,
- WifiScanner.WIFI_BAND_24_GHZ,
- WifiScanner.WIFI_BAND_5_GHZ,
- WifiScanner.WIFI_BAND_5_GHZ_DFS_ONLY,
- WifiScanner.WIFI_BAND_6_GHZ})
- public @interface WifiBandBasic {}
-
- @IntDef(prefix = { "CHANNEL_WIDTH_" }, value = {
- SoftApInfo.CHANNEL_WIDTH_INVALID,
- SoftApInfo.CHANNEL_WIDTH_20MHZ_NOHT,
- SoftApInfo.CHANNEL_WIDTH_20MHZ,
- SoftApInfo.CHANNEL_WIDTH_40MHZ,
- SoftApInfo.CHANNEL_WIDTH_80MHZ,
- SoftApInfo.CHANNEL_WIDTH_80MHZ_PLUS_MHZ,
- SoftApInfo.CHANNEL_WIDTH_160MHZ,
- SoftApInfo.CHANNEL_WIDTH_2160MHZ,
- SoftApInfo.CHANNEL_WIDTH_4320MHZ,
- SoftApInfo.CHANNEL_WIDTH_6480MHZ,
- SoftApInfo.CHANNEL_WIDTH_8640MHZ,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface Bandwidth {}
-
- @IntDef(prefix = { "CHANNEL_WIDTH_" }, value = {
- ScanResult.CHANNEL_WIDTH_20MHZ,
- ScanResult.CHANNEL_WIDTH_40MHZ,
- ScanResult.CHANNEL_WIDTH_80MHZ,
- ScanResult.CHANNEL_WIDTH_160MHZ,
- ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface ChannelWidth{}
-
- @IntDef(prefix = { "WIFI_STANDARD_" }, value = {
- ScanResult.WIFI_STANDARD_UNKNOWN,
- ScanResult.WIFI_STANDARD_LEGACY,
- ScanResult.WIFI_STANDARD_11N,
- ScanResult.WIFI_STANDARD_11AC,
- ScanResult.WIFI_STANDARD_11AX,
- ScanResult.WIFI_STANDARD_11AD,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface WifiStandard{}
-
- @IntDef(prefix = { "PROTOCOL_" }, value = {
- ScanResult.PROTOCOL_NONE,
- ScanResult.PROTOCOL_WPA,
- ScanResult.PROTOCOL_RSN,
- ScanResult.PROTOCOL_OSEN,
- ScanResult.PROTOCOL_WAPI
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface Protocol {}
-
- @IntDef(prefix = { "KEY_MGMT_" }, value = {
- ScanResult.KEY_MGMT_NONE,
- ScanResult.KEY_MGMT_PSK,
- ScanResult.KEY_MGMT_EAP,
- ScanResult.KEY_MGMT_FT_PSK,
- ScanResult.KEY_MGMT_FT_EAP,
- ScanResult.KEY_MGMT_PSK_SHA256,
- ScanResult.KEY_MGMT_EAP_SHA256,
- ScanResult.KEY_MGMT_OSEN,
- ScanResult.KEY_MGMT_SAE,
- ScanResult.KEY_MGMT_OWE,
- ScanResult.KEY_MGMT_EAP_SUITE_B_192,
- ScanResult.KEY_MGMT_FT_SAE,
- ScanResult.KEY_MGMT_OWE_TRANSITION,
- ScanResult.KEY_MGMT_WAPI_PSK,
- ScanResult.KEY_MGMT_WAPI_CERT
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface KeyMgmt {}
-
- @IntDef(prefix = { "CIPHER_" }, value = {
- ScanResult.CIPHER_NONE,
- ScanResult.CIPHER_NO_GROUP_ADDRESSED,
- ScanResult.CIPHER_TKIP,
- ScanResult.CIPHER_CCMP,
- ScanResult.CIPHER_GCMP_256,
- ScanResult.CIPHER_SMS4
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface Cipher {}
-}
diff --git a/wifi/java/android/net/wifi/WifiClient.java b/wifi/java/android/net/wifi/WifiClient.java
deleted file mode 100644
index 85e2b3312b293..0000000000000
--- a/wifi/java/android/net/wifi/WifiClient.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * 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 android.net.wifi;
-
-import android.annotation.NonNull;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Objects;
-
-/** @hide */
-@SystemApi
-public final class WifiClient implements Parcelable {
-
- private final MacAddress mMacAddress;
-
- /** The identifier of the AP instance which the client connected. */
- private final String mApInstanceIdentifier;
-
- /**
- * The mac address of this client.
- */
- @NonNull
- public MacAddress getMacAddress() {
- return mMacAddress;
- }
-
- /**
- * Get AP instance identifier.
- *
- * The AP instance identifier is a unique identity which can be used to
- * associate the {@link SoftApInfo} to a specific {@link WifiClient}
- * - see {@link SoftApInfo#getApInstanceIdentifier()}
- * @hide
- */
- @NonNull
- public String getApInstanceIdentifier() {
- return mApInstanceIdentifier;
- }
-
- private WifiClient(Parcel in) {
- mMacAddress = in.readParcelable(null);
- mApInstanceIdentifier = in.readString();
- }
-
- /** @hide */
- public WifiClient(@NonNull MacAddress macAddress, @NonNull String apInstanceIdentifier) {
- Objects.requireNonNull(macAddress, "mMacAddress must not be null.");
-
- this.mMacAddress = macAddress;
- this.mApInstanceIdentifier = apInstanceIdentifier;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeParcelable(mMacAddress, flags);
- dest.writeString(mApInstanceIdentifier);
- }
-
- @NonNull
- public static final Creator CREATOR = new Creator() {
- public WifiClient createFromParcel(Parcel in) {
- return new WifiClient(in);
- }
-
- public WifiClient[] newArray(int size) {
- return new WifiClient[size];
- }
- };
-
- @NonNull
- @Override
- public String toString() {
- return "WifiClient{"
- + "mMacAddress=" + mMacAddress
- + "mApInstanceIdentifier=" + mApInstanceIdentifier
- + '}';
- }
-
- @Override
- public boolean equals(@NonNull Object o) {
- if (this == o) return true;
- if (!(o instanceof WifiClient)) return false;
- WifiClient client = (WifiClient) o;
- return Objects.equals(mMacAddress, client.mMacAddress)
- && mApInstanceIdentifier.equals(client.mApInstanceIdentifier);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mMacAddress, mApInstanceIdentifier);
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiConfiguration.java b/wifi/java/android/net/wifi/WifiConfiguration.java
deleted file mode 100644
index 6c0b2dfa7899a..0000000000000
--- a/wifi/java/android/net/wifi/WifiConfiguration.java
+++ /dev/null
@@ -1,3659 +0,0 @@
-/*
- * Copyright (C) 2008 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 android.net.wifi;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SuppressLint;
-import android.annotation.SystemApi;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.content.pm.PackageManager;
-import android.net.IpConfiguration;
-import android.net.IpConfiguration.ProxySettings;
-import android.net.MacAddress;
-import android.net.NetworkSpecifier;
-import android.net.ProxyInfo;
-import android.net.StaticIpConfiguration;
-import android.net.Uri;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.SystemClock;
-import android.os.UserHandle;
-import android.telephony.SubscriptionInfo;
-import android.telephony.SubscriptionManager;
-import android.telephony.TelephonyManager;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.SparseArray;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.net.module.util.MacAddressUtils;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.BitSet;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-
-/**
- * A class representing a configured Wi-Fi network, including the
- * security configuration.
- *
- * @deprecated Use {@link WifiNetworkSpecifier.Builder} to create {@link NetworkSpecifier} and
- * {@link WifiNetworkSuggestion.Builder} to create {@link WifiNetworkSuggestion}. This will become a
- * system use only object in the future.
- */
-@Deprecated
-public class WifiConfiguration implements Parcelable {
- private static final String TAG = "WifiConfiguration";
- /**
- * Current Version of the Backup Serializer.
- */
- private static final int BACKUP_VERSION = 3;
- /** {@hide} */
- public static final String ssidVarName = "ssid";
- /** {@hide} */
- public static final String bssidVarName = "bssid";
- /** {@hide} */
- public static final String pskVarName = "psk";
- /** {@hide} */
- @Deprecated
- @UnsupportedAppUsage
- public static final String[] wepKeyVarNames = { "wep_key0", "wep_key1", "wep_key2", "wep_key3" };
- /** {@hide} */
- @Deprecated
- public static final String wepTxKeyIdxVarName = "wep_tx_keyidx";
- /** {@hide} */
- public static final String priorityVarName = "priority";
- /** {@hide} */
- public static final String hiddenSSIDVarName = "scan_ssid";
- /** {@hide} */
- public static final String pmfVarName = "ieee80211w";
- /** {@hide} */
- public static final String updateIdentiferVarName = "update_identifier";
- /**
- * The network ID for an invalid network.
- *
- * @hide
- */
- @SystemApi
- public static final int INVALID_NETWORK_ID = -1;
- /** {@hide} */
- public static final int LOCAL_ONLY_NETWORK_ID = -2;
-
- /** {@hide} */
- private String mPasspointManagementObjectTree;
- /** {@hide} */
- private static final int MAXIMUM_RANDOM_MAC_GENERATION_RETRY = 3;
-
- /**
- * Recognized key management schemes.
- */
- public static class KeyMgmt {
- private KeyMgmt() { }
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(value = {
- NONE,
- WPA_PSK,
- WPA_EAP,
- IEEE8021X,
- WPA2_PSK,
- OSEN,
- FT_PSK,
- FT_EAP,
- SAE,
- OWE,
- SUITE_B_192,
- WPA_PSK_SHA256,
- WPA_EAP_SHA256,
- WAPI_PSK,
- WAPI_CERT,
- FILS_SHA256,
- FILS_SHA384})
- public @interface KeyMgmtScheme {}
-
- /** WPA is not used; plaintext or static WEP could be used. */
- public static final int NONE = 0;
- /** WPA pre-shared key (requires {@code preSharedKey} to be specified). */
- public static final int WPA_PSK = 1;
- /** WPA using EAP authentication. Generally used with an external authentication server. */
- public static final int WPA_EAP = 2;
- /**
- * IEEE 802.1X using EAP authentication and (optionally) dynamically
- * generated WEP keys.
- */
- public static final int IEEE8021X = 3;
-
- /**
- * WPA2 pre-shared key for use with soft access point
- * (requires {@code preSharedKey} to be specified).
- * @hide
- */
- @SystemApi
- public static final int WPA2_PSK = 4;
- /**
- * Hotspot 2.0 r2 OSEN:
- * @hide
- */
- public static final int OSEN = 5;
-
- /**
- * IEEE 802.11r Fast BSS Transition with PSK authentication.
- * @hide
- */
- public static final int FT_PSK = 6;
-
- /**
- * IEEE 802.11r Fast BSS Transition with EAP authentication.
- * @hide
- */
- public static final int FT_EAP = 7;
-
- /**
- * Simultaneous Authentication of Equals
- */
- public static final int SAE = 8;
-
- /**
- * Opportunististic Wireless Encryption
- */
- public static final int OWE = 9;
-
- /**
- * SUITE_B_192 192 bit level
- */
- public static final int SUITE_B_192 = 10;
-
- /**
- * WPA pre-shared key with stronger SHA256-based algorithms.
- * @hide
- */
- public static final int WPA_PSK_SHA256 = 11;
-
- /**
- * WPA using EAP authentication with stronger SHA256-based algorithms.
- * @hide
- */
- public static final int WPA_EAP_SHA256 = 12;
-
- /**
- * WAPI pre-shared key (requires {@code preSharedKey} to be specified).
- * @hide
- */
- @SystemApi
- public static final int WAPI_PSK = 13;
-
- /**
- * WAPI certificate to be specified.
- * @hide
- */
- @SystemApi
- public static final int WAPI_CERT = 14;
-
- /**
- * IEEE 802.11ai FILS SK with SHA256
- * @hide
- */
- public static final int FILS_SHA256 = 15;
- /**
- * IEEE 802.11ai FILS SK with SHA384:
- * @hide
- */
- public static final int FILS_SHA384 = 16;
-
- public static final String varName = "key_mgmt";
-
- public static final String[] strings = { "NONE", "WPA_PSK", "WPA_EAP",
- "IEEE8021X", "WPA2_PSK", "OSEN", "FT_PSK", "FT_EAP",
- "SAE", "OWE", "SUITE_B_192", "WPA_PSK_SHA256", "WPA_EAP_SHA256",
- "WAPI_PSK", "WAPI_CERT", "FILS_SHA256", "FILS_SHA384" };
- }
-
- /**
- * Recognized security protocols.
- */
- public static class Protocol {
- private Protocol() { }
-
- /** WPA/IEEE 802.11i/D3.0
- * @deprecated Due to security and performance limitations, use of WPA-1 networks
- * is discouraged. WPA-2 (RSN) should be used instead. */
- @Deprecated
- public static final int WPA = 0;
- /** RSN WPA2/WPA3/IEEE 802.11i */
- public static final int RSN = 1;
- /** HS2.0 r2 OSEN
- * @hide
- */
- public static final int OSEN = 2;
-
- /**
- * WAPI Protocol
- */
- public static final int WAPI = 3;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(value = {WPA, RSN, OSEN, WAPI})
- public @interface ProtocolScheme {};
-
- public static final String varName = "proto";
-
- public static final String[] strings = { "WPA", "RSN", "OSEN", "WAPI" };
- }
-
- /**
- * Recognized IEEE 802.11 authentication algorithms.
- */
- public static class AuthAlgorithm {
- private AuthAlgorithm() { }
-
- /** Open System authentication (required for WPA/WPA2) */
- public static final int OPEN = 0;
- /** Shared Key authentication (requires static WEP keys)
- * @deprecated Due to security and performance limitations, use of WEP networks
- * is discouraged. */
- @Deprecated
- public static final int SHARED = 1;
- /** LEAP/Network EAP (only used with LEAP) */
- public static final int LEAP = 2;
-
- /** SAE (Used only for WPA3-Personal) */
- public static final int SAE = 3;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(value = {OPEN, SHARED, LEAP, SAE})
- public @interface AuthAlgorithmScheme {};
-
- public static final String varName = "auth_alg";
-
- public static final String[] strings = { "OPEN", "SHARED", "LEAP", "SAE" };
- }
-
- /**
- * Recognized pairwise ciphers for WPA.
- */
- public static class PairwiseCipher {
- private PairwiseCipher() { }
-
- /** Use only Group keys (deprecated) */
- public static final int NONE = 0;
- /** Temporal Key Integrity Protocol [IEEE 802.11i/D7.0]
- * @deprecated Due to security and performance limitations, use of WPA-1 networks
- * is discouraged. WPA-2 (RSN) should be used instead. */
- @Deprecated
- public static final int TKIP = 1;
- /** AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0] */
- public static final int CCMP = 2;
- /**
- * AES in Galois/Counter Mode
- */
- public static final int GCMP_256 = 3;
- /**
- * SMS4 cipher for WAPI
- */
- public static final int SMS4 = 4;
-
- /**
- * AES in Galois/Counter Mode with a 128-bit integrity key
- */
- public static final int GCMP_128 = 5;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(value = {NONE, TKIP, CCMP, GCMP_256, SMS4, GCMP_128})
- public @interface PairwiseCipherScheme {};
-
- public static final String varName = "pairwise";
-
- public static final String[] strings = { "NONE", "TKIP", "CCMP", "GCMP_256", "SMS4",
- "GCMP_128" };
- }
-
- /**
- * Recognized group ciphers.
- *
- * CCMP = AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0]
- * TKIP = Temporal Key Integrity Protocol [IEEE 802.11i/D7.0]
- * WEP104 = WEP (Wired Equivalent Privacy) with 104-bit key
- * WEP40 = WEP (Wired Equivalent Privacy) with 40-bit key (original 802.11)
- * GCMP_256 = AES in Galois/Counter Mode
- *
- */
- public static class GroupCipher {
- private GroupCipher() { }
-
- /** WEP40 = WEP (Wired Equivalent Privacy) with 40-bit key (original 802.11)
- * @deprecated Due to security and performance limitations, use of WEP networks
- * is discouraged. */
- @Deprecated
- public static final int WEP40 = 0;
- /** WEP104 = WEP (Wired Equivalent Privacy) with 104-bit key
- * @deprecated Due to security and performance limitations, use of WEP networks
- * is discouraged. */
- @Deprecated
- public static final int WEP104 = 1;
- /** Temporal Key Integrity Protocol [IEEE 802.11i/D7.0] */
- public static final int TKIP = 2;
- /** AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0] */
- public static final int CCMP = 3;
- /** Hotspot 2.0 r2 OSEN
- * @hide
- */
- public static final int GTK_NOT_USED = 4;
- /**
- * AES in Galois/Counter Mode
- */
- public static final int GCMP_256 = 5;
- /**
- * SMS4 cipher for WAPI
- */
- public static final int SMS4 = 6;
- /**
- * AES in Galois/Counter Mode with a 128-bit integrity key
- */
- public static final int GCMP_128 = 7;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(value = {WEP40, WEP104, TKIP, CCMP, GTK_NOT_USED, GCMP_256, SMS4, GCMP_128})
- public @interface GroupCipherScheme {};
-
- public static final String varName = "group";
-
- public static final String[] strings =
- { /* deprecated */ "WEP40", /* deprecated */ "WEP104",
- "TKIP", "CCMP", "GTK_NOT_USED", "GCMP_256",
- "SMS4", "GCMP_128" };
- }
-
- /**
- * Recognized group management ciphers.
- *
- * BIP_CMAC_256 = Cipher-based Message Authentication Code 256 bits
- * BIP_GMAC_128 = Galois Message Authentication Code 128 bits
- * BIP_GMAC_256 = Galois Message Authentication Code 256 bits
- *
- */
- public static class GroupMgmtCipher {
- private GroupMgmtCipher() { }
-
- /** CMAC-256 = Cipher-based Message Authentication Code */
- public static final int BIP_CMAC_256 = 0;
-
- /** GMAC-128 = Galois Message Authentication Code */
- public static final int BIP_GMAC_128 = 1;
-
- /** GMAC-256 = Galois Message Authentication Code */
- public static final int BIP_GMAC_256 = 2;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(value = {BIP_CMAC_256, BIP_GMAC_128, BIP_GMAC_256})
- public @interface GroupMgmtCipherScheme {};
-
- private static final String varName = "groupMgmt";
-
- /** @hide */
- @SuppressLint("AllUpper")
- public static final @NonNull String[] strings = { "BIP_CMAC_256",
- "BIP_GMAC_128", "BIP_GMAC_256"};
- }
-
- /**
- * Recognized suiteB ciphers.
- *
- * ECDHE_ECDSA
- * ECDHE_RSA
- *
- * @hide
- */
- public static class SuiteBCipher {
- private SuiteBCipher() { }
-
- /** Diffie-Hellman with Elliptic Curve_ECDSA signature */
- public static final int ECDHE_ECDSA = 0;
-
- /** Diffie-Hellman with_RSA signature */
- public static final int ECDHE_RSA = 1;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(value = {ECDHE_ECDSA, ECDHE_RSA})
- public @interface SuiteBCipherScheme {};
-
- private static final String varName = "SuiteB";
-
- /** @hide */
- @SuppressLint("AllUpper")
- public static final String[] strings = { "ECDHE_ECDSA", "ECDHE_RSA" };
- }
-
- /** Possible status of a network configuration. */
- public static class Status {
- private Status() { }
-
- /** this is the network we are currently connected to */
- public static final int CURRENT = 0;
- /** supplicant will not attempt to use this network */
- public static final int DISABLED = 1;
- /** supplicant will consider this network available for association */
- public static final int ENABLED = 2;
-
- public static final String[] strings = { "current", "disabled", "enabled" };
- }
-
- /** Security type for an open network. */
- public static final int SECURITY_TYPE_OPEN = 0;
- /** Security type for a WEP network. */
- public static final int SECURITY_TYPE_WEP = 1;
- /** Security type for a PSK network. */
- public static final int SECURITY_TYPE_PSK = 2;
- /** Security type for an EAP network. */
- public static final int SECURITY_TYPE_EAP = 3;
- /** Security type for an SAE network. */
- public static final int SECURITY_TYPE_SAE = 4;
- /**
- * Security type for a WPA3-Enterprise in 192-bit security network.
- * This is the same as {@link #SECURITY_TYPE_EAP_SUITE_B} and uses the same value.
- */
- public static final int SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT = 5;
- /**
- * Security type for a WPA3-Enterprise in 192-bit security network.
- * @deprecated Use the {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT} constant
- * (which is the same value).
- */
- @Deprecated
- public static final int SECURITY_TYPE_EAP_SUITE_B =
- SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT;
- /** Security type for an OWE network. */
- public static final int SECURITY_TYPE_OWE = 6;
- /** Security type for a WAPI PSK network. */
- public static final int SECURITY_TYPE_WAPI_PSK = 7;
- /** Security type for a WAPI Certificate network. */
- public static final int SECURITY_TYPE_WAPI_CERT = 8;
- /** Security type for a WPA3-Enterprise network. */
- public static final int SECURITY_TYPE_EAP_WPA3_ENTERPRISE = 9;
- /**
- * Security type for an OSEN network.
- * @hide
- */
- public static final int SECURITY_TYPE_OSEN = 10;
- /**
- * Security type for a Passpoint R1/R2 network.
- * Passpoint R1/R2 uses Enterprise security, where TKIP and WEP are not allowed.
- * @hide
- */
- public static final int SECURITY_TYPE_PASSPOINT_R1_R2 = 11;
-
- /**
- * Security type for a Passpoint R3 network.
- * Passpoint R3 uses Enterprise security, where TKIP and WEP are not allowed,
- * and PMF must be set to Required.
- * @hide
- */
- public static final int SECURITY_TYPE_PASSPOINT_R3 = 12;
-
- /**
- * Security types we support.
- * @hide
- */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = { "SECURITY_TYPE_" }, value = {
- SECURITY_TYPE_OPEN,
- SECURITY_TYPE_WEP,
- SECURITY_TYPE_PSK,
- SECURITY_TYPE_EAP,
- SECURITY_TYPE_SAE,
- SECURITY_TYPE_EAP_SUITE_B,
- SECURITY_TYPE_OWE,
- SECURITY_TYPE_WAPI_PSK,
- SECURITY_TYPE_WAPI_CERT,
- SECURITY_TYPE_EAP_WPA3_ENTERPRISE,
- SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT,
- SECURITY_TYPE_PASSPOINT_R1_R2,
- SECURITY_TYPE_PASSPOINT_R3,
- })
- public @interface SecurityType {}
-
- private List mSecurityParamsList = new ArrayList<>();
-
- private void updateLegacySecurityParams() {
- if (mSecurityParamsList.isEmpty()) return;
- mSecurityParamsList.get(0).updateLegacyWifiConfiguration(this);
- }
-
- /**
- * Set the various security params to correspond to the provided security type.
- * This is accomplished by setting the various BitSets exposed in WifiConfiguration.
- *
- * This API would clear existing security types and add a default one.
- *
- * @param securityType One of the following security types:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WEP},
- * {@link #SECURITY_TYPE_PSK},
- * {@link #SECURITY_TYPE_EAP},
- * {@link #SECURITY_TYPE_SAE},
- * {@link #SECURITY_TYPE_OWE},
- * {@link #SECURITY_TYPE_WAPI_PSK},
- * {@link #SECURITY_TYPE_WAPI_CERT},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT},
- */
- public void setSecurityParams(@SecurityType int securityType) {
- // Clear existing data.
- mSecurityParamsList.clear();
- addSecurityParams(securityType);
- }
-
- /**
- * Set security params by the given key management mask.
- *
- * @param givenAllowedKeyManagement the given allowed key management mask.
- * @hide
- */
- public void setSecurityParams(@NonNull BitSet givenAllowedKeyManagement) {
- if (givenAllowedKeyManagement == null) {
- throw new IllegalArgumentException("Invalid allowed key management mask.");
- }
- // Clear existing data.
- mSecurityParamsList.clear();
-
- allowedKeyManagement = (BitSet) givenAllowedKeyManagement.clone();
- convertLegacyFieldsToSecurityParamsIfNeeded();
- }
-
- /**
- * Add the various security params.
- *
- * This API would clear existing security types and add a default one.
- * @hide
- */
- public void setSecurityParams(SecurityParams params) {
- // Clear existing data.
- mSecurityParamsList.clear();
- addSecurityParams(params);
- }
-
- /**
- * Set the security params by the given security params list.
- *
- * This will overwrite existing security params list directly.
- *
- * @param securityParamsList the desired security params list.
- * @hide
- */
- public void setSecurityParams(@NonNull List securityParamsList) {
- if (securityParamsList == null || securityParamsList.isEmpty()) {
- throw new IllegalArgumentException("An empty security params list is invalid.");
- }
- mSecurityParamsList = new ArrayList<>(securityParamsList);
- }
-
- /**
- * Add the various security params to correspond to the provided security type.
- * This is accomplished by setting the various BitSets exposed in WifiConfiguration.
- *
- * @param securityType One of the following security types:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WEP},
- * {@link #SECURITY_TYPE_PSK},
- * {@link #SECURITY_TYPE_EAP},
- * {@link #SECURITY_TYPE_SAE},
- * {@link #SECURITY_TYPE_OWE},
- * {@link #SECURITY_TYPE_WAPI_PSK},
- * {@link #SECURITY_TYPE_WAPI_CERT},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT},
- *
- * @hide
- */
- public void addSecurityParams(@SecurityType int securityType) {
- // This ensures that there won't be duplicate security types.
- if (mSecurityParamsList.stream().anyMatch(params -> params.isSecurityType(securityType))) {
- throw new IllegalArgumentException("duplicate security type " + securityType);
- }
- addSecurityParams(SecurityParams.createSecurityParamsBySecurityType(securityType));
- }
-
- /** @hide */
- public void addSecurityParams(@NonNull SecurityParams newParams) {
- if (mSecurityParamsList.stream().anyMatch(params -> params.isSameSecurityType(newParams))) {
- throw new IllegalArgumentException("duplicate security params " + newParams);
- }
- if (!mSecurityParamsList.isEmpty()) {
- if (newParams.isEnterpriseSecurityType() && !isEnterprise()) {
- throw new IllegalArgumentException(
- "An enterprise security type cannot be added to a personal configuation.");
- }
- if (!newParams.isEnterpriseSecurityType() && isEnterprise()) {
- throw new IllegalArgumentException(
- "A personal security type cannot be added to an enterprise configuation.");
- }
- if (newParams.isOpenSecurityType() && !isOpenNetwork()) {
- throw new IllegalArgumentException(
- "An open security type cannot be added to a non-open configuation.");
- }
- if (!newParams.isOpenSecurityType() && isOpenNetwork()) {
- throw new IllegalArgumentException(
- "A non-open security type cannot be added to an open configuation.");
- }
- if (newParams.isSecurityType(SECURITY_TYPE_OSEN)) {
- throw new IllegalArgumentException(
- "An OSEN security type must be the only one type.");
- }
- }
- mSecurityParamsList.add(new SecurityParams(newParams));
- updateLegacySecurityParams();
- }
-
- /**
- * If there is no security params, generate one according to legacy fields.
- * @hide
- */
- public void convertLegacyFieldsToSecurityParamsIfNeeded() {
- if (!mSecurityParamsList.isEmpty()) return;
-
- if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
- setSecurityParams(SECURITY_TYPE_WAPI_CERT);
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_PSK)) {
- setSecurityParams(SECURITY_TYPE_WAPI_PSK);
- } else if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- setSecurityParams(SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT);
- } else if (allowedKeyManagement.get(KeyMgmt.OWE)) {
- setSecurityParams(SECURITY_TYPE_OWE);
- } else if (allowedKeyManagement.get(KeyMgmt.SAE)) {
- setSecurityParams(SECURITY_TYPE_SAE);
- } else if (allowedKeyManagement.get(KeyMgmt.OSEN)) {
- setSecurityParams(SECURITY_TYPE_OSEN);
- } else if (allowedKeyManagement.get(KeyMgmt.WPA2_PSK)) {
- setSecurityParams(SECURITY_TYPE_PSK);
- } else if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
- if (requirePmf) {
- setSecurityParams(SECURITY_TYPE_EAP_WPA3_ENTERPRISE);
- } else {
- setSecurityParams(SECURITY_TYPE_EAP);
- }
- } else if (allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
- setSecurityParams(SECURITY_TYPE_PSK);
- } else if (allowedKeyManagement.get(KeyMgmt.NONE)) {
- if (hasWepKeys()) {
- setSecurityParams(SECURITY_TYPE_WEP);
- } else {
- setSecurityParams(SECURITY_TYPE_OPEN);
- }
- } else {
- setSecurityParams(SECURITY_TYPE_OPEN);
- }
- }
-
- /**
- * Disable the various security params to correspond to the provided security type.
- * This is accomplished by setting the various BitSets exposed in WifiConfiguration.
- *
- * @param securityType One of the following security types:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WEP},
- * {@link #SECURITY_TYPE_PSK},
- * {@link #SECURITY_TYPE_EAP},
- * {@link #SECURITY_TYPE_SAE},
- * {@link #SECURITY_TYPE_OWE},
- * {@link #SECURITY_TYPE_WAPI_PSK},
- * {@link #SECURITY_TYPE_WAPI_CERT},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT},
- *
- * @hide
- */
- public void setSecurityParamsEnabled(@SecurityType int securityType, boolean enable) {
- mSecurityParamsList.stream()
- .filter(params -> params.isSecurityType(securityType))
- .findAny()
- .ifPresent(params -> params.setEnabled(enable));
- }
-
- /**
- * Get the specific security param.
- *
- * @param securityType One of the following security types:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WEP},
- * {@link #SECURITY_TYPE_PSK},
- * {@link #SECURITY_TYPE_EAP},
- * {@link #SECURITY_TYPE_SAE},
- * {@link #SECURITY_TYPE_OWE},
- * {@link #SECURITY_TYPE_WAPI_PSK},
- * {@link #SECURITY_TYPE_WAPI_CERT},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT},
- *
- * @return the copy of specific security params if found; otherwise null.
- * @hide
- */
- public @Nullable SecurityParams getSecurityParams(@SecurityType int securityType) {
- SecurityParams p = mSecurityParamsList.stream()
- .filter(params -> params.isSecurityType(securityType))
- .findAny()
- .orElse(null);
- return (p != null) ? new SecurityParams(p) : null;
- }
-
- /**
- * Indicate whether this configuration is the specific security type.
- *
- * @param securityType One of the following security types:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WEP},
- * {@link #SECURITY_TYPE_PSK},
- * {@link #SECURITY_TYPE_EAP},
- * {@link #SECURITY_TYPE_SAE},
- * {@link #SECURITY_TYPE_OWE},
- * {@link #SECURITY_TYPE_WAPI_PSK},
- * {@link #SECURITY_TYPE_WAPI_CERT},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT},
- *
- * @return true if there is a security params matches the type.
- * @hide
- */
- public boolean isSecurityType(@SecurityType int securityType) {
- return mSecurityParamsList.stream()
- .anyMatch(params -> params.isSecurityType(securityType));
- }
-
- /**
- * Get the security params list of this configuration.
- *
- * The returning list is a priority list, the first is the lowest priority and default one.
- *
- * @return this list of security params.
- * @hide
- */
- public List getSecurityParamsList() {
- return Collections.unmodifiableList(mSecurityParamsList);
- }
-
- /**
- * Enable the support of Fast Initial Link Set-up (FILS).
- *
- * FILS can be applied to all security types.
- * @param enableFilsSha256 Enable FILS SHA256.
- * @param enableFilsSha384 Enable FILS SHA256.
- * @hide
- */
- public void enableFils(boolean enableFilsSha256, boolean enableFilsSha384) {
- mSecurityParamsList.stream()
- .forEach(params -> params.enableFils(enableFilsSha256, enableFilsSha384));
- updateLegacySecurityParams();
- }
-
- /**
- * Indicate FILS SHA256 is enabled.
- *
- * @return true if FILS SHA256 is enabled.
- * @hide
- */
- public boolean isFilsSha256Enabled() {
- return mSecurityParamsList.stream()
- .anyMatch(params -> params.getAllowedKeyManagement().get(KeyMgmt.FILS_SHA256));
- }
-
- /**
- * Indicate FILS SHA384 is enabled.
- *
- * @return true if FILS SHA384 is enabled.
- * @hide
- */
- public boolean isFilsSha384Enabled() {
- return mSecurityParamsList.stream()
- .anyMatch(params -> params.getAllowedKeyManagement().get(KeyMgmt.FILS_SHA384));
- }
-
- /**
- * Enable Suite-B ciphers.
- *
- * @param enableEcdheEcdsa enable Diffie-Hellman with Elliptic Curve ECDSA cipher support.
- * @param enableEcdheRsa enable Diffie-Hellman with RSA cipher support.
- * @hide
- */
- public void enableSuiteBCiphers(boolean enableEcdheEcdsa, boolean enableEcdheRsa) {
- mSecurityParamsList.stream()
- .filter(params -> params.isSecurityType(SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT))
- .findAny()
- .ifPresent(params -> params.enableSuiteBCiphers(enableEcdheEcdsa, enableEcdheRsa));
- updateLegacySecurityParams();
- }
-
- /**
- * Indicate ECDHE_ECDSA is enabled.
- *
- * @return true if enabled.
- * @hide
- */
- public boolean isSuiteBCipherEcdheEcdsaEnabled() {
- return mSecurityParamsList.stream()
- .anyMatch(params -> params.getAllowedSuiteBCiphers().get(SuiteBCipher.ECDHE_ECDSA));
- }
-
- /**
- * Indicate ECDHE_RSA is enabled.
- *
- * @return true if enabled.
- * @hide
- */
- public boolean isSuiteBCipherEcdheRsaEnabled() {
- return mSecurityParamsList.stream()
- .anyMatch(params -> params.getAllowedSuiteBCiphers().get(SuiteBCipher.ECDHE_RSA));
- }
-
- /**
- * Set SAE Hash-toElement only mode enabled.
- *
- * @param enable true if enabled; false otherwise.
- * @hide
- */
- public void enableSaeH2eOnlyMode(boolean enable) {
- mSecurityParamsList.stream()
- .filter(params -> params.isSecurityType(SECURITY_TYPE_SAE))
- .findAny()
- .ifPresent(params -> params.enableSaeH2eOnlyMode(enable));
- }
-
- /**
- * Set SAE Public-Key only mode enabled.
- *
- * @param enable true if enabled; false otherwise.
- * @hide
- */
- public void enableSaePkOnlyMode(boolean enable) {
- mSecurityParamsList.stream()
- .filter(params -> params.isSecurityType(SECURITY_TYPE_SAE))
- .findAny()
- .ifPresent(params -> params.enableSaePkOnlyMode(enable));
- }
-
- /** @hide */
- public static final int UNKNOWN_UID = -1;
-
- /**
- * The ID number that the supplicant uses to identify this
- * network configuration entry. This must be passed as an argument
- * to most calls into the supplicant.
- */
- public int networkId;
-
- // Fixme We need remove this field to use only Quality network selection status only
- /**
- * The current status of this network configuration entry.
- * @see Status
- */
- public int status;
-
- /**
- * The network's SSID. Can either be a UTF-8 string,
- * which must be enclosed in double quotation marks
- * (e.g., {@code "MyNetwork"}), or a string of
- * hex digits, which are not enclosed in quotes
- * (e.g., {@code 01a243f405}).
- */
- public String SSID;
-
- /**
- * When set, this network configuration entry should only be used when
- * associating with the AP having the specified BSSID. The value is
- * a string in the format of an Ethernet MAC address, e.g.,
- * XX:XX:XX:XX:XX:XX where each X is a hex digit.
- */
- public String BSSID;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"AP_BAND_"}, value = {
- AP_BAND_2GHZ,
- AP_BAND_5GHZ,
- AP_BAND_ANY})
- public @interface ApBand {}
-
- /**
- * 2GHz band.
- * @hide
- */
- public static final int AP_BAND_2GHZ = 0;
-
- /**
- * 5GHz band.
- * @hide
- */
- public static final int AP_BAND_5GHZ = 1;
-
- /**
- * 60GHz band
- * @hide
- */
- public static final int AP_BAND_60GHZ = 2;
-
- /**
- * Device is allowed to choose the optimal band (2Ghz or 5Ghz) based on device capability,
- * operating country code and current radio conditions.
- * @hide
- */
- public static final int AP_BAND_ANY = -1;
-
- /**
- * The band which the AP resides on.
- * One of {@link #AP_BAND_2GHZ}, {@link #AP_BAND_5GHZ}, or {@link #AP_BAND_ANY}.
- * By default, {@link #AP_BAND_2GHZ} is chosen.
- *
- * @hide
- */
- @UnsupportedAppUsage
- @ApBand
- public int apBand = AP_BAND_2GHZ;
-
- /**
- * The channel which AP resides on,currently, US only
- * 2G 1-11
- * 5G 36,40,44,48,149,153,157,161,165
- * 0 - find a random available channel according to the apBand
- * @hide
- */
- @UnsupportedAppUsage
- public int apChannel = 0;
-
- /**
- * Pre-shared key for use with WPA-PSK. Either an ASCII string enclosed in
- * double quotation marks (e.g., {@code "abcdefghij"} for PSK passphrase or
- * a string of 64 hex digits for raw PSK.
- *
- * When the value of this key is read, the actual key is
- * not returned, just a "*" if the key has a value, or the null
- * string otherwise.
- */
- public String preSharedKey;
-
- /**
- * Four WEP keys. For each of the four values, provide either an ASCII
- * string enclosed in double quotation marks (e.g., {@code "abcdef"}),
- * a string of hex digits (e.g., {@code 0102030405}), or an empty string
- * (e.g., {@code ""}).
- *
- * When the value of one of these keys is read, the actual key is
- * not returned, just a "*" if the key has a value, or the null
- * string otherwise.
- * @deprecated Due to security and performance limitations, use of WEP networks
- * is discouraged.
- */
- @Deprecated
- public String[] wepKeys;
-
- /** Default WEP key index, ranging from 0 to 3.
- * @deprecated Due to security and performance limitations, use of WEP networks
- * is discouraged. */
- @Deprecated
- public int wepTxKeyIndex;
-
- /**
- * Priority determines the preference given to a network by {@code wpa_supplicant}
- * when choosing an access point with which to associate.
- * @deprecated This field does not exist anymore.
- */
- @Deprecated
- public int priority;
-
- /**
- * This is a network that does not broadcast its SSID, so an
- * SSID-specific probe request must be used for scans.
- */
- public boolean hiddenSSID;
-
- /**
- * True if the network requires Protected Management Frames (PMF), false otherwise.
- * @hide
- */
- @SystemApi
- public boolean requirePmf;
-
- /**
- * Update identifier, for Passpoint network.
- * @hide
- */
- public String updateIdentifier;
-
- /**
- * The set of key management protocols supported by this configuration.
- * See {@link KeyMgmt} for descriptions of the values.
- * Defaults to WPA-PSK WPA-EAP.
- */
- @NonNull
- public BitSet allowedKeyManagement;
- /**
- * The set of security protocols supported by this configuration.
- * See {@link Protocol} for descriptions of the values.
- * Defaults to WPA RSN.
- */
- @NonNull
- public BitSet allowedProtocols;
- /**
- * The set of authentication protocols supported by this configuration.
- * See {@link AuthAlgorithm} for descriptions of the values.
- * Defaults to automatic selection.
- */
- @NonNull
- public BitSet allowedAuthAlgorithms;
- /**
- * The set of pairwise ciphers for WPA supported by this configuration.
- * See {@link PairwiseCipher} for descriptions of the values.
- * Defaults to CCMP TKIP.
- */
- @NonNull
- public BitSet allowedPairwiseCiphers;
- /**
- * The set of group ciphers supported by this configuration.
- * See {@link GroupCipher} for descriptions of the values.
- * Defaults to CCMP TKIP WEP104 WEP40.
- */
- @NonNull
- public BitSet allowedGroupCiphers;
- /**
- * The set of group management ciphers supported by this configuration.
- * See {@link GroupMgmtCipher} for descriptions of the values.
- */
- @NonNull
- public BitSet allowedGroupManagementCiphers;
- /**
- * The set of SuiteB ciphers supported by this configuration.
- * To be used for WPA3-Enterprise mode. Set automatically by the framework based on the
- * certificate type that is used in this configuration.
- */
- @NonNull
- public BitSet allowedSuiteBCiphers;
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the EAP.
- */
- public WifiEnterpriseConfig enterpriseConfig;
-
- /**
- * Fully qualified domain name of a Passpoint configuration
- */
- public String FQDN;
-
- /**
- * Name of Passpoint credential provider
- */
- public String providerFriendlyName;
-
- /**
- * Flag indicating if this network is provided by a home Passpoint provider or a roaming
- * Passpoint provider. This flag will be {@code true} if this network is provided by
- * a home Passpoint provider and {@code false} if is provided by a roaming Passpoint provider
- * or is a non-Passpoint network.
- */
- public boolean isHomeProviderNetwork;
-
- /**
- * Roaming Consortium Id list for Passpoint credential; identifies a set of networks where
- * Passpoint credential will be considered valid
- */
- public long[] roamingConsortiumIds;
-
- /**
- * True if this network configuration is visible to and usable by other users on the
- * same device, false otherwise.
- *
- * @hide
- */
- @SystemApi
- public boolean shared;
-
- /**
- * @hide
- */
- @NonNull
- @UnsupportedAppUsage
- private IpConfiguration mIpConfiguration;
-
- /**
- * @hide
- * dhcp server MAC address if known
- */
- public String dhcpServer;
-
- /**
- * @hide
- * default Gateway MAC address if known
- */
- @UnsupportedAppUsage
- public String defaultGwMacAddress;
-
- /**
- * @hide
- * last time we connected, this configuration had validated internet access
- */
- @UnsupportedAppUsage
- public boolean validatedInternetAccess;
-
- /**
- * @hide
- * The number of beacon intervals between Delivery Traffic Indication Maps (DTIM)
- * This value is populated from scan results that contain Beacon Frames, which are infrequent.
- * The value is not guaranteed to be set or current (Although it SHOULDNT change once set)
- * Valid values are from 1 - 255. Initialized here as 0, use this to check if set.
- */
- public int dtimInterval = 0;
-
- /**
- * Flag indicating if this configuration represents a legacy Passpoint configuration
- * (Release N or older). This is used for migrating Passpoint configuration from N to O.
- * This will no longer be needed after O.
- * @hide
- */
- public boolean isLegacyPasspointConfig = false;
- /**
- * @hide
- * Uid of app creating the configuration
- */
- @SystemApi
- public int creatorUid;
-
- /**
- * @hide
- * Uid of last app issuing a connection related command
- */
- @UnsupportedAppUsage
- public int lastConnectUid;
-
- /**
- * @hide
- * Uid of last app modifying the configuration
- */
- @SystemApi
- public int lastUpdateUid;
-
- /**
- * @hide
- * Universal name for app creating the configuration
- * see {@link PackageManager#getNameForUid(int)}
- */
- @SystemApi
- public String creatorName;
-
- /**
- * @hide
- * Universal name for app updating the configuration
- * see {@link PackageManager#getNameForUid(int)}
- */
- @SystemApi
- public String lastUpdateName;
-
- /**
- * The carrier ID identifies the operator who provides this network configuration.
- * see {@link TelephonyManager#getSimCarrierId()}
- * @hide
- */
- @SystemApi
- public int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
-
- /**
- * The subscription ID identifies the SIM card for which this network configuration is valid.
- * See {@link SubscriptionInfo#getSubscriptionId()}
- * @hide
- */
- @SystemApi
- public int subscriptionId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
-
- /**
- * @hide
- * Auto-join is allowed by user for this network.
- * Default true.
- */
- @SystemApi
- public boolean allowAutojoin = true;
-
- /** @hide **/
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- public static int INVALID_RSSI = -127;
-
- /**
- * @hide
- * Number of reports indicating no Internet Access
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public int numNoInternetAccessReports;
-
- /**
- * @hide
- * The WiFi configuration is considered to have no internet access for purpose of autojoining
- * if there has been a report of it having no internet access, and, it never have had
- * internet access in the past.
- */
- @SystemApi
- public boolean hasNoInternetAccess() {
- return numNoInternetAccessReports > 0 && !validatedInternetAccess;
- }
-
- /**
- * The WiFi configuration is expected not to have Internet access (e.g., a wireless printer, a
- * Chromecast hotspot, etc.). This will be set if the user explicitly confirms a connection to
- * this configuration and selects "don't ask again".
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public boolean noInternetAccessExpected;
-
- /**
- * The WiFi configuration is expected not to have Internet access (e.g., a wireless printer, a
- * Chromecast hotspot, etc.). This will be set if the user explicitly confirms a connection to
- * this configuration and selects "don't ask again".
- * @hide
- */
- @SystemApi
- public boolean isNoInternetAccessExpected() {
- return noInternetAccessExpected;
- }
-
- /**
- * This Wifi configuration is expected for OSU(Online Sign Up) of Passpoint Release 2.
- * @hide
- */
- public boolean osu;
-
- /**
- * @hide
- * Last time the system was connected to this configuration.
- */
- public long lastConnected;
-
- /**
- * @hide
- * Last time the system was disconnected to this configuration.
- */
- public long lastDisconnected;
-
- /**
- * Set if the configuration was self added by the framework
- * This boolean is cleared if we get a connect/save/ update or
- * any wifiManager command that indicate the user interacted with the configuration
- * since we will now consider that the configuration belong to him.
- * @deprecated only kept for @UnsupportedAppUsage
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public boolean selfAdded;
-
- /**
- * Peer WifiConfiguration this WifiConfiguration was added for
- * @hide
- */
- public String peerWifiConfiguration;
-
- /**
- * @hide
- * Indicate that a WifiConfiguration is temporary and should not be saved
- * nor considered by AutoJoin.
- */
- public boolean ephemeral;
-
- /**
- * @hide
- * Indicate that a WifiConfiguration is temporary and should not be saved
- * nor considered by AutoJoin.
- */
- @SystemApi
- public boolean isEphemeral() {
- return ephemeral;
- }
-
- /**
- * Indicate whether the network is trusted or not. Networks are considered trusted
- * if the user explicitly allowed this network connection.
- * This bit can be used by suggestion network, see
- * {@link WifiNetworkSuggestion.Builder#setUntrusted(boolean)}
- * @hide
- */
- public boolean trusted;
-
- /**
- * Indicate whether the network is oem paid or not. Networks are considered oem paid
- * if the corresponding connection is only available to system apps.
- *
- * This bit can only be used by suggestion network, see
- * {@link WifiNetworkSuggestion.Builder#setOemPaid(boolean)}
- * @hide
- */
- public boolean oemPaid;
-
-
- /**
- * Indicate whether the network is oem private or not. Networks are considered oem private
- * if the corresponding connection is only available to system apps.
- *
- * This bit can only be used by suggestion network, see
- * {@link WifiNetworkSuggestion.Builder#setOemPrivate(boolean)}
- * @hide
- */
- public boolean oemPrivate;
-
- /**
- * Indicate whether or not the network is a carrier merged network.
- * This bit can only be used by suggestion network, see
- * {@link WifiNetworkSuggestion.Builder#setCarrierMerged(boolean)}
- * @hide
- */
- @SystemApi
- public boolean carrierMerged;
-
- /**
- * True if this Wifi configuration is created from a {@link WifiNetworkSuggestion},
- * false otherwise.
- *
- * @hide
- */
- @SystemApi
- public boolean fromWifiNetworkSuggestion;
-
- /**
- * True if this Wifi configuration is created from a {@link WifiNetworkSpecifier},
- * false otherwise.
- *
- * @hide
- */
- @SystemApi
- public boolean fromWifiNetworkSpecifier;
-
- /**
- * True if the creator of this configuration has expressed that it
- * should be considered metered, false otherwise.
- *
- * @see #isMetered(WifiConfiguration, WifiInfo)
- *
- * @hide
- */
- @SystemApi
- public boolean meteredHint;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"METERED_OVERRIDE_"}, value = {
- METERED_OVERRIDE_NONE,
- METERED_OVERRIDE_METERED,
- METERED_OVERRIDE_NOT_METERED})
- public @interface MeteredOverride {}
-
- /**
- * No metered override.
- * @hide
- */
- @SystemApi
- public static final int METERED_OVERRIDE_NONE = 0;
- /**
- * Override network to be metered.
- * @hide
- */
- @SystemApi
- public static final int METERED_OVERRIDE_METERED = 1;
- /**
- * Override network to be unmetered.
- * @hide
- */
- @SystemApi
- public static final int METERED_OVERRIDE_NOT_METERED = 2;
-
- /**
- * Indicates if the end user has expressed an explicit opinion about the
- * meteredness of this network, such as through the Settings app.
- * This value is one of {@link #METERED_OVERRIDE_NONE}, {@link #METERED_OVERRIDE_METERED},
- * or {@link #METERED_OVERRIDE_NOT_METERED}.
- *
- * This should always override any values from {@link #meteredHint} or
- * {@link WifiInfo#getMeteredHint()}.
- *
- * By default this field is set to {@link #METERED_OVERRIDE_NONE}.
- *
- * @see #isMetered(WifiConfiguration, WifiInfo)
- * @hide
- */
- @SystemApi
- @MeteredOverride
- public int meteredOverride = METERED_OVERRIDE_NONE;
-
- /**
- * Blend together all the various opinions to decide if the given network
- * should be considered metered or not.
- *
- * @hide
- */
- @SystemApi
- public static boolean isMetered(@Nullable WifiConfiguration config, @Nullable WifiInfo info) {
- boolean metered = false;
- if (info != null && info.getMeteredHint()) {
- metered = true;
- }
- if (config != null && config.meteredHint) {
- metered = true;
- }
- if (config != null
- && config.meteredOverride == WifiConfiguration.METERED_OVERRIDE_METERED) {
- metered = true;
- }
- if (config != null
- && config.meteredOverride == WifiConfiguration.METERED_OVERRIDE_NOT_METERED) {
- metered = false;
- }
- return metered;
- }
-
- /** Check whether wep keys exist. */
- private boolean hasWepKeys() {
- if (wepKeys == null) return false;
- for (int i = 0; i < wepKeys.length; i++) {
- if (wepKeys[i] != null) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * @hide
- * Returns true if this WiFi config is for an Open or Enhanced Open network.
- */
- public boolean isOpenNetwork() {
- boolean hasNonOpenSecurityType = mSecurityParamsList.stream()
- .anyMatch(params -> !params.isOpenSecurityType());
- return !hasNonOpenSecurityType && !hasWepKeys();
- }
-
- /**
- * @hide
- * Setting this value will force scan results associated with this configuration to
- * be included in the bucket of networks that are externally scored.
- * If not set, associated scan results will be treated as legacy saved networks and
- * will take precedence over networks in the scored category.
- */
- @SystemApi
- public boolean useExternalScores;
-
- /**
- * @hide
- * Number of time the scorer overrode a the priority based choice, when comparing two
- * WifiConfigurations, note that since comparing WifiConfiguration happens very often
- * potentially at every scan, this number might become very large, even on an idle
- * system.
- */
- @SystemApi
- public int numScorerOverride;
-
- /**
- * @hide
- * Number of time the scorer overrode a the priority based choice, and the comparison
- * triggered a network switch
- */
- @SystemApi
- public int numScorerOverrideAndSwitchedNetwork;
-
- /**
- * @hide
- * Number of time we associated to this configuration.
- */
- @SystemApi
- public int numAssociation;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"RANDOMIZATION_"}, value = {
- RANDOMIZATION_NONE,
- RANDOMIZATION_PERSISTENT,
- RANDOMIZATION_ENHANCED,
- RANDOMIZATION_AUTO})
- public @interface MacRandomizationSetting {}
-
- /**
- * Use factory MAC when connecting to this network
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_NONE = 0;
- /**
- * Generate a randomized MAC once and reuse it for all connections to this network
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_PERSISTENT = 1;
-
- /**
- * Use a randomly generated MAC address for connections to this network.
- * This option does not persist the randomized MAC address.
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_ENHANCED = 2;
-
- /**
- * Let the wifi framework automatically decide the MAC randomization strategy.
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_AUTO = 3;
-
- /**
- * Level of MAC randomization for this network.
- * One of {@link #RANDOMIZATION_NONE}, {@link #RANDOMIZATION_AUTO},
- * {@link #RANDOMIZATION_PERSISTENT} or {@link #RANDOMIZATION_ENHANCED}.
- * By default this field is set to {@link #RANDOMIZATION_AUTO}.
- * @hide
- */
- @SystemApi
- @MacRandomizationSetting
- public int macRandomizationSetting = RANDOMIZATION_AUTO;
-
- /**
- * @hide
- * Randomized MAC address to use with this particular network
- */
- @NonNull
- private MacAddress mRandomizedMacAddress;
-
- /**
- * @hide
- * The wall clock time of when |mRandomizedMacAddress| should be re-randomized in enhanced
- * MAC randomization mode.
- */
- public long randomizedMacExpirationTimeMs = 0;
-
- /**
- * The wall clock time of when |mRandomizedMacAddress| is last modified.
- * @hide
- */
- public long randomizedMacLastModifiedTimeMs = 0;
-
- /**
- * @hide
- * Checks if the given MAC address can be used for Connected Mac Randomization
- * by verifying that it is non-null, unicast, locally assigned, and not default mac.
- * @param mac MacAddress to check
- * @return true if mac is good to use
- */
- public static boolean isValidMacAddressForRandomization(MacAddress mac) {
- return mac != null && !MacAddressUtils.isMulticastAddress(mac) && mac.isLocallyAssigned()
- && !MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS).equals(mac);
- }
-
- /**
- * Returns MAC address set to be the local randomized MAC address.
- * Depending on user preference, the device may or may not use the returned MAC address for
- * connections to this network.
- *
- * Information is restricted to Device Owner, Profile Owner, and Carrier apps
- * (which will only obtain addresses for configurations which they create). Other callers
- * will receive a default "02:00:00:00:00:00" MAC address.
- */
- public @NonNull MacAddress getRandomizedMacAddress() {
- return mRandomizedMacAddress;
- }
-
- /**
- * @hide
- * @param mac MacAddress to change into
- */
- public void setRandomizedMacAddress(@NonNull MacAddress mac) {
- if (mac == null) {
- Log.e(TAG, "setRandomizedMacAddress received null MacAddress.");
- return;
- }
- mRandomizedMacAddress = mac;
- }
-
- /** @hide
- * Boost given to RSSI on a home network for the purpose of calculating the score
- * This adds stickiness to home networks, as defined by:
- * - less than 4 known BSSIDs
- * - PSK only
- * - TODO: add a test to verify that all BSSIDs are behind same gateway
- ***/
- public static final int HOME_NETWORK_RSSI_BOOST = 5;
-
- /**
- * This class is used to contain all the information and API used for quality network selection.
- * @hide
- */
- @SystemApi
- public static class NetworkSelectionStatus {
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = "NETWORK_SELECTION_",
- value = {
- NETWORK_SELECTION_ENABLED,
- NETWORK_SELECTION_TEMPORARY_DISABLED,
- NETWORK_SELECTION_PERMANENTLY_DISABLED})
- public @interface NetworkEnabledStatus {}
- /**
- * This network will be considered as a potential candidate to connect to during network
- * selection.
- */
- public static final int NETWORK_SELECTION_ENABLED = 0;
- /**
- * This network was temporary disabled. May be re-enabled after a time out.
- */
- public static final int NETWORK_SELECTION_TEMPORARY_DISABLED = 1;
- /**
- * This network was permanently disabled.
- */
- public static final int NETWORK_SELECTION_PERMANENTLY_DISABLED = 2;
- /**
- * Maximum Network selection status
- * @hide
- */
- public static final int NETWORK_SELECTION_STATUS_MAX = 3;
-
- /**
- * Quality network selection status String (for debug purpose). Use Quality network
- * selection status value as index to extec the corresponding debug string
- * @hide
- */
- public static final String[] QUALITY_NETWORK_SELECTION_STATUS = {
- "NETWORK_SELECTION_ENABLED",
- "NETWORK_SELECTION_TEMPORARY_DISABLED",
- "NETWORK_SELECTION_PERMANENTLY_DISABLED"};
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = "DISABLED_", value = {
- DISABLED_NONE,
- DISABLED_ASSOCIATION_REJECTION,
- DISABLED_AUTHENTICATION_FAILURE,
- DISABLED_DHCP_FAILURE,
- DISABLED_NO_INTERNET_TEMPORARY,
- DISABLED_AUTHENTICATION_NO_CREDENTIALS,
- DISABLED_NO_INTERNET_PERMANENT,
- DISABLED_BY_WIFI_MANAGER,
- DISABLED_BY_WRONG_PASSWORD,
- DISABLED_AUTHENTICATION_NO_SUBSCRIPTION,
- DISABLED_AUTHENTICATION_FAILURE_GENERIC,
- DISABLED_AUTHENTICATION_FAILURE_CARRIER_SPECIFIC})
- public @interface NetworkSelectionDisableReason {}
-
- // Quality Network disabled reasons
- /** Default value. Means not disabled. */
- public static final int DISABLED_NONE = 0;
- /**
- * The starting index for network selection disabled reasons.
- * @hide
- */
- public static final int NETWORK_SELECTION_DISABLED_STARTING_INDEX = 1;
- /** This network is temporarily disabled because of multiple association rejections. */
- public static final int DISABLED_ASSOCIATION_REJECTION = 1;
- /** This network is disabled due to generic authentication failure. */
- public static final int DISABLED_AUTHENTICATION_FAILURE_GENERIC = 2;
- /** Separate DISABLED_AUTHENTICATION_FAILURE into DISABLED_AUTHENTICATION_FAILURE_GENERIC
- * and DISABLED_AUTHENTICATION_FAILURE_CARRIER_SPECIFIC
- * @deprecated Use the {@link #DISABLED_AUTHENTICATION_FAILURE_GENERIC} constant
- * (which is the same value).
- */
- @Deprecated
- public static final int DISABLED_AUTHENTICATION_FAILURE =
- DISABLED_AUTHENTICATION_FAILURE_GENERIC;
- /** This network is temporarily disabled because of multiple DHCP failure. */
- public static final int DISABLED_DHCP_FAILURE = 3;
- /** This network is temporarily disabled because it has no Internet access. */
- public static final int DISABLED_NO_INTERNET_TEMPORARY = 4;
- /** This network is permanently disabled due to absence of user credentials */
- public static final int DISABLED_AUTHENTICATION_NO_CREDENTIALS = 5;
- /**
- * This network is permanently disabled because it has no Internet access and the user does
- * not want to stay connected.
- */
- public static final int DISABLED_NO_INTERNET_PERMANENT = 6;
- /** This network is permanently disabled due to WifiManager disabling it explicitly. */
- public static final int DISABLED_BY_WIFI_MANAGER = 7;
- /** This network is permanently disabled due to wrong password. */
- public static final int DISABLED_BY_WRONG_PASSWORD = 8;
- /** This network is permanently disabled because service is not subscribed. */
- public static final int DISABLED_AUTHENTICATION_NO_SUBSCRIPTION = 9;
- /** This network is disabled due to carrier specific EAP failure. */
- public static final int DISABLED_AUTHENTICATION_FAILURE_CARRIER_SPECIFIC = 10;
- /**
- * All other disable reasons should be strictly less than this value.
- * @hide
- */
- public static final int NETWORK_SELECTION_DISABLED_MAX = 11;
-
- /**
- * Get an integer that is equal to the maximum integer value of all the
- * DISABLED_* reasons
- * e.g. {@link #DISABLED_NONE}, {@link #DISABLED_ASSOCIATION_REJECTION}, etc.
- *
- * All DISABLED_* constants will be contiguous in the range
- * 0, 1, 2, 3, ..., getMaxNetworkSelectionDisableReasons()
- *
- *
- * For example, this can be used to iterate through all the network selection
- * disable reasons like so:
- *
{@code
- * for (int reason = 0; reason <= getMaxNetworkSelectionDisableReasons(); reason++) {
- * ...
- * }
- * }
- */
- public static int getMaxNetworkSelectionDisableReason() {
- return NETWORK_SELECTION_DISABLED_MAX - 1;
- }
-
- /**
- * Contains info about disable reasons.
- * @hide
- */
- public static final class DisableReasonInfo {
- /**
- * String representation for the disable reason.
- * Note that these strings are persisted in
- * {@link
- * com.android.server.wifi.util.XmlUtil.NetworkSelectionStatusXmlUtil#writeToXml},
- * so do not change the string values to maintain backwards compatibility.
- */
- public final String mReasonStr;
- /**
- * Network Selection disable reason threshold, used to debounce network failures before
- * we disable them.
- */
- public final int mDisableThreshold;
- /**
- * Network Selection disable timeout for the error. After the timeout milliseconds,
- * enable the network again.
- * If this is set to Integer.MAX_VALUE, the network will be permanently disabled until
- * the next time the user manually connects to it.
- */
- public final int mDisableTimeoutMillis;
-
- /**
- * Constructor
- * @param reasonStr string representation of the error
- * @param disableThreshold number of failures before we disable the network
- * @param disableTimeoutMillis the timeout, in milliseconds, before we re-enable the
- * network after disabling it
- */
- public DisableReasonInfo(String reasonStr, int disableThreshold,
- int disableTimeoutMillis) {
- mReasonStr = reasonStr;
- mDisableThreshold = disableThreshold;
- mDisableTimeoutMillis = disableTimeoutMillis;
- }
- }
-
- /**
- * Quality network selection disable reason infos.
- * @hide
- */
- public static final SparseArray DISABLE_REASON_INFOS =
- buildDisableReasonInfos();
-
- private static SparseArray buildDisableReasonInfos() {
- SparseArray reasons = new SparseArray<>();
-
- reasons.append(DISABLED_NONE,
- new DisableReasonInfo(
- // Note that these strings are persisted in
- // XmlUtil.NetworkSelectionStatusXmlUtil#writeToXml,
- // so do not change the string values to maintain backwards
- // compatibility.
- "NETWORK_SELECTION_ENABLE",
- -1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_ASSOCIATION_REJECTION,
- new DisableReasonInfo(
- // Note that there is a space at the end of this string. Cannot fix
- // since this string is persisted.
- "NETWORK_SELECTION_DISABLED_ASSOCIATION_REJECTION ",
- 5,
- 5 * 60 * 1000));
-
- reasons.append(DISABLED_AUTHENTICATION_FAILURE,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_AUTHENTICATION_FAILURE",
- 5,
- 5 * 60 * 1000));
-
- reasons.append(DISABLED_DHCP_FAILURE,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_DHCP_FAILURE",
- 5,
- 5 * 60 * 1000));
-
- reasons.append(DISABLED_NO_INTERNET_TEMPORARY,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_NO_INTERNET_TEMPORARY",
- 1,
- 10 * 60 * 1000));
-
- reasons.append(DISABLED_AUTHENTICATION_NO_CREDENTIALS,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_AUTHENTICATION_NO_CREDENTIALS",
- 1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_NO_INTERNET_PERMANENT,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_NO_INTERNET_PERMANENT",
- 1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_BY_WIFI_MANAGER,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_BY_WIFI_MANAGER",
- 1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_BY_WRONG_PASSWORD,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_BY_WRONG_PASSWORD",
- 1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_AUTHENTICATION_NO_SUBSCRIPTION,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_AUTHENTICATION_NO_SUBSCRIPTION",
- 1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_AUTHENTICATION_FAILURE_GENERIC,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_AUTHENTICATION_FAILURE_GENERIC",
- 5,
- 5 * 60 * 1000));
-
- reasons.append(DISABLED_AUTHENTICATION_FAILURE_CARRIER_SPECIFIC,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_AUTHENTICATION_FAILURE_CARRIER_SPECIFIC",
- 1,
- Integer.MAX_VALUE));
-
- return reasons;
- }
-
- /**
- * Get the {@link NetworkSelectionDisableReason} int code by its string value.
- * @return the NetworkSelectionDisableReason int code corresponding to the reason string,
- * or -1 if the reason string is unrecognized.
- * @hide
- */
- @NetworkSelectionDisableReason
- public static int getDisableReasonByString(@NonNull String reasonString) {
- for (int i = 0; i < DISABLE_REASON_INFOS.size(); i++) {
- int key = DISABLE_REASON_INFOS.keyAt(i);
- DisableReasonInfo value = DISABLE_REASON_INFOS.valueAt(i);
- if (value != null && TextUtils.equals(reasonString, value.mReasonStr)) {
- return key;
- }
- }
- Log.e(TAG, "Unrecognized network disable reason: " + reasonString);
- return -1;
- }
-
- /**
- * Invalid time stamp for network selection disable
- * @hide
- */
- public static final long INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP = -1L;
-
- /**
- * This constant indicates the current configuration has connect choice set
- */
- private static final int CONNECT_CHOICE_EXISTS = 1;
-
- /**
- * This constant indicates the current configuration does not have connect choice set
- */
- private static final int CONNECT_CHOICE_NOT_EXISTS = -1;
-
- // fields for QualityNetwork Selection
- /**
- * Network selection status, should be in one of three status: enable, temporaily disabled
- * or permanently disabled
- */
- @NetworkEnabledStatus
- private int mStatus;
-
- /**
- * Reason for disable this network
- */
- @NetworkSelectionDisableReason
- private int mNetworkSelectionDisableReason;
-
- /**
- * Last time we temporarily disabled the configuration
- */
- private long mTemporarilyDisabledTimestamp = INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP;
-
- /**
- * counter for each Network selection disable reason
- */
- private int[] mNetworkSeclectionDisableCounter = new int[NETWORK_SELECTION_DISABLED_MAX];
-
- /**
- * Connect Choice over this configuration
- *
- * When current wifi configuration is visible to the user but user explicitly choose to
- * connect to another network X, the another networks X's configure key will be stored here.
- * We will consider user has a preference of X over this network. And in the future,
- * network selection will always give X a higher preference over this configuration.
- * configKey is : "SSID"-WEP-WPA_PSK-WPA_EAP
- */
- private String mConnectChoice;
-
- /**
- * The RSSI when the user made the connectChoice.
- */
- private int mConnectChoiceRssi;
-
- /**
- * Used to cache the temporary candidate during the network selection procedure. It will be
- * kept updating once a new scan result has a higher score than current one
- */
- private ScanResult mCandidate;
-
- /**
- * Used to cache the score of the current temporary candidate during the network
- * selection procedure.
- */
- private int mCandidateScore;
-
- /**
- * Indicate whether this network is visible in latest Qualified Network Selection. This
- * means there is scan result found related to this Configuration and meet the minimum
- * requirement. The saved network need not join latest Qualified Network Selection. For
- * example, it is disabled. True means network is visible in latest Qualified Network
- * Selection and false means network is invisible
- */
- private boolean mSeenInLastQualifiedNetworkSelection;
-
- /**
- * Boolean indicating if we have ever successfully connected to this network.
- *
- * This value will be set to true upon a successful connection.
- * This value will be set to false if a previous value was not stored in the config or if
- * the credentials are updated (ex. a password change).
- */
- private boolean mHasEverConnected;
-
- /**
- * Boolean indicating if captive portal has never been detected on this network.
- *
- * This should be true by default, for newly created WifiConfigurations until a captive
- * portal is detected.
- */
- private boolean mHasNeverDetectedCaptivePortal = true;
-
- /**
- * set whether this network is visible in latest Qualified Network Selection
- * @param seen value set to candidate
- * @hide
- */
- public void setSeenInLastQualifiedNetworkSelection(boolean seen) {
- mSeenInLastQualifiedNetworkSelection = seen;
- }
-
- /**
- * get whether this network is visible in latest Qualified Network Selection
- * @return returns true -- network is visible in latest Qualified Network Selection
- * false -- network is invisible in latest Qualified Network Selection
- * @hide
- */
- public boolean getSeenInLastQualifiedNetworkSelection() {
- return mSeenInLastQualifiedNetworkSelection;
- }
- /**
- * set the temporary candidate of current network selection procedure
- * @param scanCandidate {@link ScanResult} the candidate set to mCandidate
- * @hide
- */
- public void setCandidate(ScanResult scanCandidate) {
- mCandidate = scanCandidate;
- }
-
- /**
- * get the temporary candidate of current network selection procedure
- * @return returns {@link ScanResult} temporary candidate of current network selection
- * procedure
- * @hide
- */
- public ScanResult getCandidate() {
- return mCandidate;
- }
-
- /**
- * set the score of the temporary candidate of current network selection procedure
- * @param score value set to mCandidateScore
- * @hide
- */
- public void setCandidateScore(int score) {
- mCandidateScore = score;
- }
-
- /**
- * get the score of the temporary candidate of current network selection procedure
- * @return returns score of the temporary candidate of current network selection procedure
- * @hide
- */
- public int getCandidateScore() {
- return mCandidateScore;
- }
-
- /**
- * get user preferred choice over this configuration
- * @return returns configKey of user preferred choice over this configuration
- * @hide
- */
- public String getConnectChoice() {
- return mConnectChoice;
- }
-
- /**
- * set user preferred choice over this configuration
- * @param newConnectChoice, the configKey of user preferred choice over this configuration
- * @hide
- */
- public void setConnectChoice(String newConnectChoice) {
- mConnectChoice = newConnectChoice;
- }
-
- /**
- * Associate a RSSI with the user connect choice network.
- * @param rssi signal strength
- * @hide
- */
- public void setConnectChoiceRssi(int rssi) {
- mConnectChoiceRssi = rssi;
- }
-
- /**
- * @return returns the RSSI of the last time the user made the connect choice.
- * @hide
- */
- public int getConnectChoiceRssi() {
- return mConnectChoiceRssi;
- }
-
- /** Get the current Quality network selection status as a String (for debugging). */
- @NonNull
- public String getNetworkStatusString() {
- return QUALITY_NETWORK_SELECTION_STATUS[mStatus];
- }
-
- /** @hide */
- public void setHasEverConnected(boolean value) {
- mHasEverConnected = value;
- }
-
- /** True if the device has ever connected to this network, false otherwise. */
- public boolean hasEverConnected() {
- return mHasEverConnected;
- }
-
- /**
- * Set whether a captive portal has never been detected on this network.
- * @hide
- */
- public void setHasNeverDetectedCaptivePortal(boolean value) {
- mHasNeverDetectedCaptivePortal = value;
- }
-
- /** @hide */
- public boolean hasNeverDetectedCaptivePortal() {
- return mHasNeverDetectedCaptivePortal;
- }
-
- /** @hide */
- public NetworkSelectionStatus() {
- // previously stored configs will not have this parameter, so we default to false.
- mHasEverConnected = false;
- }
-
- /**
- * NetworkSelectionStatus exports an immutable public API.
- * However, test code has a need to construct a NetworkSelectionStatus in a specific state.
- * (Note that mocking using Mockito does not work if the object needs to be parceled and
- * unparceled.)
- * Export a @SystemApi Builder to allow tests to construct a NetworkSelectionStatus object
- * in the desired state, without sacrificing NetworkSelectionStatus's immutability.
- */
- @VisibleForTesting
- public static final class Builder {
- private final NetworkSelectionStatus mNetworkSelectionStatus =
- new NetworkSelectionStatus();
-
- /**
- * Set the current network selection status.
- * One of:
- * {@link #NETWORK_SELECTION_ENABLED},
- * {@link #NETWORK_SELECTION_TEMPORARY_DISABLED},
- * {@link #NETWORK_SELECTION_PERMANENTLY_DISABLED}
- * @see NetworkSelectionStatus#getNetworkSelectionStatus()
- */
- @NonNull
- public Builder setNetworkSelectionStatus(@NetworkEnabledStatus int status) {
- mNetworkSelectionStatus.setNetworkSelectionStatus(status);
- return this;
- }
-
- /**
- *
- * Set the current network's disable reason.
- * One of the {@link #DISABLED_NONE} or DISABLED_* constants.
- * e.g. {@link #DISABLED_ASSOCIATION_REJECTION}.
- * @see NetworkSelectionStatus#getNetworkSelectionDisableReason()
- */
- @NonNull
- public Builder setNetworkSelectionDisableReason(
- @NetworkSelectionDisableReason int reason) {
- mNetworkSelectionStatus.setNetworkSelectionDisableReason(reason);
- return this;
- }
-
- /**
- * Build a NetworkSelectionStatus object.
- */
- @NonNull
- public NetworkSelectionStatus build() {
- NetworkSelectionStatus status = new NetworkSelectionStatus();
- status.copy(mNetworkSelectionStatus);
- return status;
- }
- }
-
- /**
- * Get the network disable reason string for a reason code (for debugging).
- * @param reason specific error reason. One of the {@link #DISABLED_NONE} or
- * DISABLED_* constants e.g. {@link #DISABLED_ASSOCIATION_REJECTION}.
- * @return network disable reason string, or null if the reason is invalid.
- */
- @Nullable
- public static String getNetworkSelectionDisableReasonString(
- @NetworkSelectionDisableReason int reason) {
- DisableReasonInfo info = DISABLE_REASON_INFOS.get(reason);
- if (info == null) {
- return null;
- } else {
- return info.mReasonStr;
- }
- }
- /**
- * get current network disable reason
- * @return current network disable reason in String (for debug purpose)
- * @hide
- */
- public String getNetworkSelectionDisableReasonString() {
- return getNetworkSelectionDisableReasonString(mNetworkSelectionDisableReason);
- }
-
- /**
- * Get the current network network selection status.
- * One of:
- * {@link #NETWORK_SELECTION_ENABLED},
- * {@link #NETWORK_SELECTION_TEMPORARY_DISABLED},
- * {@link #NETWORK_SELECTION_PERMANENTLY_DISABLED}
- */
- @NetworkEnabledStatus
- public int getNetworkSelectionStatus() {
- return mStatus;
- }
-
- /**
- * True if the current network is enabled to join network selection, false otherwise.
- * @hide
- */
- public boolean isNetworkEnabled() {
- return mStatus == NETWORK_SELECTION_ENABLED;
- }
-
- /**
- * @return whether current network is temporary disabled
- * @hide
- */
- public boolean isNetworkTemporaryDisabled() {
- return mStatus == NETWORK_SELECTION_TEMPORARY_DISABLED;
- }
-
- /**
- * True if the current network is permanently disabled, false otherwise.
- * @hide
- */
- public boolean isNetworkPermanentlyDisabled() {
- return mStatus == NETWORK_SELECTION_PERMANENTLY_DISABLED;
- }
-
- /**
- * set current network selection status
- * @param status network selection status to set
- * @hide
- */
- public void setNetworkSelectionStatus(int status) {
- if (status >= 0 && status < NETWORK_SELECTION_STATUS_MAX) {
- mStatus = status;
- }
- }
-
- /**
- * Returns the current network's disable reason.
- * One of the {@link #DISABLED_NONE} or DISABLED_* constants
- * e.g. {@link #DISABLED_ASSOCIATION_REJECTION}.
- */
- @NetworkSelectionDisableReason
- public int getNetworkSelectionDisableReason() {
- return mNetworkSelectionDisableReason;
- }
-
- /**
- * set Network disable reason
- * @param reason Network disable reason
- * @hide
- */
- public void setNetworkSelectionDisableReason(@NetworkSelectionDisableReason int reason) {
- if (reason >= 0 && reason < NETWORK_SELECTION_DISABLED_MAX) {
- mNetworkSelectionDisableReason = reason;
- } else {
- throw new IllegalArgumentException("Illegal reason value: " + reason);
- }
- }
-
- /**
- * @param timeStamp Set when current network is disabled in millisecond since January 1,
- * 1970 00:00:00.0 UTC
- * @hide
- */
- public void setDisableTime(long timeStamp) {
- mTemporarilyDisabledTimestamp = timeStamp;
- }
-
- /**
- * Returns when the current network was disabled, in milliseconds since January 1,
- * 1970 00:00:00.0 UTC.
- */
- public long getDisableTime() {
- return mTemporarilyDisabledTimestamp;
- }
-
- /**
- * Get the disable counter of a specific reason.
- * @param reason specific failure reason. One of the {@link #DISABLED_NONE} or
- * DISABLED_* constants e.g. {@link #DISABLED_ASSOCIATION_REJECTION}.
- * @exception IllegalArgumentException for invalid reason
- * @return counter number for specific error reason.
- */
- public int getDisableReasonCounter(@NetworkSelectionDisableReason int reason) {
- if (reason >= DISABLED_NONE && reason < NETWORK_SELECTION_DISABLED_MAX) {
- return mNetworkSeclectionDisableCounter[reason];
- } else {
- throw new IllegalArgumentException("Illegal reason value: " + reason);
- }
- }
-
- /**
- * set the counter of a specific failure reason
- * @param reason reason for disable error
- * @param value the counter value for this specific reason
- * @exception throw IllegalArgumentException for illegal input
- * @hide
- */
- public void setDisableReasonCounter(int reason, int value) {
- if (reason >= DISABLED_NONE && reason < NETWORK_SELECTION_DISABLED_MAX) {
- mNetworkSeclectionDisableCounter[reason] = value;
- } else {
- throw new IllegalArgumentException("Illegal reason value: " + reason);
- }
- }
-
- /**
- * increment the counter of a specific failure reason
- * @param reason a specific failure reason
- * @exception throw IllegalArgumentException for illegal input
- * @hide
- */
- public void incrementDisableReasonCounter(int reason) {
- if (reason >= DISABLED_NONE && reason < NETWORK_SELECTION_DISABLED_MAX) {
- mNetworkSeclectionDisableCounter[reason]++;
- } else {
- throw new IllegalArgumentException("Illegal reason value: " + reason);
- }
- }
-
- /**
- * clear the counter of a specific failure reason
- * @param reason a specific failure reason
- * @exception throw IllegalArgumentException for illegal input
- * @hide
- */
- public void clearDisableReasonCounter(int reason) {
- if (reason >= DISABLED_NONE && reason < NETWORK_SELECTION_DISABLED_MAX) {
- mNetworkSeclectionDisableCounter[reason] = DISABLED_NONE;
- } else {
- throw new IllegalArgumentException("Illegal reason value: " + reason);
- }
- }
-
- /**
- * clear all the failure reason counters
- * @hide
- */
- public void clearDisableReasonCounter() {
- Arrays.fill(mNetworkSeclectionDisableCounter, DISABLED_NONE);
- }
-
- /**
- * BSSID for connection to this network (through network selection procedure)
- */
- private String mNetworkSelectionBSSID;
-
- /**
- * get current network Selection BSSID
- * @return current network Selection BSSID
- * @hide
- */
- public String getNetworkSelectionBSSID() {
- return mNetworkSelectionBSSID;
- }
-
- /**
- * set network Selection BSSID
- * @param bssid The target BSSID for assocaition
- * @hide
- */
- public void setNetworkSelectionBSSID(String bssid) {
- mNetworkSelectionBSSID = bssid;
- }
-
- /** @hide */
- public void copy(NetworkSelectionStatus source) {
- mStatus = source.mStatus;
- mNetworkSelectionDisableReason = source.mNetworkSelectionDisableReason;
- for (int index = DISABLED_NONE; index < NETWORK_SELECTION_DISABLED_MAX;
- index++) {
- mNetworkSeclectionDisableCounter[index] =
- source.mNetworkSeclectionDisableCounter[index];
- }
- mTemporarilyDisabledTimestamp = source.mTemporarilyDisabledTimestamp;
- mNetworkSelectionBSSID = source.mNetworkSelectionBSSID;
- setSeenInLastQualifiedNetworkSelection(source.getSeenInLastQualifiedNetworkSelection());
- setCandidate(source.getCandidate());
- setCandidateScore(source.getCandidateScore());
- setConnectChoice(source.getConnectChoice());
- setConnectChoiceRssi(source.getConnectChoiceRssi());
- setHasEverConnected(source.hasEverConnected());
- setHasNeverDetectedCaptivePortal(source.hasNeverDetectedCaptivePortal());
- }
-
- /** @hide */
- public void writeToParcel(Parcel dest) {
- dest.writeInt(getNetworkSelectionStatus());
- dest.writeInt(getNetworkSelectionDisableReason());
- for (int index = DISABLED_NONE; index < NETWORK_SELECTION_DISABLED_MAX;
- index++) {
- dest.writeInt(getDisableReasonCounter(index));
- }
- dest.writeLong(getDisableTime());
- dest.writeString(getNetworkSelectionBSSID());
- if (getConnectChoice() != null) {
- dest.writeInt(CONNECT_CHOICE_EXISTS);
- dest.writeString(getConnectChoice());
- dest.writeInt(getConnectChoiceRssi());
- } else {
- dest.writeInt(CONNECT_CHOICE_NOT_EXISTS);
- }
- dest.writeInt(hasEverConnected() ? 1 : 0);
- dest.writeInt(hasNeverDetectedCaptivePortal() ? 1 : 0);
- }
-
- /** @hide */
- public void readFromParcel(Parcel in) {
- setNetworkSelectionStatus(in.readInt());
- setNetworkSelectionDisableReason(in.readInt());
- for (int index = DISABLED_NONE; index < NETWORK_SELECTION_DISABLED_MAX;
- index++) {
- setDisableReasonCounter(index, in.readInt());
- }
- setDisableTime(in.readLong());
- setNetworkSelectionBSSID(in.readString());
- if (in.readInt() == CONNECT_CHOICE_EXISTS) {
- setConnectChoice(in.readString());
- setConnectChoiceRssi(in.readInt());
- } else {
- setConnectChoice(null);
- }
- setHasEverConnected(in.readInt() != 0);
- setHasNeverDetectedCaptivePortal(in.readInt() != 0);
- }
- }
-
- /**
- * @hide
- * network selection related member
- */
- private NetworkSelectionStatus mNetworkSelectionStatus = new NetworkSelectionStatus();
-
- /**
- * This class is intended to store extra failure reason information for the most recent
- * connection attempt, so that it may be surfaced to the settings UI
- * @hide
- */
- // TODO(b/148626966): called by SUW via reflection, remove once SUW is updated
- public static class RecentFailure {
-
- private RecentFailure() {}
-
- /**
- * Association Rejection Status code (NONE for success/non-association-rejection-fail)
- */
- @RecentFailureReason
- private int mAssociationStatus = RECENT_FAILURE_NONE;
- private long mLastUpdateTimeSinceBootMillis;
-
- /**
- * @param status the association status code for the recent failure
- */
- public void setAssociationStatus(@RecentFailureReason int status,
- long updateTimeSinceBootMs) {
- mAssociationStatus = status;
- mLastUpdateTimeSinceBootMillis = updateTimeSinceBootMs;
- }
- /**
- * Sets the RecentFailure to NONE
- */
- public void clear() {
- mAssociationStatus = RECENT_FAILURE_NONE;
- mLastUpdateTimeSinceBootMillis = 0;
- }
- /**
- * Get the recent failure code. One of {@link #RECENT_FAILURE_NONE},
- * {@link #RECENT_FAILURE_AP_UNABLE_TO_HANDLE_NEW_STA},
- * {@link #RECENT_FAILURE_MBO_OCE_DISCONNECT},
- * {@link #RECENT_FAILURE_REFUSED_TEMPORARILY},
- * {@link #RECENT_FAILURE_POOR_CHANNEL_CONDITIONS}.
- * {@link #RECENT_FAILURE_DISCONNECTION_AP_BUSY}
- */
- @RecentFailureReason
- public int getAssociationStatus() {
- return mAssociationStatus;
- }
-
- /**
- * Get the timestamp the failure status is last updated, in milliseconds since boot.
- */
- public long getLastUpdateTimeSinceBootMillis() {
- return mLastUpdateTimeSinceBootMillis;
- }
- }
-
- /**
- * RecentFailure member
- * @hide
- */
- // TODO(b/148626966): called by SUW via reflection, once SUW is updated, make private and
- // rename to mRecentFailure
- @NonNull
- public final RecentFailure recentFailure = new RecentFailure();
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = "RECENT_FAILURE_", value = {
- RECENT_FAILURE_NONE,
- RECENT_FAILURE_AP_UNABLE_TO_HANDLE_NEW_STA,
- RECENT_FAILURE_MBO_OCE_DISCONNECT,
- RECENT_FAILURE_REFUSED_TEMPORARILY,
- RECENT_FAILURE_POOR_CHANNEL_CONDITIONS,
- RECENT_FAILURE_DISCONNECTION_AP_BUSY
- })
- public @interface RecentFailureReason {}
-
- /**
- * No recent failure, or no specific reason given for the recent connection failure
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_NONE = 0;
- /**
- * Connection to this network recently failed due to Association Rejection Status 17
- * (AP is full)
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_AP_UNABLE_TO_HANDLE_NEW_STA = 17;
-
- /**
- * This network recently disconnected as a result of MBO/OCE.
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_MBO_OCE_DISCONNECT = 1001;
-
- /**
- * Failed to connect because the association is rejected by the AP.
- * IEEE 802.11 association status code 30.
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_REFUSED_TEMPORARILY = 1002;
-
- /**
- * Failed to connect because of excess frame loss and/or poor channel conditions.
- * IEEE 802.11 association status code 34.
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_POOR_CHANNEL_CONDITIONS = 1003;
-
- /**
- * Disconnected by the AP because the AP can't handle all the associated stations.
- * IEEE 802.11 disconnection reason code 5.
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_DISCONNECTION_AP_BUSY = 1004;
-
- /**
- * Get the failure reason for the most recent connection attempt, or
- * {@link #RECENT_FAILURE_NONE} if there was no failure.
- *
- * Failure reasons include:
- * {@link #RECENT_FAILURE_AP_UNABLE_TO_HANDLE_NEW_STA}
- * {@link #RECENT_FAILURE_MBO_OCE_DISCONNECT}
- * {@link #RECENT_FAILURE_REFUSED_TEMPORARILY}
- * {@link #RECENT_FAILURE_POOR_CHANNEL_CONDITIONS}
- * {@link #RECENT_FAILURE_DISCONNECTION_AP_BUSY}
- * @hide
- */
- @RecentFailureReason
- @SystemApi
- public int getRecentFailureReason() {
- return recentFailure.getAssociationStatus();
- }
-
- /**
- * Get the network selection status.
- * @hide
- */
- @NonNull
- @SystemApi
- public NetworkSelectionStatus getNetworkSelectionStatus() {
- return mNetworkSelectionStatus;
- }
-
- /**
- * Set the network selection status.
- * @hide
- */
- @SystemApi
- public void setNetworkSelectionStatus(@NonNull NetworkSelectionStatus status) {
- mNetworkSelectionStatus = status;
- }
-
- /**
- * @hide
- * Linked Configurations: represent the set of Wificonfigurations that are equivalent
- * regarding roaming and auto-joining.
- * The linked configuration may or may not have same SSID, and may or may not have same
- * credentials.
- * For instance, linked configurations will have same defaultGwMacAddress or same dhcp server.
- */
- public HashMap linkedConfigurations;
-
- public WifiConfiguration() {
- networkId = INVALID_NETWORK_ID;
- SSID = null;
- BSSID = null;
- FQDN = null;
- roamingConsortiumIds = new long[0];
- priority = 0;
- hiddenSSID = false;
- allowedKeyManagement = new BitSet();
- allowedProtocols = new BitSet();
- allowedAuthAlgorithms = new BitSet();
- allowedPairwiseCiphers = new BitSet();
- allowedGroupCiphers = new BitSet();
- allowedGroupManagementCiphers = new BitSet();
- allowedSuiteBCiphers = new BitSet();
- wepKeys = new String[4];
- for (int i = 0; i < wepKeys.length; i++) {
- wepKeys[i] = null;
- }
- enterpriseConfig = new WifiEnterpriseConfig();
- ephemeral = false;
- osu = false;
- trusted = true; // Networks are considered trusted by default.
- oemPaid = false;
- oemPrivate = false;
- carrierMerged = false;
- fromWifiNetworkSuggestion = false;
- fromWifiNetworkSpecifier = false;
- meteredHint = false;
- meteredOverride = METERED_OVERRIDE_NONE;
- useExternalScores = false;
- validatedInternetAccess = false;
- mIpConfiguration = new IpConfiguration();
- lastUpdateUid = -1;
- creatorUid = -1;
- shared = true;
- dtimInterval = 0;
- mRandomizedMacAddress = MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
- }
-
- /**
- * Identify if this configuration represents a Passpoint network
- */
- public boolean isPasspoint() {
- return !TextUtils.isEmpty(FQDN)
- && !TextUtils.isEmpty(providerFriendlyName)
- && enterpriseConfig != null
- && enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.NONE
- && !TextUtils.isEmpty(mPasspointUniqueId);
- }
-
- /**
- * Helper function, identify if a configuration is linked
- * @hide
- */
- public boolean isLinked(WifiConfiguration config) {
- if (config != null) {
- if (config.linkedConfigurations != null && linkedConfigurations != null) {
- if (config.linkedConfigurations.get(getKey()) != null
- && linkedConfigurations.get(config.getKey()) != null) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Helper function, idenfity if a configuration should be treated as an enterprise network
- * @hide
- */
- @UnsupportedAppUsage
- public boolean isEnterprise() {
- boolean hasEnterpriseSecurityType = mSecurityParamsList.stream()
- .anyMatch(params -> params.isEnterpriseSecurityType());
- return (hasEnterpriseSecurityType
- && enterpriseConfig != null
- && enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.NONE);
- }
-
- private static String logTimeOfDay(long millis) {
- Calendar c = Calendar.getInstance();
- if (millis >= 0) {
- c.setTimeInMillis(millis);
- return String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c);
- } else {
- return Long.toString(millis);
- }
- }
-
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- if (this.status == WifiConfiguration.Status.CURRENT) {
- sbuf.append("* ");
- } else if (this.status == WifiConfiguration.Status.DISABLED) {
- sbuf.append("- DSBLE ");
- }
- sbuf.append("ID: ").append(this.networkId).append(" SSID: ").append(this.SSID).
- append(" PROVIDER-NAME: ").append(this.providerFriendlyName).
- append(" BSSID: ").append(this.BSSID).append(" FQDN: ").append(this.FQDN)
- .append(" HOME-PROVIDER-NETWORK: ").append(this.isHomeProviderNetwork)
- .append(" PRIO: ").append(this.priority)
- .append(" HIDDEN: ").append(this.hiddenSSID)
- .append(" PMF: ").append(this.requirePmf)
- .append("CarrierId: ").append(this.carrierId)
- .append('\n');
-
-
- sbuf.append(" NetworkSelectionStatus ")
- .append(mNetworkSelectionStatus.getNetworkStatusString())
- .append("\n");
- if (mNetworkSelectionStatus.getNetworkSelectionDisableReason() > 0) {
- sbuf.append(" mNetworkSelectionDisableReason ")
- .append(mNetworkSelectionStatus.getNetworkSelectionDisableReasonString())
- .append("\n");
-
- for (int index = NetworkSelectionStatus.DISABLED_NONE;
- index < NetworkSelectionStatus.NETWORK_SELECTION_DISABLED_MAX; index++) {
- if (mNetworkSelectionStatus.getDisableReasonCounter(index) != 0) {
- sbuf.append(
- NetworkSelectionStatus.getNetworkSelectionDisableReasonString(index))
- .append(" counter:")
- .append(mNetworkSelectionStatus.getDisableReasonCounter(index))
- .append("\n");
- }
- }
- }
- if (mNetworkSelectionStatus.getConnectChoice() != null) {
- sbuf.append(" connect choice: ").append(mNetworkSelectionStatus.getConnectChoice());
- sbuf.append(" connect choice rssi: ")
- .append(mNetworkSelectionStatus.getConnectChoiceRssi());
- }
- sbuf.append(" hasEverConnected: ")
- .append(mNetworkSelectionStatus.hasEverConnected()).append("\n");
- sbuf.append(" hasNeverDetectedCaptivePortal: ")
- .append(mNetworkSelectionStatus.hasNeverDetectedCaptivePortal()).append("\n");
-
- if (this.numAssociation > 0) {
- sbuf.append(" numAssociation ").append(this.numAssociation).append("\n");
- }
- if (this.numNoInternetAccessReports > 0) {
- sbuf.append(" numNoInternetAccessReports ");
- sbuf.append(this.numNoInternetAccessReports).append("\n");
- }
- if (this.validatedInternetAccess) sbuf.append(" validatedInternetAccess");
- if (this.ephemeral) sbuf.append(" ephemeral");
- if (this.osu) sbuf.append(" osu");
- if (this.trusted) sbuf.append(" trusted");
- if (this.oemPaid) sbuf.append(" oemPaid");
- if (this.oemPrivate) sbuf.append(" oemPrivate");
- if (this.carrierMerged) sbuf.append(" carrierMerged");
- if (this.fromWifiNetworkSuggestion) sbuf.append(" fromWifiNetworkSuggestion");
- if (this.fromWifiNetworkSpecifier) sbuf.append(" fromWifiNetworkSpecifier");
- if (this.meteredHint) sbuf.append(" meteredHint");
- if (this.useExternalScores) sbuf.append(" useExternalScores");
- if (this.validatedInternetAccess || this.ephemeral || this.trusted || this.oemPaid
- || this.oemPrivate || this.carrierMerged || this.fromWifiNetworkSuggestion
- || this.fromWifiNetworkSpecifier || this.meteredHint || this.useExternalScores) {
- sbuf.append("\n");
- }
- if (this.meteredOverride != METERED_OVERRIDE_NONE) {
- sbuf.append(" meteredOverride ").append(meteredOverride).append("\n");
- }
- sbuf.append(" macRandomizationSetting: ").append(macRandomizationSetting).append("\n");
- sbuf.append(" mRandomizedMacAddress: ").append(mRandomizedMacAddress).append("\n");
- sbuf.append(" randomizedMacExpirationTimeMs: ")
- .append(randomizedMacExpirationTimeMs == 0 ? ""
- : logTimeOfDay(randomizedMacExpirationTimeMs)).append("\n");
- sbuf.append(" randomizedMacLastModifiedTimeMs: ")
- .append(randomizedMacLastModifiedTimeMs == 0 ? ""
- : logTimeOfDay(randomizedMacLastModifiedTimeMs)).append("\n");
- sbuf.append(" KeyMgmt:");
- for (int k = 0; k < this.allowedKeyManagement.size(); k++) {
- if (this.allowedKeyManagement.get(k)) {
- sbuf.append(" ");
- if (k < KeyMgmt.strings.length) {
- sbuf.append(KeyMgmt.strings[k]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append(" Protocols:");
- for (int p = 0; p < this.allowedProtocols.size(); p++) {
- if (this.allowedProtocols.get(p)) {
- sbuf.append(" ");
- if (p < Protocol.strings.length) {
- sbuf.append(Protocol.strings[p]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" AuthAlgorithms:");
- for (int a = 0; a < this.allowedAuthAlgorithms.size(); a++) {
- if (this.allowedAuthAlgorithms.get(a)) {
- sbuf.append(" ");
- if (a < AuthAlgorithm.strings.length) {
- sbuf.append(AuthAlgorithm.strings[a]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" PairwiseCiphers:");
- for (int pc = 0; pc < this.allowedPairwiseCiphers.size(); pc++) {
- if (this.allowedPairwiseCiphers.get(pc)) {
- sbuf.append(" ");
- if (pc < PairwiseCipher.strings.length) {
- sbuf.append(PairwiseCipher.strings[pc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" GroupCiphers:");
- for (int gc = 0; gc < this.allowedGroupCiphers.size(); gc++) {
- if (this.allowedGroupCiphers.get(gc)) {
- sbuf.append(" ");
- if (gc < GroupCipher.strings.length) {
- sbuf.append(GroupCipher.strings[gc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" GroupMgmtCiphers:");
- for (int gmc = 0; gmc < this.allowedGroupManagementCiphers.size(); gmc++) {
- if (this.allowedGroupManagementCiphers.get(gmc)) {
- sbuf.append(" ");
- if (gmc < GroupMgmtCipher.strings.length) {
- sbuf.append(GroupMgmtCipher.strings[gmc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" SuiteBCiphers:");
- for (int sbc = 0; sbc < this.allowedSuiteBCiphers.size(); sbc++) {
- if (this.allowedSuiteBCiphers.get(sbc)) {
- sbuf.append(" ");
- if (sbc < SuiteBCipher.strings.length) {
- sbuf.append(SuiteBCipher.strings[sbc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n').append(" PSK/SAE: ");
- if (this.preSharedKey != null) {
- sbuf.append('*');
- }
-
- sbuf.append("\nSecurityParams List:\n");
- mSecurityParamsList.stream()
- .forEach(params -> sbuf.append(params.toString()));
-
- sbuf.append("\nEnterprise config:\n");
- sbuf.append(enterpriseConfig);
-
- sbuf.append("IP config:\n");
- sbuf.append(mIpConfiguration.toString());
-
- if (mNetworkSelectionStatus.getNetworkSelectionBSSID() != null) {
- sbuf.append(" networkSelectionBSSID="
- + mNetworkSelectionStatus.getNetworkSelectionBSSID());
- }
- long now_ms = SystemClock.elapsedRealtime();
- if (mNetworkSelectionStatus.getDisableTime() != NetworkSelectionStatus
- .INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP) {
- sbuf.append('\n');
- long diff = now_ms - mNetworkSelectionStatus.getDisableTime();
- if (diff <= 0) {
- sbuf.append(" blackListed since ");
- } else {
- sbuf.append(" blackListed: ").append(Long.toString(diff / 1000)).append("sec ");
- }
- }
- if (creatorUid != 0) sbuf.append(" cuid=" + creatorUid);
- if (creatorName != null) sbuf.append(" cname=" + creatorName);
- if (lastUpdateUid != 0) sbuf.append(" luid=" + lastUpdateUid);
- if (lastUpdateName != null) sbuf.append(" lname=" + lastUpdateName);
- if (updateIdentifier != null) sbuf.append(" updateIdentifier=" + updateIdentifier);
- sbuf.append(" lcuid=" + lastConnectUid);
- sbuf.append(" allowAutojoin=" + allowAutojoin);
- sbuf.append(" noInternetAccessExpected=" + noInternetAccessExpected);
- sbuf.append(" mostRecentlyConnected=" + isMostRecentlyConnected);
-
- sbuf.append(" ");
-
- if (this.lastConnected != 0) {
- sbuf.append('\n');
- sbuf.append("lastConnected: ").append(logTimeOfDay(this.lastConnected));
- sbuf.append(" ");
- }
- sbuf.append('\n');
- if (this.linkedConfigurations != null) {
- for (String key : this.linkedConfigurations.keySet()) {
- sbuf.append(" linked: ").append(key);
- sbuf.append('\n');
- }
- }
- sbuf.append("recentFailure: ").append("Association Rejection code: ")
- .append(recentFailure.getAssociationStatus()).append(", last update time: ")
- .append(recentFailure.getLastUpdateTimeSinceBootMillis()).append("\n");
- return sbuf.toString();
- }
-
- /**
- * Get the SSID in a human-readable format, with all additional formatting removed
- * e.g. quotation marks around the SSID, "P" prefix
- * @hide
- */
- @NonNull
- @SystemApi
- public String getPrintableSsid() {
- if (SSID == null) return "";
- final int length = SSID.length();
- if (length > 2 && (SSID.charAt(0) == '"') && SSID.charAt(length - 1) == '"') {
- return SSID.substring(1, length - 1);
- }
-
- /* The ascii-encoded string format is P""
- * The decoding is implemented in the supplicant for a newly configured
- * network.
- */
- if (length > 3 && (SSID.charAt(0) == 'P') && (SSID.charAt(1) == '"') &&
- (SSID.charAt(length-1) == '"')) {
- WifiSsid wifiSsid = WifiSsid.createFromAsciiEncoded(
- SSID.substring(2, length - 1));
- return wifiSsid.toString();
- }
- return SSID;
- }
-
- /**
- * Get an identifier for associating credentials with this config
- * @param current configuration contains values for additional fields
- * that are not part of this configuration. Used
- * when a config with some fields is passed by an application.
- * @throws IllegalStateException if config is invalid for key id generation
- * @hide
- */
- public String getKeyIdForCredentials(WifiConfiguration current) {
- String keyMgmt = "";
-
- try {
- // Get current config details for fields that are not initialized
- if (TextUtils.isEmpty(SSID)) SSID = current.SSID;
- if (allowedKeyManagement.cardinality() == 0) {
- allowedKeyManagement = current.allowedKeyManagement;
- }
- if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
- keyMgmt += KeyMgmt.strings[KeyMgmt.WPA_EAP];
- }
- if (allowedKeyManagement.get(KeyMgmt.OSEN)) {
- keyMgmt += KeyMgmt.strings[KeyMgmt.OSEN];
- }
- if (allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
- keyMgmt += KeyMgmt.strings[KeyMgmt.IEEE8021X];
- }
- if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- keyMgmt += KeyMgmt.strings[KeyMgmt.SUITE_B_192];
- }
- if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
- keyMgmt += KeyMgmt.strings[KeyMgmt.WAPI_CERT];
- }
-
- if (TextUtils.isEmpty(keyMgmt)) {
- throw new IllegalStateException("Not an EAP network");
- }
- String keyId = trimStringForKeyId(SSID) + "_" + keyMgmt + "_"
- + trimStringForKeyId(enterpriseConfig.getKeyId(current != null
- ? current.enterpriseConfig : null));
-
- if (!fromWifiNetworkSuggestion) {
- return keyId;
- }
- return keyId + "_" + trimStringForKeyId(BSSID) + "_" + trimStringForKeyId(creatorName);
- } catch (NullPointerException e) {
- throw new IllegalStateException("Invalid config details");
- }
- }
-
- private String trimStringForKeyId(String string) {
- if (string == null) {
- return "";
- }
- // Remove quotes and spaces
- return string.replace("\"", "").replace(" ", "");
- }
-
- private static BitSet readBitSet(Parcel src) {
- int cardinality = src.readInt();
-
- BitSet set = new BitSet();
- for (int i = 0; i < cardinality; i++) {
- set.set(src.readInt());
- }
-
- return set;
- }
-
- private static void writeBitSet(Parcel dest, BitSet set) {
- int nextSetBit = -1;
-
- dest.writeInt(set.cardinality());
-
- while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
- dest.writeInt(nextSetBit);
- }
- }
-
- /**
- * Get the authentication type of the network.
- * @return One of the {@link KeyMgmt} constants. e.g. {@link KeyMgmt#WPA2_PSK}.
- * @hide
- */
- @SystemApi
- @KeyMgmt.KeyMgmtScheme
- public int getAuthType() {
- if (allowedKeyManagement.cardinality() > 1) {
- if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
- if (allowedKeyManagement.cardinality() == 2
- && allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
- return KeyMgmt.WPA_EAP;
- }
- if (allowedKeyManagement.cardinality() == 3
- && allowedKeyManagement.get(KeyMgmt.IEEE8021X)
- && allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- return KeyMgmt.SUITE_B_192;
- }
- }
- throw new IllegalStateException("Invalid auth type set: " + allowedKeyManagement);
- }
- if (allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
- return KeyMgmt.WPA_PSK;
- } else if (allowedKeyManagement.get(KeyMgmt.WPA2_PSK)) {
- return KeyMgmt.WPA2_PSK;
- } else if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
- return KeyMgmt.WPA_EAP;
- } else if (allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
- return KeyMgmt.IEEE8021X;
- } else if (allowedKeyManagement.get(KeyMgmt.SAE)) {
- return KeyMgmt.SAE;
- } else if (allowedKeyManagement.get(KeyMgmt.OWE)) {
- return KeyMgmt.OWE;
- } else if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- return KeyMgmt.SUITE_B_192;
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_PSK)) {
- return KeyMgmt.WAPI_PSK;
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
- return KeyMgmt.WAPI_CERT;
- }
- return KeyMgmt.NONE;
- }
-
- /**
- * Return a String that can be used to uniquely identify this WifiConfiguration.
- *
- * Note: Do not persist this value! This value is not guaranteed to remain backwards compatible.
- */
- @NonNull
- public String getKey() {
- // Passpoint ephemeral networks have their unique identifier set. Return it as is to be
- // able to match internally.
- if (mPasspointUniqueId != null) {
- return mPasspointUniqueId;
- }
-
- String key = getSsidAndSecurityTypeString();
- if (!shared) {
- key += "-" + UserHandle.getUserHandleForUid(creatorUid).getIdentifier();
- }
-
- return key;
- }
-
- /**
- * Get a unique key which represent this Wi-Fi network. If two profiles are for
- * the same Wi-Fi network, but from different provider, they would have the same key.
- * @hide
- */
- public String getNetworkKey() {
- // Passpoint ephemeral networks have their unique identifier set. Return it as is to be
- // able to match internally.
- if (mPasspointUniqueId != null) {
- return mPasspointUniqueId;
- }
-
- String key = SSID + getDefaultSecurityType();
- if (!shared) {
- key += "-" + UserHandle.getUserHandleForUid(creatorUid).getIdentifier();
- }
-
- return key;
- }
-
- /** @hide
- * return the SSID + security type in String format.
- */
- public String getSsidAndSecurityTypeString() {
- String key;
- if (allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.WPA_PSK];
- } else if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)
- || allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.WPA_EAP];
- } else if (wepTxKeyIndex >= 0 && wepTxKeyIndex < wepKeys.length
- && wepKeys[wepTxKeyIndex] != null) {
- key = SSID + "WEP";
- } else if (allowedKeyManagement.get(KeyMgmt.OWE)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.OWE];
- } else if (allowedKeyManagement.get(KeyMgmt.SAE)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.SAE];
- } else if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.SUITE_B_192];
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_PSK)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.WAPI_PSK];
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.WAPI_CERT];
- } else if (allowedKeyManagement.get(KeyMgmt.OSEN)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.OSEN];
- } else {
- key = SSID + KeyMgmt.strings[KeyMgmt.NONE];
- }
- return key;
- }
-
- /**
- * Get the IpConfiguration object associated with this WifiConfiguration.
- * @hide
- */
- @NonNull
- @SystemApi
- public IpConfiguration getIpConfiguration() {
- return new IpConfiguration(mIpConfiguration);
- }
-
- /**
- * Set the {@link IpConfiguration} for this network.
- * @param ipConfiguration the {@link IpConfiguration} to set, or null to use the default
- * constructor {@link IpConfiguration#IpConfiguration()}.
- * @hide
- */
- @SystemApi
- public void setIpConfiguration(@Nullable IpConfiguration ipConfiguration) {
- if (ipConfiguration == null) ipConfiguration = new IpConfiguration();
- mIpConfiguration = ipConfiguration;
- }
-
- /**
- * Get the {@link StaticIpConfiguration} for this network.
- * @return the {@link StaticIpConfiguration}, or null if unset.
- * @hide
- */
- @Nullable
- @UnsupportedAppUsage
- public StaticIpConfiguration getStaticIpConfiguration() {
- return mIpConfiguration.getStaticIpConfiguration();
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setStaticIpConfiguration(StaticIpConfiguration staticIpConfiguration) {
- mIpConfiguration.setStaticIpConfiguration(staticIpConfiguration);
- }
-
- /**
- * Get the {@link IpConfiguration.IpAssignment} for this network.
- * @hide
- */
- @NonNull
- @UnsupportedAppUsage
- public IpConfiguration.IpAssignment getIpAssignment() {
- return mIpConfiguration.getIpAssignment();
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setIpAssignment(IpConfiguration.IpAssignment ipAssignment) {
- mIpConfiguration.setIpAssignment(ipAssignment);
- }
-
- /**
- * Get the {@link IpConfiguration.ProxySettings} for this network.
- * @hide
- */
- @NonNull
- @UnsupportedAppUsage
- public IpConfiguration.ProxySettings getProxySettings() {
- return mIpConfiguration.getProxySettings();
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setProxySettings(IpConfiguration.ProxySettings proxySettings) {
- mIpConfiguration.setProxySettings(proxySettings);
- }
-
- /**
- * Returns the HTTP proxy used by this object.
- * @return a {@link ProxyInfo httpProxy} representing the proxy specified by this
- * WifiConfiguration, or {@code null} if no proxy is specified.
- */
- public ProxyInfo getHttpProxy() {
- if (mIpConfiguration.getProxySettings() == IpConfiguration.ProxySettings.NONE) {
- return null;
- }
- return new ProxyInfo(mIpConfiguration.getHttpProxy());
- }
-
- /**
- * Set the {@link ProxyInfo} for this WifiConfiguration. This method should only be used by a
- * device owner or profile owner. When other apps attempt to save a {@link WifiConfiguration}
- * with modified proxy settings, the methods {@link WifiManager#addNetwork} and
- * {@link WifiManager#updateNetwork} fail and return {@code -1}.
- *
- * @param httpProxy {@link ProxyInfo} representing the httpProxy to be used by this
- * WifiConfiguration. Setting this to {@code null} will explicitly set no
- * proxy, removing any proxy that was previously set.
- * @exception IllegalArgumentException for invalid httpProxy
- */
- public void setHttpProxy(ProxyInfo httpProxy) {
- if (httpProxy == null) {
- mIpConfiguration.setProxySettings(IpConfiguration.ProxySettings.NONE);
- mIpConfiguration.setHttpProxy(null);
- return;
- }
- ProxyInfo httpProxyCopy;
- ProxySettings proxySettingCopy;
- if (!Uri.EMPTY.equals(httpProxy.getPacFileUrl())) {
- proxySettingCopy = IpConfiguration.ProxySettings.PAC;
- // Construct a new PAC URL Proxy
- httpProxyCopy = ProxyInfo.buildPacProxy(httpProxy.getPacFileUrl(), httpProxy.getPort());
- } else {
- proxySettingCopy = IpConfiguration.ProxySettings.STATIC;
- // Construct a new HTTP Proxy
- httpProxyCopy = ProxyInfo.buildDirectProxy(httpProxy.getHost(), httpProxy.getPort(),
- Arrays.asList(httpProxy.getExclusionList()));
- }
- if (!httpProxyCopy.isValid()) {
- throw new IllegalArgumentException("Invalid ProxyInfo: " + httpProxyCopy.toString());
- }
- mIpConfiguration.setProxySettings(proxySettingCopy);
- mIpConfiguration.setHttpProxy(httpProxyCopy);
- }
-
- /**
- * Set the {@link ProxySettings} and {@link ProxyInfo} for this network.
- * @hide
- */
- @UnsupportedAppUsage
- public void setProxy(@NonNull ProxySettings settings, @NonNull ProxyInfo proxy) {
- mIpConfiguration.setProxySettings(settings);
- mIpConfiguration.setHttpProxy(proxy);
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** @hide */
- public void setPasspointManagementObjectTree(String passpointManagementObjectTree) {
- mPasspointManagementObjectTree = passpointManagementObjectTree;
- }
-
- /** @hide */
- public String getMoTree() {
- return mPasspointManagementObjectTree;
- }
-
- /** Copy constructor */
- public WifiConfiguration(@NonNull WifiConfiguration source) {
- if (source != null) {
- networkId = source.networkId;
- status = source.status;
- SSID = source.SSID;
- BSSID = source.BSSID;
- FQDN = source.FQDN;
- roamingConsortiumIds = source.roamingConsortiumIds.clone();
- providerFriendlyName = source.providerFriendlyName;
- isHomeProviderNetwork = source.isHomeProviderNetwork;
- preSharedKey = source.preSharedKey;
-
- mNetworkSelectionStatus.copy(source.getNetworkSelectionStatus());
- apBand = source.apBand;
- apChannel = source.apChannel;
-
- wepKeys = new String[4];
- for (int i = 0; i < wepKeys.length; i++) {
- wepKeys[i] = source.wepKeys[i];
- }
-
- wepTxKeyIndex = source.wepTxKeyIndex;
- priority = source.priority;
- hiddenSSID = source.hiddenSSID;
- allowedKeyManagement = (BitSet) source.allowedKeyManagement.clone();
- allowedProtocols = (BitSet) source.allowedProtocols.clone();
- allowedAuthAlgorithms = (BitSet) source.allowedAuthAlgorithms.clone();
- allowedPairwiseCiphers = (BitSet) source.allowedPairwiseCiphers.clone();
- allowedGroupCiphers = (BitSet) source.allowedGroupCiphers.clone();
- allowedGroupManagementCiphers = (BitSet) source.allowedGroupManagementCiphers.clone();
- allowedSuiteBCiphers = (BitSet) source.allowedSuiteBCiphers.clone();
- mSecurityParamsList = new ArrayList(source.mSecurityParamsList);
- enterpriseConfig = new WifiEnterpriseConfig(source.enterpriseConfig);
-
- defaultGwMacAddress = source.defaultGwMacAddress;
-
- mIpConfiguration = new IpConfiguration(source.mIpConfiguration);
-
- if ((source.linkedConfigurations != null)
- && (source.linkedConfigurations.size() > 0)) {
- linkedConfigurations = new HashMap();
- linkedConfigurations.putAll(source.linkedConfigurations);
- }
- validatedInternetAccess = source.validatedInternetAccess;
- isLegacyPasspointConfig = source.isLegacyPasspointConfig;
- ephemeral = source.ephemeral;
- osu = source.osu;
- trusted = source.trusted;
- oemPaid = source.oemPaid;
- oemPrivate = source.oemPrivate;
- carrierMerged = source.carrierMerged;
- fromWifiNetworkSuggestion = source.fromWifiNetworkSuggestion;
- fromWifiNetworkSpecifier = source.fromWifiNetworkSpecifier;
- meteredHint = source.meteredHint;
- meteredOverride = source.meteredOverride;
- useExternalScores = source.useExternalScores;
-
- lastConnectUid = source.lastConnectUid;
- lastUpdateUid = source.lastUpdateUid;
- creatorUid = source.creatorUid;
- creatorName = source.creatorName;
- lastUpdateName = source.lastUpdateName;
- peerWifiConfiguration = source.peerWifiConfiguration;
-
- lastConnected = source.lastConnected;
- lastDisconnected = source.lastDisconnected;
- numScorerOverride = source.numScorerOverride;
- numScorerOverrideAndSwitchedNetwork = source.numScorerOverrideAndSwitchedNetwork;
- numAssociation = source.numAssociation;
- allowAutojoin = source.allowAutojoin;
- numNoInternetAccessReports = source.numNoInternetAccessReports;
- noInternetAccessExpected = source.noInternetAccessExpected;
- shared = source.shared;
- recentFailure.setAssociationStatus(source.recentFailure.getAssociationStatus(),
- source.recentFailure.getLastUpdateTimeSinceBootMillis());
- mRandomizedMacAddress = source.mRandomizedMacAddress;
- macRandomizationSetting = source.macRandomizationSetting;
- randomizedMacExpirationTimeMs = source.randomizedMacExpirationTimeMs;
- randomizedMacLastModifiedTimeMs = source.randomizedMacLastModifiedTimeMs;
- requirePmf = source.requirePmf;
- updateIdentifier = source.updateIdentifier;
- carrierId = source.carrierId;
- subscriptionId = source.subscriptionId;
- mPasspointUniqueId = source.mPasspointUniqueId;
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(networkId);
- dest.writeInt(status);
- mNetworkSelectionStatus.writeToParcel(dest);
- dest.writeString(SSID);
- dest.writeString(BSSID);
- dest.writeInt(apBand);
- dest.writeInt(apChannel);
- dest.writeString(FQDN);
- dest.writeString(providerFriendlyName);
- dest.writeInt(isHomeProviderNetwork ? 1 : 0);
- dest.writeInt(roamingConsortiumIds.length);
- for (long roamingConsortiumId : roamingConsortiumIds) {
- dest.writeLong(roamingConsortiumId);
- }
- dest.writeString(preSharedKey);
- for (String wepKey : wepKeys) {
- dest.writeString(wepKey);
- }
- dest.writeInt(wepTxKeyIndex);
- dest.writeInt(priority);
- dest.writeInt(hiddenSSID ? 1 : 0);
- dest.writeInt(requirePmf ? 1 : 0);
- dest.writeString(updateIdentifier);
-
- writeBitSet(dest, allowedKeyManagement);
- writeBitSet(dest, allowedProtocols);
- writeBitSet(dest, allowedAuthAlgorithms);
- writeBitSet(dest, allowedPairwiseCiphers);
- writeBitSet(dest, allowedGroupCiphers);
- writeBitSet(dest, allowedGroupManagementCiphers);
- writeBitSet(dest, allowedSuiteBCiphers);
-
- dest.writeInt(mSecurityParamsList.size());
- mSecurityParamsList.stream()
- .forEach(params -> params.writeToParcel(dest, flags));
-
- dest.writeParcelable(enterpriseConfig, flags);
-
- dest.writeParcelable(mIpConfiguration, flags);
- dest.writeString(dhcpServer);
- dest.writeString(defaultGwMacAddress);
- dest.writeInt(validatedInternetAccess ? 1 : 0);
- dest.writeInt(isLegacyPasspointConfig ? 1 : 0);
- dest.writeInt(ephemeral ? 1 : 0);
- dest.writeInt(trusted ? 1 : 0);
- dest.writeInt(oemPaid ? 1 : 0);
- dest.writeInt(oemPrivate ? 1 : 0);
- dest.writeInt(carrierMerged ? 1 : 0);
- dest.writeInt(fromWifiNetworkSuggestion ? 1 : 0);
- dest.writeInt(fromWifiNetworkSpecifier ? 1 : 0);
- dest.writeInt(meteredHint ? 1 : 0);
- dest.writeInt(meteredOverride);
- dest.writeInt(useExternalScores ? 1 : 0);
- dest.writeInt(creatorUid);
- dest.writeInt(lastConnectUid);
- dest.writeInt(lastUpdateUid);
- dest.writeString(creatorName);
- dest.writeString(lastUpdateName);
- dest.writeInt(numScorerOverride);
- dest.writeInt(numScorerOverrideAndSwitchedNetwork);
- dest.writeInt(numAssociation);
- dest.writeBoolean(allowAutojoin);
- dest.writeInt(numNoInternetAccessReports);
- dest.writeInt(noInternetAccessExpected ? 1 : 0);
- dest.writeInt(shared ? 1 : 0);
- dest.writeString(mPasspointManagementObjectTree);
- dest.writeInt(recentFailure.getAssociationStatus());
- dest.writeLong(recentFailure.getLastUpdateTimeSinceBootMillis());
- dest.writeParcelable(mRandomizedMacAddress, flags);
- dest.writeInt(macRandomizationSetting);
- dest.writeInt(osu ? 1 : 0);
- dest.writeLong(randomizedMacExpirationTimeMs);
- dest.writeLong(randomizedMacLastModifiedTimeMs);
- dest.writeInt(carrierId);
- dest.writeString(mPasspointUniqueId);
- dest.writeInt(subscriptionId);
- }
-
- /** Implement the Parcelable interface {@hide} */
- @UnsupportedAppUsage
- public static final @android.annotation.NonNull Creator CREATOR =
- new Creator() {
- public WifiConfiguration createFromParcel(Parcel in) {
- WifiConfiguration config = new WifiConfiguration();
- config.networkId = in.readInt();
- config.status = in.readInt();
- config.mNetworkSelectionStatus.readFromParcel(in);
- config.SSID = in.readString();
- config.BSSID = in.readString();
- config.apBand = in.readInt();
- config.apChannel = in.readInt();
- config.FQDN = in.readString();
- config.providerFriendlyName = in.readString();
- config.isHomeProviderNetwork = in.readInt() != 0;
- int numRoamingConsortiumIds = in.readInt();
- config.roamingConsortiumIds = new long[numRoamingConsortiumIds];
- for (int i = 0; i < numRoamingConsortiumIds; i++) {
- config.roamingConsortiumIds[i] = in.readLong();
- }
- config.preSharedKey = in.readString();
- for (int i = 0; i < config.wepKeys.length; i++) {
- config.wepKeys[i] = in.readString();
- }
- config.wepTxKeyIndex = in.readInt();
- config.priority = in.readInt();
- config.hiddenSSID = in.readInt() != 0;
- config.requirePmf = in.readInt() != 0;
- config.updateIdentifier = in.readString();
-
- config.allowedKeyManagement = readBitSet(in);
- config.allowedProtocols = readBitSet(in);
- config.allowedAuthAlgorithms = readBitSet(in);
- config.allowedPairwiseCiphers = readBitSet(in);
- config.allowedGroupCiphers = readBitSet(in);
- config.allowedGroupManagementCiphers = readBitSet(in);
- config.allowedSuiteBCiphers = readBitSet(in);
-
- int numSecurityParams = in.readInt();
- for (int i = 0; i < numSecurityParams; i++) {
- config.mSecurityParamsList.add(SecurityParams.createFromParcel(in));
- }
-
- config.enterpriseConfig = in.readParcelable(null);
- config.setIpConfiguration(in.readParcelable(null));
- config.dhcpServer = in.readString();
- config.defaultGwMacAddress = in.readString();
- config.validatedInternetAccess = in.readInt() != 0;
- config.isLegacyPasspointConfig = in.readInt() != 0;
- config.ephemeral = in.readInt() != 0;
- config.trusted = in.readInt() != 0;
- config.oemPaid = in.readInt() != 0;
- config.oemPrivate = in.readInt() != 0;
- config.carrierMerged = in.readInt() != 0;
- config.fromWifiNetworkSuggestion = in.readInt() != 0;
- config.fromWifiNetworkSpecifier = in.readInt() != 0;
- config.meteredHint = in.readInt() != 0;
- config.meteredOverride = in.readInt();
- config.useExternalScores = in.readInt() != 0;
- config.creatorUid = in.readInt();
- config.lastConnectUid = in.readInt();
- config.lastUpdateUid = in.readInt();
- config.creatorName = in.readString();
- config.lastUpdateName = in.readString();
- config.numScorerOverride = in.readInt();
- config.numScorerOverrideAndSwitchedNetwork = in.readInt();
- config.numAssociation = in.readInt();
- config.allowAutojoin = in.readBoolean();
- config.numNoInternetAccessReports = in.readInt();
- config.noInternetAccessExpected = in.readInt() != 0;
- config.shared = in.readInt() != 0;
- config.mPasspointManagementObjectTree = in.readString();
- config.recentFailure.setAssociationStatus(in.readInt(), in.readLong());
- config.mRandomizedMacAddress = in.readParcelable(null);
- config.macRandomizationSetting = in.readInt();
- config.osu = in.readInt() != 0;
- config.randomizedMacExpirationTimeMs = in.readLong();
- config.randomizedMacLastModifiedTimeMs = in.readLong();
- config.carrierId = in.readInt();
- config.mPasspointUniqueId = in.readString();
- config.subscriptionId = in.readInt();
- return config;
- }
-
- public WifiConfiguration[] newArray(int size) {
- return new WifiConfiguration[size];
- }
- };
-
- /**
- * Passpoint Unique identifier
- * @hide
- */
- private String mPasspointUniqueId = null;
-
- /**
- * Set the Passpoint unique identifier
- * @param uniqueId Passpoint unique identifier to be set
- * @hide
- */
- public void setPasspointUniqueId(String uniqueId) {
- mPasspointUniqueId = uniqueId;
- }
-
- /**
- * Set the Passpoint unique identifier
- * @hide
- */
- public String getPasspointUniqueId() {
- return mPasspointUniqueId;
- }
-
- /**
- * If network is one of the most recently connected.
- * For framework internal use only. Do not parcel.
- * @hide
- */
- public boolean isMostRecentlyConnected = false;
-
- /**
- * Whether the key mgmt indicates if the WifiConfiguration needs a preSharedKey or not.
- * @return true if preSharedKey is needed, false otherwise.
- * @hide
- */
- public boolean needsPreSharedKey() {
- return mSecurityParamsList.stream()
- .anyMatch(params -> params.isSecurityType(SECURITY_TYPE_PSK)
- || params.isSecurityType(SECURITY_TYPE_SAE)
- || params.isSecurityType(SECURITY_TYPE_WAPI_PSK));
- }
-
- /**
- * Get a unique key which represent this Wi-Fi configuration profile. If two profiles are for
- * the same Wi-Fi network, but from different providers (apps, carriers, or data subscriptions),
- * they would have different keys.
- * @return a unique key which represent this profile.
- * @hide
- */
- @SystemApi
- @NonNull public String getProfileKey() {
- if (mPasspointUniqueId != null) {
- return mPasspointUniqueId;
- }
-
- String key = SSID + getDefaultSecurityType();
- if (!shared) {
- key += "-" + UserHandle.getUserHandleForUid(creatorUid).getIdentifier();
- }
- if (fromWifiNetworkSuggestion) {
- key += "_" + creatorName + "-" + carrierId + "-" + subscriptionId;
- }
-
- return key;
- }
-
- /**
- * Get the default security type string.
- * @hide
- */
- public String getDefaultSecurityType() {
- String key;
- if (allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
- key = KeyMgmt.strings[KeyMgmt.WPA_PSK];
- } else if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)
- || allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
- key = KeyMgmt.strings[KeyMgmt.WPA_EAP];
- } else if (wepTxKeyIndex >= 0 && wepTxKeyIndex < wepKeys.length
- && wepKeys[wepTxKeyIndex] != null) {
- key = "WEP";
- } else if (allowedKeyManagement.get(KeyMgmt.OWE)) {
- key = KeyMgmt.strings[KeyMgmt.OWE];
- } else if (allowedKeyManagement.get(KeyMgmt.SAE)) {
- key = KeyMgmt.strings[KeyMgmt.SAE];
- } else if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- key = KeyMgmt.strings[KeyMgmt.SUITE_B_192];
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_PSK)) {
- key = KeyMgmt.strings[KeyMgmt.WAPI_PSK];
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
- key = KeyMgmt.strings[KeyMgmt.WAPI_CERT];
- } else if (allowedKeyManagement.get(KeyMgmt.OSEN)) {
- key = KeyMgmt.strings[KeyMgmt.OSEN];
- } else {
- key = KeyMgmt.strings[KeyMgmt.NONE];
- }
- return key;
- }
-
-}
diff --git a/wifi/java/android/net/wifi/WifiEnterpriseConfig.java b/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
deleted file mode 100644
index e127ea99c716b..0000000000000
--- a/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
+++ /dev/null
@@ -1,1514 +0,0 @@
-/*
- * Copyright (C) 2013 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 android.net.wifi;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.nio.charset.StandardCharsets;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-import java.security.interfaces.ECPublicKey;
-import java.security.interfaces.RSAPublicKey;
-import java.security.spec.ECParameterSpec;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Enterprise configuration details for Wi-Fi. Stores details about the EAP method
- * and any associated credentials.
- */
-public class WifiEnterpriseConfig implements Parcelable {
-
- /** Key prefix for WAPI AS certificates. */
- public static final String WAPI_AS_CERTIFICATE = "WAPIAS_";
-
- /** Key prefix for WAPI user certificates. */
- public static final String WAPI_USER_CERTIFICATE = "WAPIUSR_";
-
- /**
- * Intent extra: name for WAPI AS certificates
- */
- public static final String EXTRA_WAPI_AS_CERTIFICATE_NAME =
- "android.net.wifi.extra.WAPI_AS_CERTIFICATE_NAME";
-
- /**
- * Intent extra: data for WAPI AS certificates
- */
- public static final String EXTRA_WAPI_AS_CERTIFICATE_DATA =
- "android.net.wifi.extra.WAPI_AS_CERTIFICATE_DATA";
-
- /**
- * Intent extra: name for WAPI USER certificates
- */
- public static final String EXTRA_WAPI_USER_CERTIFICATE_NAME =
- "android.net.wifi.extra.WAPI_USER_CERTIFICATE_NAME";
-
- /**
- * Intent extra: data for WAPI USER certificates
- */
- public static final String EXTRA_WAPI_USER_CERTIFICATE_DATA =
- "android.net.wifi.extra.WAPI_USER_CERTIFICATE_DATA";
-
- /** @hide */
- public static final String EMPTY_VALUE = "NULL";
- /** @hide */
- public static final String EAP_KEY = "eap";
- /** @hide */
- public static final String PHASE2_KEY = "phase2";
- /** @hide */
- public static final String IDENTITY_KEY = "identity";
- /** @hide */
- public static final String ANON_IDENTITY_KEY = "anonymous_identity";
- /** @hide */
- public static final String PASSWORD_KEY = "password";
- /** @hide */
- public static final String SUBJECT_MATCH_KEY = "subject_match";
- /** @hide */
- public static final String ALTSUBJECT_MATCH_KEY = "altsubject_match";
- /** @hide */
- public static final String DOM_SUFFIX_MATCH_KEY = "domain_suffix_match";
- /** @hide */
- public static final String OPP_KEY_CACHING = "proactive_key_caching";
- /** @hide */
- public static final String EAP_ERP = "eap_erp";
- /** @hide */
- public static final String OCSP = "ocsp";
-
- /**
- * String representing the keystore OpenSSL ENGINE's ID.
- * @hide
- */
- public static final String ENGINE_ID_KEYSTORE = "keystore";
-
- /**
- * String representing the keystore URI used for wpa_supplicant.
- * @hide
- */
- public static final String KEYSTORE_URI = "keystore://";
-
- /**
- * String representing the keystore URI used for wpa_supplicant,
- * Unlike #KEYSTORE_URI, this supports a list of space-delimited aliases
- * @hide
- */
- public static final String KEYSTORES_URI = "keystores://";
-
- /**
- * String to set the engine value to when it should be enabled.
- * @hide
- */
- public static final String ENGINE_ENABLE = "1";
-
- /**
- * String to set the engine value to when it should be disabled.
- * @hide
- */
- public static final String ENGINE_DISABLE = "0";
-
- /**
- * Key prefix for CA certificates.
- * Note: copied from {@link android.security.Credentials#CA_CERTIFICATE} since it is @hide.
- */
- private static final String CA_CERTIFICATE = "CACERT_";
- /**
- * Key prefix for user certificates.
- * Note: copied from {@link android.security.Credentials#USER_CERTIFICATE} since it is @hide.
- */
- private static final String USER_CERTIFICATE = "USRCERT_";
- /**
- * Key prefix for user private and secret keys.
- * Note: copied from {@link android.security.Credentials#USER_PRIVATE_KEY} since it is @hide.
- */
- private static final String USER_PRIVATE_KEY = "USRPKEY_";
-
- /** @hide */
- public static final String CA_CERT_PREFIX = KEYSTORE_URI + CA_CERTIFICATE;
- /** @hide */
- public static final String CLIENT_CERT_PREFIX = KEYSTORE_URI + USER_CERTIFICATE;
- /** @hide */
- public static final String CLIENT_CERT_KEY = "client_cert";
- /** @hide */
- public static final String CA_CERT_KEY = "ca_cert";
- /** @hide */
- public static final String CA_PATH_KEY = "ca_path";
- /** @hide */
- public static final String ENGINE_KEY = "engine";
- /** @hide */
- public static final String ENGINE_ID_KEY = "engine_id";
- /** @hide */
- public static final String PRIVATE_KEY_ID_KEY = "key_id";
- /** @hide */
- public static final String REALM_KEY = "realm";
- /** @hide */
- public static final String PLMN_KEY = "plmn";
- /** @hide */
- public static final String CA_CERT_ALIAS_DELIMITER = " ";
- /** @hide */
- public static final String WAPI_CERT_SUITE_KEY = "wapi_cert_suite";
-
- /**
- * Do not use OCSP stapling (TLS certificate status extension)
- * @hide
- */
- @SystemApi
- public static final int OCSP_NONE = 0;
-
- /**
- * Try to use OCSP stapling, but not require response
- * @hide
- */
- @SystemApi
- public static final int OCSP_REQUEST_CERT_STATUS = 1;
-
- /**
- * Require valid OCSP stapling response
- * @hide
- */
- @SystemApi
- public static final int OCSP_REQUIRE_CERT_STATUS = 2;
-
- /**
- * Require valid OCSP stapling response for all not-trusted certificates in the server
- * certificate chain
- * @hide
- */
- @SystemApi
- public static final int OCSP_REQUIRE_ALL_NON_TRUSTED_CERTS_STATUS = 3;
-
- /** @hide */
- @IntDef(prefix = {"OCSP_"}, value = {
- OCSP_NONE,
- OCSP_REQUEST_CERT_STATUS,
- OCSP_REQUIRE_CERT_STATUS,
- OCSP_REQUIRE_ALL_NON_TRUSTED_CERTS_STATUS
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface Ocsp {}
-
- /**
- * Whether to use/require OCSP (Online Certificate Status Protocol) to check server certificate.
- * @hide
- */
- private @Ocsp int mOcsp = OCSP_NONE;
-
- // Fields to copy verbatim from wpa_supplicant.
- private static final String[] SUPPLICANT_CONFIG_KEYS = new String[] {
- IDENTITY_KEY,
- ANON_IDENTITY_KEY,
- PASSWORD_KEY,
- CLIENT_CERT_KEY,
- CA_CERT_KEY,
- SUBJECT_MATCH_KEY,
- ENGINE_KEY,
- ENGINE_ID_KEY,
- PRIVATE_KEY_ID_KEY,
- ALTSUBJECT_MATCH_KEY,
- DOM_SUFFIX_MATCH_KEY,
- CA_PATH_KEY
- };
-
- /**
- * Fields that have unquoted values in {@link #mFields}.
- */
- private static final List UNQUOTED_KEYS = Arrays.asList(ENGINE_KEY, OPP_KEY_CACHING,
- EAP_ERP);
-
- @UnsupportedAppUsage
- private HashMap mFields = new HashMap();
- private X509Certificate[] mCaCerts;
- private PrivateKey mClientPrivateKey;
- private X509Certificate[] mClientCertificateChain;
- private int mEapMethod = Eap.NONE;
- private int mPhase2Method = Phase2.NONE;
- private boolean mIsAppInstalledDeviceKeyAndCert = false;
- private boolean mIsAppInstalledCaCert = false;
-
- private static final String TAG = "WifiEnterpriseConfig";
-
- public WifiEnterpriseConfig() {
- // Do not set defaults so that the enterprise fields that are not changed
- // by API are not changed underneath
- // This is essential because an app may not have all fields like password
- // available. It allows modification of subset of fields.
-
- }
-
- /**
- * Copy over the contents of the source WifiEnterpriseConfig object over to this object.
- *
- * @param source Source WifiEnterpriseConfig object.
- * @param ignoreMaskedPassword Set to true to ignore masked password field, false otherwise.
- * @param mask if |ignoreMaskedPassword| is set, check if the incoming password field is set
- * to this value.
- */
- private void copyFrom(WifiEnterpriseConfig source, boolean ignoreMaskedPassword, String mask) {
- for (String key : source.mFields.keySet()) {
- if (ignoreMaskedPassword && key.equals(PASSWORD_KEY)
- && TextUtils.equals(source.mFields.get(key), mask)) {
- continue;
- }
- mFields.put(key, source.mFields.get(key));
- }
- if (source.mCaCerts != null) {
- mCaCerts = Arrays.copyOf(source.mCaCerts, source.mCaCerts.length);
- } else {
- mCaCerts = null;
- }
- mClientPrivateKey = source.mClientPrivateKey;
- if (source.mClientCertificateChain != null) {
- mClientCertificateChain = Arrays.copyOf(
- source.mClientCertificateChain,
- source.mClientCertificateChain.length);
- } else {
- mClientCertificateChain = null;
- }
- mEapMethod = source.mEapMethod;
- mPhase2Method = source.mPhase2Method;
- mIsAppInstalledDeviceKeyAndCert = source.mIsAppInstalledDeviceKeyAndCert;
- mIsAppInstalledCaCert = source.mIsAppInstalledCaCert;
- mOcsp = source.mOcsp;
- }
-
- /**
- * Copy constructor.
- * This copies over all the fields verbatim (does not ignore masked password fields).
- *
- * @param source Source WifiEnterpriseConfig object.
- */
- public WifiEnterpriseConfig(WifiEnterpriseConfig source) {
- copyFrom(source, false, "");
- }
-
- /**
- * Copy fields from the provided external WifiEnterpriseConfig.
- * This is needed to handle the WifiEnterpriseConfig objects which were sent by apps with the
- * password field masked.
- *
- * @param externalConfig External WifiEnterpriseConfig object.
- * @param mask String mask to compare against.
- * @hide
- */
- public void copyFromExternal(WifiEnterpriseConfig externalConfig, String mask) {
- copyFrom(externalConfig, true, convertToQuotedString(mask));
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mFields.size());
- for (Map.Entry entry : mFields.entrySet()) {
- dest.writeString(entry.getKey());
- dest.writeString(entry.getValue());
- }
-
- dest.writeInt(mEapMethod);
- dest.writeInt(mPhase2Method);
- ParcelUtil.writeCertificates(dest, mCaCerts);
- ParcelUtil.writePrivateKey(dest, mClientPrivateKey);
- ParcelUtil.writeCertificates(dest, mClientCertificateChain);
- dest.writeBoolean(mIsAppInstalledDeviceKeyAndCert);
- dest.writeBoolean(mIsAppInstalledCaCert);
- dest.writeInt(mOcsp);
- }
-
- public static final @android.annotation.NonNull Creator CREATOR =
- new Creator() {
- @Override
- public WifiEnterpriseConfig createFromParcel(Parcel in) {
- WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
- int count = in.readInt();
- for (int i = 0; i < count; i++) {
- String key = in.readString();
- String value = in.readString();
- enterpriseConfig.mFields.put(key, value);
- }
-
- enterpriseConfig.mEapMethod = in.readInt();
- enterpriseConfig.mPhase2Method = in.readInt();
- enterpriseConfig.mCaCerts = ParcelUtil.readCertificates(in);
- enterpriseConfig.mClientPrivateKey = ParcelUtil.readPrivateKey(in);
- enterpriseConfig.mClientCertificateChain = ParcelUtil.readCertificates(in);
- enterpriseConfig.mIsAppInstalledDeviceKeyAndCert = in.readBoolean();
- enterpriseConfig.mIsAppInstalledCaCert = in.readBoolean();
- enterpriseConfig.mOcsp = in.readInt();
- return enterpriseConfig;
- }
-
- @Override
- public WifiEnterpriseConfig[] newArray(int size) {
- return new WifiEnterpriseConfig[size];
- }
- };
-
- /** The Extensible Authentication Protocol method used */
- public static final class Eap {
- /** No EAP method used. Represents an empty config */
- public static final int NONE = -1;
- /** Protected EAP */
- public static final int PEAP = 0;
- /** EAP-Transport Layer Security */
- public static final int TLS = 1;
- /** EAP-Tunneled Transport Layer Security */
- public static final int TTLS = 2;
- /** EAP-Password */
- public static final int PWD = 3;
- /** EAP-Subscriber Identity Module [RFC-4186] */
- public static final int SIM = 4;
- /** EAP-Authentication and Key Agreement [RFC-4187] */
- public static final int AKA = 5;
- /** EAP-Authentication and Key Agreement Prime [RFC-5448] */
- public static final int AKA_PRIME = 6;
- /** Hotspot 2.0 r2 OSEN */
- public static final int UNAUTH_TLS = 7;
- /** WAPI Certificate */
- public static final int WAPI_CERT = 8;
- /** @hide */
- public static final String[] strings =
- { "PEAP", "TLS", "TTLS", "PWD", "SIM", "AKA", "AKA'", "WFA-UNAUTH-TLS",
- "WAPI_CERT" };
-
- /** Prevent initialization */
- private Eap() {}
- }
-
- /** The inner authentication method used */
- public static final class Phase2 {
- public static final int NONE = 0;
- /** Password Authentication Protocol */
- public static final int PAP = 1;
- /** Microsoft Challenge Handshake Authentication Protocol */
- public static final int MSCHAP = 2;
- /** Microsoft Challenge Handshake Authentication Protocol v2 */
- public static final int MSCHAPV2 = 3;
- /** Generic Token Card */
- public static final int GTC = 4;
- /** EAP-Subscriber Identity Module [RFC-4186] */
- public static final int SIM = 5;
- /** EAP-Authentication and Key Agreement [RFC-4187] */
- public static final int AKA = 6;
- /** EAP-Authentication and Key Agreement Prime [RFC-5448] */
- public static final int AKA_PRIME = 7;
- private static final String AUTH_PREFIX = "auth=";
- private static final String AUTHEAP_PREFIX = "autheap=";
- /** @hide */
- public static final String[] strings = {EMPTY_VALUE, "PAP", "MSCHAP",
- "MSCHAPV2", "GTC", "SIM", "AKA", "AKA'" };
-
- /** Prevent initialization */
- private Phase2() {}
- }
-
- // Loader and saver interfaces for exchanging data with wpa_supplicant.
- // TODO: Decouple this object (which is just a placeholder of the configuration)
- // from the implementation that knows what wpa_supplicant wants.
- /**
- * Interface used for retrieving supplicant configuration from WifiEnterpriseConfig
- * @hide
- */
- public interface SupplicantSaver {
- /**
- * Set a value within wpa_supplicant configuration
- * @param key index to set within wpa_supplciant
- * @param value the value for the key
- * @return true if successful; false otherwise
- */
- boolean saveValue(String key, String value);
- }
-
- /**
- * Interface used for populating a WifiEnterpriseConfig from supplicant configuration
- * @hide
- */
- public interface SupplicantLoader {
- /**
- * Returns a value within wpa_supplicant configuration
- * @param key index to set within wpa_supplciant
- * @return string value if successful; null otherwise
- */
- String loadValue(String key);
- }
-
- /**
- * Internal use only; supply field values to wpa_supplicant config. The configuration
- * process aborts on the first failed call on {@code saver}.
- * @param saver proxy for setting configuration in wpa_supplciant
- * @return whether the save succeeded on all attempts
- * @hide
- */
- public boolean saveToSupplicant(SupplicantSaver saver) {
- if (!isEapMethodValid()) {
- return false;
- }
-
- // wpa_supplicant can update the anonymous identity for these kinds of networks after
- // framework reads them, so make sure the framework doesn't try to overwrite them.
- boolean shouldNotWriteAnonIdentity = mEapMethod == WifiEnterpriseConfig.Eap.SIM
- || mEapMethod == WifiEnterpriseConfig.Eap.AKA
- || mEapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME;
- for (String key : mFields.keySet()) {
- if (shouldNotWriteAnonIdentity && ANON_IDENTITY_KEY.equals(key)) {
- continue;
- }
- if (!saver.saveValue(key, mFields.get(key))) {
- return false;
- }
- }
-
- if (!saver.saveValue(EAP_KEY, Eap.strings[mEapMethod])) {
- return false;
- }
-
- if (mEapMethod != Eap.TLS && mEapMethod != Eap.UNAUTH_TLS && mPhase2Method != Phase2.NONE) {
- boolean is_autheap = mEapMethod == Eap.TTLS && mPhase2Method == Phase2.GTC;
- String prefix = is_autheap ? Phase2.AUTHEAP_PREFIX : Phase2.AUTH_PREFIX;
- String value = convertToQuotedString(prefix + Phase2.strings[mPhase2Method]);
- return saver.saveValue(PHASE2_KEY, value);
- } else if (mPhase2Method == Phase2.NONE) {
- // By default, send a null phase 2 to clear old configuration values.
- return saver.saveValue(PHASE2_KEY, null);
- } else {
- Log.e(TAG, "WiFi enterprise configuration is invalid as it supplies a "
- + "phase 2 method but the phase1 method does not support it.");
- return false;
- }
- }
-
- /**
- * Internal use only; retrieve configuration from wpa_supplicant config.
- * @param loader proxy for retrieving configuration keys from wpa_supplicant
- * @hide
- */
- public void loadFromSupplicant(SupplicantLoader loader) {
- for (String key : SUPPLICANT_CONFIG_KEYS) {
- String value = loader.loadValue(key);
- if (value == null) {
- mFields.put(key, EMPTY_VALUE);
- } else {
- mFields.put(key, value);
- }
- }
- String eapMethod = loader.loadValue(EAP_KEY);
- mEapMethod = getStringIndex(Eap.strings, eapMethod, Eap.NONE);
-
- String phase2Method = removeDoubleQuotes(loader.loadValue(PHASE2_KEY));
- // Remove "auth=" or "autheap=" prefix.
- if (phase2Method.startsWith(Phase2.AUTH_PREFIX)) {
- phase2Method = phase2Method.substring(Phase2.AUTH_PREFIX.length());
- } else if (phase2Method.startsWith(Phase2.AUTHEAP_PREFIX)) {
- phase2Method = phase2Method.substring(Phase2.AUTHEAP_PREFIX.length());
- }
- mPhase2Method = getStringIndex(Phase2.strings, phase2Method, Phase2.NONE);
- }
-
- /**
- * Set the EAP authentication method.
- * @param eapMethod is one {@link Eap#PEAP}, {@link Eap#TLS}, {@link Eap#TTLS} or
- * {@link Eap#PWD}
- * @throws IllegalArgumentException on an invalid eap method
- */
- public void setEapMethod(int eapMethod) {
- switch (eapMethod) {
- /** Valid methods */
- case Eap.WAPI_CERT:
- mEapMethod = eapMethod;
- setPhase2Method(Phase2.NONE);
- break;
- case Eap.TLS:
- case Eap.UNAUTH_TLS:
- setPhase2Method(Phase2.NONE);
- /* fall through */
- case Eap.PEAP:
- case Eap.PWD:
- case Eap.TTLS:
- case Eap.SIM:
- case Eap.AKA:
- case Eap.AKA_PRIME:
- mEapMethod = eapMethod;
- setFieldValue(OPP_KEY_CACHING, "1");
- break;
- default:
- throw new IllegalArgumentException("Unknown EAP method");
- }
- }
-
- /**
- * Get the eap method.
- * @return eap method configured
- */
- public int getEapMethod() {
- return mEapMethod;
- }
-
- /**
- * Set Phase 2 authentication method. Sets the inner authentication method to be used in
- * phase 2 after setting up a secure channel
- * @param phase2Method is the inner authentication method and can be one of {@link Phase2#NONE},
- * {@link Phase2#PAP}, {@link Phase2#MSCHAP}, {@link Phase2#MSCHAPV2},
- * {@link Phase2#GTC}
- * @throws IllegalArgumentException on an invalid phase2 method
- *
- */
- public void setPhase2Method(int phase2Method) {
- switch (phase2Method) {
- case Phase2.NONE:
- case Phase2.PAP:
- case Phase2.MSCHAP:
- case Phase2.MSCHAPV2:
- case Phase2.GTC:
- case Phase2.SIM:
- case Phase2.AKA:
- case Phase2.AKA_PRIME:
- mPhase2Method = phase2Method;
- break;
- default:
- throw new IllegalArgumentException("Unknown Phase 2 method");
- }
- }
-
- /**
- * Get the phase 2 authentication method.
- * @return a phase 2 method defined at {@link Phase2}
- * */
- public int getPhase2Method() {
- return mPhase2Method;
- }
-
- /**
- * Set the identity
- * @param identity
- */
- public void setIdentity(String identity) {
- setFieldValue(IDENTITY_KEY, identity, "");
- }
-
- /**
- * Get the identity
- * @return the identity
- */
- public String getIdentity() {
- return getFieldValue(IDENTITY_KEY);
- }
-
- /**
- * Set anonymous identity. This is used as the unencrypted identity with
- * certain EAP types
- * @param anonymousIdentity the anonymous identity
- */
- public void setAnonymousIdentity(String anonymousIdentity) {
- setFieldValue(ANON_IDENTITY_KEY, anonymousIdentity);
- }
-
- /**
- * Get the anonymous identity
- * @return anonymous identity
- */
- public String getAnonymousIdentity() {
- return getFieldValue(ANON_IDENTITY_KEY);
- }
-
- /**
- * Set the password.
- * @param password the password
- */
- public void setPassword(String password) {
- setFieldValue(PASSWORD_KEY, password);
- }
-
- /**
- * Get the password.
- *
- * Returns locally set password value. For networks fetched from
- * framework, returns "*".
- */
- public String getPassword() {
- return getFieldValue(PASSWORD_KEY);
- }
-
- /**
- * Encode a CA certificate alias so it does not contain illegal character.
- * @hide
- */
- public static String encodeCaCertificateAlias(String alias) {
- byte[] bytes = alias.getBytes(StandardCharsets.UTF_8);
- StringBuilder sb = new StringBuilder(bytes.length * 2);
- for (byte o : bytes) {
- sb.append(String.format("%02x", o & 0xFF));
- }
- return sb.toString();
- }
-
- /**
- * Decode a previously-encoded CA certificate alias.
- * @hide
- */
- public static String decodeCaCertificateAlias(String alias) {
- byte[] data = new byte[alias.length() >> 1];
- for (int n = 0, position = 0; n < alias.length(); n += 2, position++) {
- data[position] = (byte) Integer.parseInt(alias.substring(n, n + 2), 16);
- }
- try {
- return new String(data, StandardCharsets.UTF_8);
- } catch (NumberFormatException e) {
- e.printStackTrace();
- return alias;
- }
- }
-
- /**
- * Set CA certificate alias.
- *
- * See the {@link android.security.KeyChain} for details on installing or choosing
- * a certificate
- *
- * @param alias identifies the certificate
- * @hide
- */
- @UnsupportedAppUsage
- public void setCaCertificateAlias(String alias) {
- setFieldValue(CA_CERT_KEY, alias, CA_CERT_PREFIX);
- }
-
- /**
- * Set CA certificate aliases. When creating installing the corresponding certificate to
- * the keystore, please use alias encoded by {@link #encodeCaCertificateAlias(String)}.
- *
- * See the {@link android.security.KeyChain} for details on installing or choosing
- * a certificate.
- *
- * @param aliases identifies the certificate. Can be null to indicate the absence of a
- * certificate.
- * @hide
- */
- @SystemApi
- public void setCaCertificateAliases(@Nullable String[] aliases) {
- if (aliases == null) {
- setFieldValue(CA_CERT_KEY, null, CA_CERT_PREFIX);
- } else if (aliases.length == 1) {
- // Backwards compatibility: use the original cert prefix if setting only one alias.
- setCaCertificateAlias(aliases[0]);
- } else {
- // Use KEYSTORES_URI which supports multiple aliases.
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < aliases.length; i++) {
- if (i > 0) {
- sb.append(CA_CERT_ALIAS_DELIMITER);
- }
- sb.append(encodeCaCertificateAlias(CA_CERTIFICATE + aliases[i]));
- }
- setFieldValue(CA_CERT_KEY, sb.toString(), KEYSTORES_URI);
- }
- }
-
- /**
- * Get CA certificate alias
- * @return alias to the CA certificate
- * @hide
- */
- @UnsupportedAppUsage
- public String getCaCertificateAlias() {
- return getFieldValue(CA_CERT_KEY, CA_CERT_PREFIX);
- }
-
- /**
- * Get CA certificate aliases.
- * @return alias to the CA certificate, or null if unset.
- * @hide
- */
- @Nullable
- @SystemApi
- public String[] getCaCertificateAliases() {
- String value = getFieldValue(CA_CERT_KEY);
- if (value.startsWith(CA_CERT_PREFIX)) {
- // Backwards compatibility: parse the original alias prefix.
- return new String[] {getFieldValue(CA_CERT_KEY, CA_CERT_PREFIX)};
- } else if (value.startsWith(KEYSTORES_URI)) {
- String values = value.substring(KEYSTORES_URI.length());
-
- String[] aliases = TextUtils.split(values, CA_CERT_ALIAS_DELIMITER);
- for (int i = 0; i < aliases.length; i++) {
- aliases[i] = decodeCaCertificateAlias(aliases[i]);
- if (aliases[i].startsWith(CA_CERTIFICATE)) {
- aliases[i] = aliases[i].substring(CA_CERTIFICATE.length());
- }
- }
- return aliases.length != 0 ? aliases : null;
- } else {
- return TextUtils.isEmpty(value) ? null : new String[] {value};
- }
- }
-
- /**
- * Specify a X.509 certificate that identifies the server.
- *
- * A default name is automatically assigned to the certificate and used
- * with this configuration. The framework takes care of installing the
- * certificate when the config is saved and removing the certificate when
- * the config is removed.
- *
- * Note: If no certificate is set for an Enterprise configuration, either by not calling this
- * API (or the {@link #setCaCertificates(X509Certificate[])}, or by calling it with null, then
- * the server certificate validation is skipped - which means that the connection is not secure.
- *
- * @param cert X.509 CA certificate
- * @throws IllegalArgumentException if not a CA certificate
- */
- public void setCaCertificate(@Nullable X509Certificate cert) {
- if (cert != null) {
- if (cert.getBasicConstraints() >= 0) {
- mIsAppInstalledCaCert = true;
- mCaCerts = new X509Certificate[] {cert};
- } else {
- mCaCerts = null;
- throw new IllegalArgumentException("Not a CA certificate");
- }
- } else {
- mCaCerts = null;
- }
- }
-
- /**
- * Get CA certificate. If multiple CA certificates are configured previously,
- * return the first one.
- * @return X.509 CA certificate
- */
- @Nullable public X509Certificate getCaCertificate() {
- if (mCaCerts != null && mCaCerts.length > 0) {
- return mCaCerts[0];
- } else {
- return null;
- }
- }
-
- /**
- * Specify a list of X.509 certificates that identifies the server. The validation
- * passes if the CA of server certificate matches one of the given certificates.
-
- *
Default names are automatically assigned to the certificates and used
- * with this configuration. The framework takes care of installing the
- * certificates when the config is saved and removing the certificates when
- * the config is removed.
- *
- * Note: If no certificates are set for an Enterprise configuration, either by not calling this
- * API (or the {@link #setCaCertificate(X509Certificate)}, or by calling it with null, then the
- * server certificate validation is skipped - which means that the
- * connection is not secure.
- *
- * @param certs X.509 CA certificates
- * @throws IllegalArgumentException if any of the provided certificates is
- * not a CA certificate
- */
- public void setCaCertificates(@Nullable X509Certificate[] certs) {
- if (certs != null) {
- X509Certificate[] newCerts = new X509Certificate[certs.length];
- for (int i = 0; i < certs.length; i++) {
- if (certs[i].getBasicConstraints() >= 0) {
- newCerts[i] = certs[i];
- } else {
- mCaCerts = null;
- throw new IllegalArgumentException("Not a CA certificate");
- }
- }
- mCaCerts = newCerts;
- mIsAppInstalledCaCert = true;
- } else {
- mCaCerts = null;
- }
- }
-
- /**
- * Get CA certificates.
- */
- @Nullable public X509Certificate[] getCaCertificates() {
- if (mCaCerts != null && mCaCerts.length > 0) {
- return mCaCerts;
- } else {
- return null;
- }
- }
-
- /**
- * @hide
- */
- public void resetCaCertificate() {
- mCaCerts = null;
- }
-
- /**
- * Set the ca_path directive on wpa_supplicant.
- *
- * From wpa_supplicant documentation:
- *
- * Directory path for CA certificate files (PEM). This path may contain
- * multiple CA certificates in OpenSSL format. Common use for this is to
- * point to system trusted CA list which is often installed into directory
- * like /etc/ssl/certs. If configured, these certificates are added to the
- * list of trusted CAs. ca_cert may also be included in that case, but it is
- * not required.
- *
- * Note: If no certificate path is set for an Enterprise configuration, either by not calling
- * this API, or by calling it with null, and no certificate is set by
- * {@link #setCaCertificate(X509Certificate)} or {@link #setCaCertificates(X509Certificate[])},
- * then the server certificate validation is skipped - which means that the connection is not
- * secure.
- *
- * @param path The path for CA certificate files, or empty string to clear.
- * @hide
- */
- @SystemApi
- public void setCaPath(@NonNull String path) {
- setFieldValue(CA_PATH_KEY, path);
- }
-
- /**
- * Get the ca_path directive from wpa_supplicant.
- * @return The path for CA certificate files, or an empty string if unset.
- * @hide
- */
- @NonNull
- @SystemApi
- public String getCaPath() {
- return getFieldValue(CA_PATH_KEY);
- }
-
- /**
- * Set Client certificate alias.
- *
- *
See the {@link android.security.KeyChain} for details on installing or choosing
- * a certificate
- *
- * @param alias identifies the certificate, or empty string to clear.
- * @hide
- */
- @SystemApi
- public void setClientCertificateAlias(@NonNull String alias) {
- setFieldValue(CLIENT_CERT_KEY, alias, CLIENT_CERT_PREFIX);
- setFieldValue(PRIVATE_KEY_ID_KEY, alias, USER_PRIVATE_KEY);
- // Also, set engine parameters
- if (TextUtils.isEmpty(alias)) {
- setFieldValue(ENGINE_KEY, ENGINE_DISABLE);
- setFieldValue(ENGINE_ID_KEY, "");
- } else {
- setFieldValue(ENGINE_KEY, ENGINE_ENABLE);
- setFieldValue(ENGINE_ID_KEY, ENGINE_ID_KEYSTORE);
- }
- }
-
- /**
- * Get client certificate alias.
- * @return alias to the client certificate, or an empty string if unset.
- * @hide
- */
- @NonNull
- @SystemApi
- public String getClientCertificateAlias() {
- return getFieldValue(CLIENT_CERT_KEY, CLIENT_CERT_PREFIX);
- }
-
- /**
- * Specify a private key and client certificate for client authorization.
- *
- * A default name is automatically assigned to the key entry and used
- * with this configuration. The framework takes care of installing the
- * key entry when the config is saved and removing the key entry when
- * the config is removed.
-
- * @param privateKey a PrivateKey instance for the end certificate.
- * @param clientCertificate an X509Certificate representing the end certificate.
- * @throws IllegalArgumentException for an invalid key or certificate.
- */
- public void setClientKeyEntry(PrivateKey privateKey, X509Certificate clientCertificate) {
- X509Certificate[] clientCertificates = null;
- if (clientCertificate != null) {
- clientCertificates = new X509Certificate[] {clientCertificate};
- }
- setClientKeyEntryWithCertificateChain(privateKey, clientCertificates);
- }
-
- /**
- * Specify a private key and client certificate chain for client authorization.
- *
- *
A default name is automatically assigned to the key entry and used
- * with this configuration. The framework takes care of installing the
- * key entry when the config is saved and removing the key entry when
- * the config is removed.
- *
- * @param privateKey a PrivateKey instance for the end certificate.
- * @param clientCertificateChain an array of X509Certificate instances which starts with
- * end certificate and continues with additional CA certificates necessary to
- * link the end certificate with some root certificate known by the authenticator.
- * @throws IllegalArgumentException for an invalid key or certificate.
- */
- public void setClientKeyEntryWithCertificateChain(PrivateKey privateKey,
- X509Certificate[] clientCertificateChain) {
- X509Certificate[] newCerts = null;
- if (clientCertificateChain != null && clientCertificateChain.length > 0) {
- // We validate that this is a well formed chain that starts
- // with an end-certificate and is followed by CA certificates.
- // We don't validate that each following certificate verifies
- // the previous. https://en.wikipedia.org/wiki/Chain_of_trust
- //
- // Basic constraints is an X.509 extension type that defines
- // whether a given certificate is allowed to sign additional
- // certificates and what path length restrictions may exist.
- // We use this to judge whether the certificate is an end
- // certificate or a CA certificate.
- // https://cryptography.io/en/latest/x509/reference/
- if (clientCertificateChain[0].getBasicConstraints() != -1) {
- throw new IllegalArgumentException(
- "First certificate in the chain must be a client end certificate");
- }
-
- for (int i = 1; i < clientCertificateChain.length; i++) {
- if (clientCertificateChain[i].getBasicConstraints() == -1) {
- throw new IllegalArgumentException(
- "All certificates following the first must be CA certificates");
- }
- }
- newCerts = Arrays.copyOf(clientCertificateChain,
- clientCertificateChain.length);
-
- if (privateKey == null) {
- throw new IllegalArgumentException("Client cert without a private key");
- }
- if (privateKey.getEncoded() == null) {
- throw new IllegalArgumentException("Private key cannot be encoded");
- }
- }
-
- mClientPrivateKey = privateKey;
- mClientCertificateChain = newCerts;
- mIsAppInstalledDeviceKeyAndCert = true;
- }
-
- /**
- * Get client certificate
- *
- * @return X.509 client certificate
- */
- public X509Certificate getClientCertificate() {
- if (mClientCertificateChain != null && mClientCertificateChain.length > 0) {
- return mClientCertificateChain[0];
- } else {
- return null;
- }
- }
-
- /**
- * Get the complete client certificate chain in the same order as it was last supplied.
- *
- *
If the chain was last supplied by a call to
- * {@link #setClientKeyEntry(java.security.PrivateKey, java.security.cert.X509Certificate)}
- * with a non-null * certificate instance, a single-element array containing the certificate
- * will be * returned. If {@link #setClientKeyEntryWithCertificateChain(
- * java.security.PrivateKey, java.security.cert.X509Certificate[])} was last called with a
- * non-empty array, this array will be returned in the same order as it was supplied.
- * Otherwise, {@code null} will be returned.
- *
- * @return X.509 client certificates
- */
- @Nullable public X509Certificate[] getClientCertificateChain() {
- if (mClientCertificateChain != null && mClientCertificateChain.length > 0) {
- return mClientCertificateChain;
- } else {
- return null;
- }
- }
-
- /**
- * @hide
- */
- public void resetClientKeyEntry() {
- mClientPrivateKey = null;
- mClientCertificateChain = null;
- }
-
- /**
- * Get the client private key as supplied in {@link #setClientKeyEntryWithCertificateChain}, or
- * null if unset.
- */
- @Nullable
- public PrivateKey getClientPrivateKey() {
- return mClientPrivateKey;
- }
-
- /**
- * Set subject match (deprecated). This is the substring to be matched against the subject of
- * the authentication server certificate.
- * @param subjectMatch substring to be matched
- * @deprecated in favor of altSubjectMatch
- */
- public void setSubjectMatch(String subjectMatch) {
- setFieldValue(SUBJECT_MATCH_KEY, subjectMatch);
- }
-
- /**
- * Get subject match (deprecated)
- * @return the subject match string
- * @deprecated in favor of altSubjectMatch
- */
- public String getSubjectMatch() {
- return getFieldValue(SUBJECT_MATCH_KEY);
- }
-
- /**
- * Set alternate subject match. This is the substring to be matched against the
- * alternate subject of the authentication server certificate.
- *
- * Note: If no alternate subject is set for an Enterprise configuration, either by not calling
- * this API, or by calling it with null, or not setting domain suffix match using the
- * {@link #setDomainSuffixMatch(String)}, then the server certificate validation is incomplete -
- * which means that the connection is not secure.
- *
- * @param altSubjectMatch substring to be matched, for example
- * DNS:server.example.com;EMAIL:server@example.com
- */
- public void setAltSubjectMatch(String altSubjectMatch) {
- setFieldValue(ALTSUBJECT_MATCH_KEY, altSubjectMatch);
- }
-
- /**
- * Get alternate subject match
- * @return the alternate subject match string
- */
- public String getAltSubjectMatch() {
- return getFieldValue(ALTSUBJECT_MATCH_KEY);
- }
-
- /**
- * Set the domain_suffix_match directive on wpa_supplicant. This is the parameter to use
- * for Hotspot 2.0 defined matching of AAA server certs per WFA HS2.0 spec, section 7.3.3.2,
- * second paragraph.
- *
- *
From wpa_supplicant documentation:
- *
Constraint for server domain name. If set, this FQDN is used as a suffix match requirement
- * for the AAAserver certificate in SubjectAltName dNSName element(s). If a matching dNSName is
- * found, this constraint is met.
- *
Suffix match here means that the host/domain name is compared one label at a time starting
- * from the top-level domain and all the labels in domain_suffix_match shall be included in the
- * certificate. The certificate may include additional sub-level labels in addition to the
- * required labels.
- *
More than one match string can be provided by using semicolons to separate the strings
- * (e.g., example.org;example.com). When multiple strings are specified, a match with any one of
- * the values is considered a sufficient match for the certificate, i.e., the conditions are
- * ORed ogether.
- *
For example, domain_suffix_match=example.com would match test.example.com but would not
- * match test-example.com.
- *
- * Note: If no domain suffix is set for an Enterprise configuration, either by not calling this
- * API, or by calling it with null, or not setting alternate subject match using the
- * {@link #setAltSubjectMatch(String)}, then the server certificate
- * validation is incomplete - which means that the connection is not secure.
- *
- * @param domain The domain value
- */
- public void setDomainSuffixMatch(String domain) {
- setFieldValue(DOM_SUFFIX_MATCH_KEY, domain);
- }
-
- /**
- * Get the domain_suffix_match value. See setDomSuffixMatch.
- * @return The domain value.
- */
- public String getDomainSuffixMatch() {
- return getFieldValue(DOM_SUFFIX_MATCH_KEY);
- }
-
- /**
- * Set realm for Passpoint credential; realm identifies a set of networks where your
- * Passpoint credential can be used
- * @param realm the realm
- */
- public void setRealm(String realm) {
- setFieldValue(REALM_KEY, realm);
- }
-
- /**
- * Get realm for Passpoint credential; see {@link #setRealm(String)} for more information
- * @return the realm
- */
- public String getRealm() {
- return getFieldValue(REALM_KEY);
- }
-
- /**
- * Set plmn (Public Land Mobile Network) of the provider of Passpoint credential
- * @param plmn the plmn value derived from mcc (mobile country code) & mnc (mobile network code)
- */
- public void setPlmn(String plmn) {
- setFieldValue(PLMN_KEY, plmn);
- }
-
- /**
- * Get plmn (Public Land Mobile Network) for Passpoint credential; see {@link #setPlmn
- * (String)} for more information
- * @return the plmn
- */
- public String getPlmn() {
- return getFieldValue(PLMN_KEY);
- }
-
- /** See {@link WifiConfiguration#getKeyIdForCredentials} @hide */
- public String getKeyId(WifiEnterpriseConfig current) {
- // If EAP method is not initialized, use current config details
- if (mEapMethod == Eap.NONE) {
- return (current != null) ? current.getKeyId(null) : EMPTY_VALUE;
- }
- if (!isEapMethodValid()) {
- return EMPTY_VALUE;
- }
- return Eap.strings[mEapMethod] + "_" + Phase2.strings[mPhase2Method];
- }
-
- private String removeDoubleQuotes(String string) {
- if (TextUtils.isEmpty(string)) return "";
- int length = string.length();
- if ((length > 1) && (string.charAt(0) == '"')
- && (string.charAt(length - 1) == '"')) {
- return string.substring(1, length - 1);
- }
- return string;
- }
-
- private String convertToQuotedString(String string) {
- return "\"" + string + "\"";
- }
-
- /**
- * Returns the index at which the toBeFound string is found in the array.
- * @param arr array of strings
- * @param toBeFound string to be found
- * @param defaultIndex default index to be returned when string is not found
- * @return the index into array
- */
- private int getStringIndex(String arr[], String toBeFound, int defaultIndex) {
- if (TextUtils.isEmpty(toBeFound)) return defaultIndex;
- for (int i = 0; i < arr.length; i++) {
- if (toBeFound.equals(arr[i])) return i;
- }
- return defaultIndex;
- }
-
- /**
- * Returns the field value for the key with prefix removed.
- * @param key into the hash
- * @param prefix is the prefix that the value may have
- * @return value
- * @hide
- */
- private String getFieldValue(String key, String prefix) {
- // TODO: Should raise an exception if |key| is EAP_KEY or PHASE2_KEY since
- // neither of these keys should be retrieved in this manner.
- String value = mFields.get(key);
- // Uninitialized or known to be empty after reading from supplicant
- if (TextUtils.isEmpty(value) || EMPTY_VALUE.equals(value)) return "";
-
- value = removeDoubleQuotes(value);
- if (value.startsWith(prefix)) {
- return value.substring(prefix.length());
- } else {
- return value;
- }
- }
-
- /**
- * Returns the field value for the key.
- * @param key into the hash
- * @return value
- * @hide
- */
- public String getFieldValue(String key) {
- return getFieldValue(key, "");
- }
-
- /**
- * Set a value with an optional prefix at key
- * @param key into the hash
- * @param value to be set
- * @param prefix an optional value to be prefixed to actual value
- * @hide
- */
- private void setFieldValue(String key, String value, String prefix) {
- // TODO: Should raise an exception if |key| is EAP_KEY or PHASE2_KEY since
- // neither of these keys should be set in this manner.
- if (TextUtils.isEmpty(value)) {
- mFields.put(key, EMPTY_VALUE);
- } else {
- String valueToSet;
- if (!UNQUOTED_KEYS.contains(key)) {
- valueToSet = convertToQuotedString(prefix + value);
- } else {
- valueToSet = prefix + value;
- }
- mFields.put(key, valueToSet);
- }
- }
-
- /**
- * Set a value at key
- * @param key into the hash
- * @param value to be set
- * @hide
- */
- public void setFieldValue(String key, String value) {
- setFieldValue(key, value, "");
- }
-
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- for (String key : mFields.keySet()) {
- // Don't display password in toString().
- String value = PASSWORD_KEY.equals(key) ? "" : mFields.get(key);
- sb.append(key).append(" ").append(value).append("\n");
- }
- if (mEapMethod >= 0 && mEapMethod < Eap.strings.length) {
- sb.append("eap_method: ").append(Eap.strings[mEapMethod]).append("\n");
- }
- if (mPhase2Method > 0 && mPhase2Method < Phase2.strings.length) {
- sb.append("phase2_method: ").append(Phase2.strings[mPhase2Method]).append("\n");
- }
- sb.append(" ocsp: ").append(mOcsp).append("\n");
- return sb.toString();
- }
-
- /**
- * Returns whether the EAP method data is valid, i.e., whether mEapMethod and mPhase2Method
- * are valid indices into {@code Eap.strings[]} and {@code Phase2.strings[]} respectively.
- */
- private boolean isEapMethodValid() {
- if (mEapMethod == Eap.NONE) {
- Log.e(TAG, "WiFi enterprise configuration is invalid as it supplies no EAP method.");
- return false;
- }
- if (mEapMethod < 0 || mEapMethod >= Eap.strings.length) {
- Log.e(TAG, "mEapMethod is invald for WiFi enterprise configuration: " + mEapMethod);
- return false;
- }
- if (mPhase2Method < 0 || mPhase2Method >= Phase2.strings.length) {
- Log.e(TAG, "mPhase2Method is invald for WiFi enterprise configuration: "
- + mPhase2Method);
- return false;
- }
- return true;
- }
-
- /**
- * Check if certificate was installed by an app, or manually (not by an app). If true,
- * certificate and keys will be removed from key storage when this network is removed. If not,
- * then certificates and keys remain persistent until the user manually removes them.
- *
- * @return true if certificate was installed by an app, false if certificate was installed
- * manually by the user.
- * @hide
- */
- public boolean isAppInstalledDeviceKeyAndCert() {
- return mIsAppInstalledDeviceKeyAndCert;
- }
-
- /**
- * Initialize the value of the app installed device key and cert flag.
- *
- * @param isAppInstalledDeviceKeyAndCert true or false
- * @hide
- */
- public void initIsAppInstalledDeviceKeyAndCert(boolean isAppInstalledDeviceKeyAndCert) {
- mIsAppInstalledDeviceKeyAndCert = isAppInstalledDeviceKeyAndCert;
- }
-
- /**
- * Check if CA certificate was installed by an app, or manually (not by an app). If true,
- * CA certificate will be removed from key storage when this network is removed. If not,
- * then certificates and keys remain persistent until the user manually removes them.
- *
- * @return true if CA certificate was installed by an app, false if CA certificate was installed
- * manually by the user.
- * @hide
- */
- public boolean isAppInstalledCaCert() {
- return mIsAppInstalledCaCert;
- }
-
- /**
- * Initialize the value of the app installed root CA cert flag.
- *
- * @param isAppInstalledCaCert true or false
- * @hide
- */
- public void initIsAppInstalledCaCert(boolean isAppInstalledCaCert) {
- mIsAppInstalledCaCert = isAppInstalledCaCert;
- }
-
- /**
- * Set the OCSP type.
- * @param ocsp is one of {@link ##OCSP_NONE}, {@link #OCSP_REQUEST_CERT_STATUS},
- * {@link #OCSP_REQUIRE_CERT_STATUS} or
- * {@link #OCSP_REQUIRE_ALL_NON_TRUSTED_CERTS_STATUS}
- * @throws IllegalArgumentException if the OCSP type is invalid
- * @hide
- */
- @SystemApi
- public void setOcsp(@Ocsp int ocsp) {
- if (ocsp >= OCSP_NONE && ocsp <= OCSP_REQUIRE_ALL_NON_TRUSTED_CERTS_STATUS) {
- mOcsp = ocsp;
- } else {
- throw new IllegalArgumentException("Invalid OCSP type.");
- }
- }
-
- /**
- * Get the OCSP type.
- * @hide
- */
- @SystemApi
- public @Ocsp int getOcsp() {
- return mOcsp;
- }
-
- /**
- * Utility method to determine whether the configuration's authentication method is SIM-based.
- *
- * @return true if the credential information requires SIM card for current authentication
- * method, otherwise it returns false.
- */
- public boolean isAuthenticationSimBased() {
- if (mEapMethod == Eap.SIM || mEapMethod == Eap.AKA || mEapMethod == Eap.AKA_PRIME) {
- return true;
- }
- if (mEapMethod == Eap.PEAP) {
- return mPhase2Method == Phase2.SIM || mPhase2Method == Phase2.AKA
- || mPhase2Method == Phase2.AKA_PRIME;
- }
- return false;
- }
-
- /**
- * Set the WAPI certificate suite name on wpa_supplicant.
- *
- * If this field is not specified, WAPI-CERT uses ASU ID from WAI packet
- * as the certificate suite name automatically.
- *
- * @param wapiCertSuite The name for WAPI certificate suite, or empty string to clear.
- * @hide
- */
- @SystemApi
- public void setWapiCertSuite(@NonNull String wapiCertSuite) {
- setFieldValue(WAPI_CERT_SUITE_KEY, wapiCertSuite);
- }
-
- /**
- * Get the WAPI certificate suite name
- * @return the certificate suite name
- * @hide
- */
- @NonNull
- @SystemApi
- public String getWapiCertSuite() {
- return getFieldValue(WAPI_CERT_SUITE_KEY);
- }
-
- /**
- * Method determines whether the Enterprise configuration is insecure. An insecure
- * configuration is one where EAP method requires a CA certification, i.e. PEAP, TLS, or
- * TTLS, and any of the following conditions are met:
- * - Both certificate and CA path are not configured.
- * - Both alternative subject match and domain suffix match are not set.
- *
- * Note: this method does not exhaustively check security of the configuration - i.e. a return
- * value of {@code false} is not a guarantee that the configuration is secure.
- * @hide
- */
- public boolean isInsecure() {
- if (mEapMethod != Eap.PEAP && mEapMethod != Eap.TLS && mEapMethod != Eap.TTLS) {
- return false;
- }
- if (TextUtils.isEmpty(getAltSubjectMatch())
- && TextUtils.isEmpty(getDomainSuffixMatch())) {
- // Both subject and domain match are not set, it's insecure.
- return true;
- }
- if (mIsAppInstalledCaCert) {
- // CA certificate is installed by App, it's secure.
- return false;
- }
- if (getCaCertificateAliases() != null) {
- // CA certificate alias from keyStore is set, it's secure.
- return false;
- }
- return TextUtils.isEmpty(getCaPath());
- }
-
- /**
- * Check if a given certificate Get the Suite-B cipher from the certificate
- *
- * @param x509Certificate Certificate to process
- * @return true if the certificate OID matches the Suite-B requirements for RSA or ECDSA
- * certificates, or false otherwise.
- * @hide
- */
- public static boolean isSuiteBCipherCert(@Nullable X509Certificate x509Certificate) {
- if (x509Certificate == null) {
- return false;
- }
- final String sigAlgOid = x509Certificate.getSigAlgOID();
-
- // Wi-Fi alliance requires the use of both ECDSA secp384r1 and RSA 3072 certificates
- // in WPA3-Enterprise 192-bit security networks, which are also known as Suite-B-192
- // networks, even though NSA Suite-B-192 mandates ECDSA only. The use of the term
- // Suite-B was already coined in the IEEE 802.11-2016 specification for
- // AKM 00-0F-AC but the test plan for WPA3-Enterprise 192-bit for APs mandates
- // support for both RSA and ECDSA, and for STAs it mandates ECDSA and optionally
- // RSA. In order to be compatible with all WPA3-Enterprise 192-bit deployments,
- // we are supporting both types here.
- if (sigAlgOid.equals("1.2.840.113549.1.1.12")) {
- // sha384WithRSAEncryption
- if (x509Certificate.getPublicKey() instanceof RSAPublicKey) {
- final RSAPublicKey rsaPublicKey = (RSAPublicKey) x509Certificate.getPublicKey();
- if (rsaPublicKey.getModulus() != null
- && rsaPublicKey.getModulus().bitLength() >= 3072) {
- return true;
- }
- }
- } else if (sigAlgOid.equals("1.2.840.10045.4.3.3")) {
- // ecdsa-with-SHA384
- if (x509Certificate.getPublicKey() instanceof ECPublicKey) {
- final ECPublicKey ecPublicKey = (ECPublicKey) x509Certificate.getPublicKey();
- final ECParameterSpec ecParameterSpec = ecPublicKey.getParams();
-
- if (ecParameterSpec != null && ecParameterSpec.getOrder() != null
- && ecParameterSpec.getOrder().bitLength() >= 384) {
- return true;
- }
- }
- }
- return false;
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiFrameworkInitializer.java b/wifi/java/android/net/wifi/WifiFrameworkInitializer.java
deleted file mode 100644
index 1507199b0264a..0000000000000
--- a/wifi/java/android/net/wifi/WifiFrameworkInitializer.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * 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 android.net.wifi;
-
-import android.annotation.SystemApi;
-import android.app.SystemServiceRegistry;
-import android.content.Context;
-import android.net.wifi.aware.IWifiAwareManager;
-import android.net.wifi.aware.WifiAwareManager;
-import android.net.wifi.p2p.IWifiP2pManager;
-import android.net.wifi.p2p.WifiP2pManager;
-import android.net.wifi.rtt.IWifiRttManager;
-import android.net.wifi.rtt.WifiRttManager;
-import android.os.HandlerThread;
-import android.os.Looper;
-
-/**
- * Class for performing registration for all Wifi services.
- *
- * @hide
- */
-@SystemApi
-public class WifiFrameworkInitializer {
-
- /**
- * A class implementing the lazy holder idiom: the unique static instance
- * of {@link #INSTANCE} is instantiated in a thread-safe way (guaranteed by
- * the language specs) the first time that NoPreloadHolder is referenced in getInstanceLooper().
- *
- * This is necessary because we can't spawn a new thread in {@link #registerServiceWrappers()}.
- * {@link #registerServiceWrappers()} is called during the Zygote phase, which disallows
- * spawning new threads. Naming the class "NoPreloadHolder" ensures that the classloader will
- * not preload this class, inadvertently spawning the thread too early.
- */
- private static class NoPreloadHolder {
- private static final HandlerThread INSTANCE = createInstance();
-
- private static HandlerThread createInstance() {
- HandlerThread thread = new HandlerThread("WifiManagerThread");
- thread.start();
- return thread;
- }
- }
-
- private static Looper getInstanceLooper() {
- return NoPreloadHolder.INSTANCE.getLooper();
- }
-
- private WifiFrameworkInitializer() {}
-
- /**
- * Called by {@link SystemServiceRegistry}'s static initializer and registers all Wifi services
- * to {@link Context}, so that {@link Context#getSystemService} can return them.
- *
- * @throws IllegalStateException if this is called from anywhere besides
- * {@link SystemServiceRegistry}
- */
- public static void registerServiceWrappers() {
- SystemServiceRegistry.registerContextAwareService(
- Context.WIFI_SERVICE,
- WifiManager.class,
- (context, serviceBinder) -> {
- IWifiManager service = IWifiManager.Stub.asInterface(serviceBinder);
- return new WifiManager(context, service, getInstanceLooper());
- }
- );
- SystemServiceRegistry.registerStaticService(
- Context.WIFI_P2P_SERVICE,
- WifiP2pManager.class,
- serviceBinder -> {
- IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(serviceBinder);
- return new WifiP2pManager(service);
- }
- );
- SystemServiceRegistry.registerContextAwareService(
- Context.WIFI_AWARE_SERVICE,
- WifiAwareManager.class,
- (context, serviceBinder) -> {
- IWifiAwareManager service = IWifiAwareManager.Stub.asInterface(serviceBinder);
- return new WifiAwareManager(context, service);
- }
- );
- SystemServiceRegistry.registerContextAwareService(
- Context.WIFI_SCANNING_SERVICE,
- WifiScanner.class,
- (context, serviceBinder) -> {
- IWifiScanner service = IWifiScanner.Stub.asInterface(serviceBinder);
- return new WifiScanner(context, service, getInstanceLooper());
- }
- );
- SystemServiceRegistry.registerContextAwareService(
- Context.WIFI_RTT_RANGING_SERVICE,
- WifiRttManager.class,
- (context, serviceBinder) -> {
- IWifiRttManager service = IWifiRttManager.Stub.asInterface(serviceBinder);
- return new WifiRttManager(context, service);
- }
- );
- SystemServiceRegistry.registerContextAwareService(
- Context.WIFI_RTT_SERVICE,
- RttManager.class,
- context -> {
- WifiRttManager wifiRttManager = context.getSystemService(WifiRttManager.class);
- return new RttManager(context, wifiRttManager);
- }
- );
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiInfo.java b/wifi/java/android/net/wifi/WifiInfo.java
deleted file mode 100644
index eb26228e62384..0000000000000
--- a/wifi/java/android/net/wifi/WifiInfo.java
+++ /dev/null
@@ -1,1277 +0,0 @@
-/*
- * Copyright (C) 2008 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 android.net.wifi;
-
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.net.NetworkInfo.DetailedState;
-import android.net.TransportInfo;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.telephony.SubscriptionManager;
-import android.text.TextUtils;
-
-import com.android.modules.utils.build.SdkLevel;
-import com.android.net.module.util.Inet4AddressUtils;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.EnumMap;
-import java.util.Locale;
-import java.util.Objects;
-
-/**
- * Describes the state of any Wi-Fi connection that is active or
- * is in the process of being set up.
- *
- * In the connected state, access to location sensitive fields requires
- * the same permissions as {@link WifiManager#getScanResults}. If such access is not allowed,
- * {@link #getSSID} will return {@link WifiManager#UNKNOWN_SSID} and
- * {@link #getBSSID} will return {@code "02:00:00:00:00:00"}.
- * {@link #getNetworkId()} will return {@code -1}.
- * {@link #getPasspointFqdn()} will return null.
- * {@link #getPasspointProviderFriendlyName()} will return null.
- */
-public class WifiInfo implements TransportInfo, Parcelable {
- private static final String TAG = "WifiInfo";
- /**
- * This is the map described in the Javadoc comment above. The positions
- * of the elements of the array must correspond to the ordinal values
- * of DetailedState.
- */
- private static final EnumMap stateMap =
- new EnumMap(SupplicantState.class);
-
- /**
- * Default MAC address reported to a client that does not have the
- * android.permission.LOCAL_MAC_ADDRESS permission.
- *
- * @hide
- */
- @SystemApi
- public static final String DEFAULT_MAC_ADDRESS = "02:00:00:00:00:00";
-
- static {
- stateMap.put(SupplicantState.DISCONNECTED, DetailedState.DISCONNECTED);
- stateMap.put(SupplicantState.INTERFACE_DISABLED, DetailedState.DISCONNECTED);
- stateMap.put(SupplicantState.INACTIVE, DetailedState.IDLE);
- stateMap.put(SupplicantState.SCANNING, DetailedState.SCANNING);
- stateMap.put(SupplicantState.AUTHENTICATING, DetailedState.CONNECTING);
- stateMap.put(SupplicantState.ASSOCIATING, DetailedState.CONNECTING);
- stateMap.put(SupplicantState.ASSOCIATED, DetailedState.CONNECTING);
- stateMap.put(SupplicantState.FOUR_WAY_HANDSHAKE, DetailedState.AUTHENTICATING);
- stateMap.put(SupplicantState.GROUP_HANDSHAKE, DetailedState.AUTHENTICATING);
- stateMap.put(SupplicantState.COMPLETED, DetailedState.OBTAINING_IPADDR);
- stateMap.put(SupplicantState.DORMANT, DetailedState.DISCONNECTED);
- stateMap.put(SupplicantState.UNINITIALIZED, DetailedState.IDLE);
- stateMap.put(SupplicantState.INVALID, DetailedState.FAILED);
- }
-
- private SupplicantState mSupplicantState;
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- private String mBSSID;
- @UnsupportedAppUsage
- private WifiSsid mWifiSsid;
- private int mNetworkId;
-
- /**
- * Used to indicate that the RSSI is invalid, for example if no RSSI measurements are available
- * yet.
- * @hide
- */
- @SystemApi
- public static final int INVALID_RSSI = -127;
-
- /** @hide **/
- public static final int MIN_RSSI = -126;
-
- /** @hide **/
- public static final int MAX_RSSI = 200;
-
-
- /**
- * Received Signal Strength Indicator
- */
- private int mRssi;
-
- /**
- * Wi-Fi standard for the connection
- */
- private @WifiAnnotations.WifiStandard int mWifiStandard;
-
- /**
- * The unit in which links speeds are expressed.
- */
- public static final String LINK_SPEED_UNITS = "Mbps";
- private int mLinkSpeed;
-
- /**
- * Constant for unknown link speed.
- */
- public static final int LINK_SPEED_UNKNOWN = -1;
-
- /**
- * Tx(transmit) Link speed in Mbps
- */
- private int mTxLinkSpeed;
-
- /**
- * Max supported Tx(transmit) link speed in Mbps
- */
- private int mMaxSupportedTxLinkSpeed;
-
- /**
- * Rx(receive) Link speed in Mbps
- */
- private int mRxLinkSpeed;
-
- /**
- * Max supported Rx(receive) link speed in Mbps
- */
- private int mMaxSupportedRxLinkSpeed;
-
- /**
- * Frequency in MHz
- */
- public static final String FREQUENCY_UNITS = "MHz";
- private int mFrequency;
-
- @UnsupportedAppUsage
- private InetAddress mIpAddress;
- @UnsupportedAppUsage
- private String mMacAddress = DEFAULT_MAC_ADDRESS;
-
- /**
- * Whether the network is ephemeral or not.
- */
- private boolean mEphemeral;
-
- /**
- * Whether the network is trusted or not.
- */
- private boolean mTrusted;
-
- /**
- * Whether the network is oem paid or not.
- */
- private boolean mOemPaid;
-
- /**
- * Whether the network is oem private or not.
- */
- private boolean mOemPrivate;
-
- /**
- * Whether the network is a carrier merged network.
- */
- private boolean mCarrierMerged;
-
- /**
- * OSU (Online Sign Up) AP for Passpoint R2.
- */
- private boolean mOsuAp;
-
- /**
- * Fully qualified domain name of a Passpoint configuration
- */
- private String mFqdn;
-
- /**
- * Name of Passpoint credential provider
- */
- private String mProviderFriendlyName;
-
- /**
- * If connected to a network suggestion or specifier, store the package name of the app,
- * else null.
- */
- private String mRequestingPackageName;
-
- /**
- * Identify which Telephony subscription provides this network.
- */
- private int mSubscriptionId;
-
- /**
- * Running total count of lost (not ACKed) transmitted unicast data packets.
- * @hide
- */
- public long txBad;
- /**
- * Running total count of transmitted unicast data retry packets.
- * @hide
- */
- public long txRetries;
- /**
- * Running total count of successfully transmitted (ACKed) unicast data packets.
- * @hide
- */
- public long txSuccess;
- /**
- * Running total count of received unicast data packets.
- * @hide
- */
- public long rxSuccess;
-
- private double mLostTxPacketsPerSecond;
-
- /**
- * Average rate of lost transmitted packets, in units of packets per second.
- * @hide
- */
- @SystemApi
- public double getLostTxPacketsPerSecond() {
- return mLostTxPacketsPerSecond;
- }
-
- /** @hide */
- public void setLostTxPacketsPerSecond(double lostTxPacketsPerSecond) {
- mLostTxPacketsPerSecond = lostTxPacketsPerSecond;
- }
-
- private double mTxRetriedTxPacketsPerSecond;
-
- /**
- * Average rate of transmitted retry packets, in units of packets per second.
- * @hide
- */
- @SystemApi
- public double getRetriedTxPacketsPerSecond() {
- return mTxRetriedTxPacketsPerSecond;
- }
-
- /** @hide */
- public void setRetriedTxPacketsRate(double txRetriedTxPacketsPerSecond) {
- mTxRetriedTxPacketsPerSecond = txRetriedTxPacketsPerSecond;
- }
-
- private double mSuccessfulTxPacketsPerSecond;
-
- /**
- * Average rate of successfully transmitted unicast packets, in units of packets per second.
- * @hide
- */
- @SystemApi
- public double getSuccessfulTxPacketsPerSecond() {
- return mSuccessfulTxPacketsPerSecond;
- }
-
- /** @hide */
- public void setSuccessfulTxPacketsPerSecond(double successfulTxPacketsPerSecond) {
- mSuccessfulTxPacketsPerSecond = successfulTxPacketsPerSecond;
- }
-
- private double mSuccessfulRxPacketsPerSecond;
-
- /**
- * Average rate of received unicast data packets, in units of packets per second.
- * @hide
- */
- @SystemApi
- public double getSuccessfulRxPacketsPerSecond() {
- return mSuccessfulRxPacketsPerSecond;
- }
-
- /** @hide */
- public void setSuccessfulRxPacketsPerSecond(double successfulRxPacketsPerSecond) {
- mSuccessfulRxPacketsPerSecond = successfulRxPacketsPerSecond;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public int score;
-
- /**
- * The current Wifi score.
- * NOTE: this value should only be used for debugging purposes. Do not rely on this value for
- * any computations. The meaning of this value can and will change at any time without warning.
- * @hide
- */
- @SystemApi
- public int getScore() {
- return score;
- }
-
- /** @hide */
- public void setScore(int score) {
- this.score = score;
- }
-
- /**
- * Flag indicating that AP has hinted that upstream connection is metered,
- * and sensitive to heavy data transfers.
- */
- private boolean mMeteredHint;
-
- /**
- * Passpoint unique key
- */
- private String mPasspointUniqueId;
-
- /** @hide */
- @UnsupportedAppUsage
- public WifiInfo() {
- mWifiSsid = null;
- mBSSID = null;
- mNetworkId = -1;
- mSupplicantState = SupplicantState.UNINITIALIZED;
- mRssi = INVALID_RSSI;
- mLinkSpeed = LINK_SPEED_UNKNOWN;
- mFrequency = -1;
- mSubscriptionId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
- }
-
- /** @hide */
- public void reset() {
- setInetAddress(null);
- setBSSID(null);
- setSSID(null);
- setNetworkId(-1);
- setRssi(INVALID_RSSI);
- setLinkSpeed(LINK_SPEED_UNKNOWN);
- setTxLinkSpeedMbps(LINK_SPEED_UNKNOWN);
- setRxLinkSpeedMbps(LINK_SPEED_UNKNOWN);
- setMaxSupportedTxLinkSpeedMbps(LINK_SPEED_UNKNOWN);
- setMaxSupportedRxLinkSpeedMbps(LINK_SPEED_UNKNOWN);
- setFrequency(-1);
- setMeteredHint(false);
- setEphemeral(false);
- setTrusted(false);
- setOemPaid(false);
- setOemPrivate(false);
- setCarrierMerged(false);
- setOsuAp(false);
- setRequestingPackageName(null);
- setFQDN(null);
- setProviderFriendlyName(null);
- setPasspointUniqueId(null);
- setSubscriptionId(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
- txBad = 0;
- txSuccess = 0;
- rxSuccess = 0;
- txRetries = 0;
- mLostTxPacketsPerSecond = 0;
- mSuccessfulTxPacketsPerSecond = 0;
- mSuccessfulRxPacketsPerSecond = 0;
- mTxRetriedTxPacketsPerSecond = 0;
- score = 0;
- }
-
- /**
- * Copy constructor
- * @hide
- */
- public WifiInfo(WifiInfo source) {
- if (source != null) {
- mSupplicantState = source.mSupplicantState;
- mBSSID = source.mBSSID;
- mWifiSsid = source.mWifiSsid;
- mNetworkId = source.mNetworkId;
- mRssi = source.mRssi;
- mLinkSpeed = source.mLinkSpeed;
- mTxLinkSpeed = source.mTxLinkSpeed;
- mRxLinkSpeed = source.mRxLinkSpeed;
- mFrequency = source.mFrequency;
- mIpAddress = source.mIpAddress;
- mMacAddress = source.mMacAddress;
- mMeteredHint = source.mMeteredHint;
- mEphemeral = source.mEphemeral;
- mTrusted = source.mTrusted;
- mOemPaid = source.mOemPaid;
- mOemPrivate = source.mOemPrivate;
- mCarrierMerged = source.mCarrierMerged;
- mRequestingPackageName =
- source.mRequestingPackageName;
- mOsuAp = source.mOsuAp;
- mFqdn = source.mFqdn;
- mProviderFriendlyName = source.mProviderFriendlyName;
- mSubscriptionId = source.mSubscriptionId;
- txBad = source.txBad;
- txRetries = source.txRetries;
- txSuccess = source.txSuccess;
- rxSuccess = source.rxSuccess;
- mLostTxPacketsPerSecond = source.mLostTxPacketsPerSecond;
- mTxRetriedTxPacketsPerSecond = source.mTxRetriedTxPacketsPerSecond;
- mSuccessfulTxPacketsPerSecond = source.mSuccessfulTxPacketsPerSecond;
- mSuccessfulRxPacketsPerSecond = source.mSuccessfulRxPacketsPerSecond;
- score = source.score;
- mWifiStandard = source.mWifiStandard;
- mMaxSupportedTxLinkSpeed = source.mMaxSupportedTxLinkSpeed;
- mMaxSupportedRxLinkSpeed = source.mMaxSupportedRxLinkSpeed;
- mPasspointUniqueId = source.mPasspointUniqueId;
- }
- }
-
- /** Builder for WifiInfo */
- public static final class Builder {
- private final WifiInfo mWifiInfo = new WifiInfo();
-
- /**
- * Set the SSID, in the form of a raw byte array.
- * @see WifiInfo#getSSID()
- */
- @NonNull
- public Builder setSsid(@NonNull byte[] ssid) {
- mWifiInfo.setSSID(WifiSsid.createFromByteArray(ssid));
- return this;
- }
-
- /**
- * Set the BSSID.
- * @see WifiInfo#getBSSID()
- */
- @NonNull
- public Builder setBssid(@NonNull String bssid) {
- mWifiInfo.setBSSID(bssid);
- return this;
- }
-
- /**
- * Set the RSSI, in dBm.
- * @see WifiInfo#getRssi()
- */
- @NonNull
- public Builder setRssi(int rssi) {
- mWifiInfo.setRssi(rssi);
- return this;
- }
-
- /**
- * Set the network ID.
- * @see WifiInfo#getNetworkId()
- */
- @NonNull
- public Builder setNetworkId(int networkId) {
- mWifiInfo.setNetworkId(networkId);
- return this;
- }
-
- /**
- * Build a WifiInfo object.
- */
- @NonNull
- public WifiInfo build() {
- return new WifiInfo(mWifiInfo);
- }
- }
-
- /** @hide */
- public void setSSID(WifiSsid wifiSsid) {
- mWifiSsid = wifiSsid;
- }
-
- /**
- * Returns the service set identifier (SSID) of the current 802.11 network.
- *
- * If the SSID can be decoded as UTF-8, it will be returned surrounded by double
- * quotation marks. Otherwise, it is returned as a string of hex digits.
- * The SSID may be {@link WifiManager#UNKNOWN_SSID}, if there is no network currently connected
- * or if the caller has insufficient permissions to access the SSID.
- *
- *
- * Prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}, this method
- * always returned the SSID with no quotes around it.
- *
- *
- * @return the SSID.
- */
- public String getSSID() {
- if (mWifiSsid != null) {
- String unicode = mWifiSsid.toString();
- if (!TextUtils.isEmpty(unicode)) {
- return "\"" + unicode + "\"";
- } else {
- String hex = mWifiSsid.getHexString();
- return (hex != null) ? hex : WifiManager.UNKNOWN_SSID;
- }
- }
- return WifiManager.UNKNOWN_SSID;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public WifiSsid getWifiSsid() {
- return mWifiSsid;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setBSSID(String BSSID) {
- mBSSID = BSSID;
- }
-
- /**
- * Return the basic service set identifier (BSSID) of the current access point.
- *
- * The BSSID may be
- * {@code null}, if there is no network currently connected.
- * {@code "02:00:00:00:00:00"}, if the caller has insufficient permissions to access the
- * BSSID.
- *
- *
- * @return the BSSID, in the form of a six-byte MAC address: {@code XX:XX:XX:XX:XX:XX}
- */
- public String getBSSID() {
- return mBSSID;
- }
-
- /**
- * Returns the received signal strength indicator of the current 802.11
- * network, in dBm.
- *
- * Use {@link android.net.wifi.WifiManager#calculateSignalLevel} to convert this number into
- * an absolute signal level which can be displayed to a user.
- *
- * @return the RSSI.
- */
- public int getRssi() {
- return mRssi;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setRssi(int rssi) {
- if (rssi < INVALID_RSSI)
- rssi = INVALID_RSSI;
- if (rssi > MAX_RSSI)
- rssi = MAX_RSSI;
- mRssi = rssi;
- }
-
- /**
- * Sets the Wi-Fi standard
- * @hide
- */
- public void setWifiStandard(@WifiAnnotations.WifiStandard int wifiStandard) {
- mWifiStandard = wifiStandard;
- }
-
- /**
- * Get connection Wi-Fi standard
- * @return the connection Wi-Fi standard
- */
- public @WifiAnnotations.WifiStandard int getWifiStandard() {
- return mWifiStandard;
- }
-
- /**
- * Returns the current link speed in {@link #LINK_SPEED_UNITS}.
- * @return the link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is unknown.
- * @see #LINK_SPEED_UNITS
- * @see #LINK_SPEED_UNKNOWN
- */
- public int getLinkSpeed() {
- return mLinkSpeed;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setLinkSpeed(int linkSpeed) {
- mLinkSpeed = linkSpeed;
- }
-
- /**
- * Returns the current transmit link speed in Mbps.
- * @return the Tx link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is unknown.
- * @see #LINK_SPEED_UNKNOWN
- */
- @IntRange(from = -1)
- public int getTxLinkSpeedMbps() {
- return mTxLinkSpeed;
- }
-
- /**
- * Returns the maximum supported transmit link speed in Mbps
- * @return the max supported tx link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is
- * unknown. @see #LINK_SPEED_UNKNOWN
- */
- public int getMaxSupportedTxLinkSpeedMbps() {
- return mMaxSupportedTxLinkSpeed;
- }
-
- /**
- * Update the last transmitted packet bit rate in Mbps.
- * @hide
- */
- public void setTxLinkSpeedMbps(int txLinkSpeed) {
- mTxLinkSpeed = txLinkSpeed;
- }
-
- /**
- * Set the maximum supported transmit link speed in Mbps
- * @hide
- */
- public void setMaxSupportedTxLinkSpeedMbps(int maxSupportedTxLinkSpeed) {
- mMaxSupportedTxLinkSpeed = maxSupportedTxLinkSpeed;
- }
-
- /**
- * Returns the current receive link speed in Mbps.
- * @return the Rx link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is unknown.
- * @see #LINK_SPEED_UNKNOWN
- */
- @IntRange(from = -1)
- public int getRxLinkSpeedMbps() {
- return mRxLinkSpeed;
- }
-
- /**
- * Returns the maximum supported receive link speed in Mbps
- * @return the max supported Rx link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is
- * unknown. @see #LINK_SPEED_UNKNOWN
- */
- public int getMaxSupportedRxLinkSpeedMbps() {
- return mMaxSupportedRxLinkSpeed;
- }
-
- /**
- * Update the last received packet bit rate in Mbps.
- * @hide
- */
- public void setRxLinkSpeedMbps(int rxLinkSpeed) {
- mRxLinkSpeed = rxLinkSpeed;
- }
-
- /**
- * Set the maximum supported receive link speed in Mbps
- * @hide
- */
- public void setMaxSupportedRxLinkSpeedMbps(int maxSupportedRxLinkSpeed) {
- mMaxSupportedRxLinkSpeed = maxSupportedRxLinkSpeed;
- }
-
- /**
- * Returns the current frequency in {@link #FREQUENCY_UNITS}.
- * @return the frequency.
- * @see #FREQUENCY_UNITS
- */
- public int getFrequency() {
- return mFrequency;
- }
-
- /** @hide */
- public void setFrequency(int frequency) {
- this.mFrequency = frequency;
- }
-
- /**
- * @hide
- */
- public boolean is24GHz() {
- return ScanResult.is24GHz(mFrequency);
- }
-
- /**
- * @hide
- */
- @UnsupportedAppUsage
- public boolean is5GHz() {
- return ScanResult.is5GHz(mFrequency);
- }
-
- /**
- * @hide
- */
- public boolean is6GHz() {
- return ScanResult.is6GHz(mFrequency);
- }
-
- /**
- * Record the MAC address of the WLAN interface
- * @param macAddress the MAC address in {@code XX:XX:XX:XX:XX:XX} form
- * @hide
- */
- @UnsupportedAppUsage
- public void setMacAddress(String macAddress) {
- this.mMacAddress = macAddress;
- }
-
- public String getMacAddress() {
- return mMacAddress;
- }
-
- /**
- * @return true if {@link #getMacAddress()} has a real MAC address.
- *
- * @hide
- */
- public boolean hasRealMacAddress() {
- return mMacAddress != null && !DEFAULT_MAC_ADDRESS.equals(mMacAddress);
- }
-
- /**
- * Indicates if we've dynamically detected this active network connection as
- * being metered.
- *
- * @see WifiConfiguration#isMetered(WifiConfiguration, WifiInfo)
- * @hide
- */
- public void setMeteredHint(boolean meteredHint) {
- mMeteredHint = meteredHint;
- }
-
- /** {@hide} */
- @UnsupportedAppUsage
- public boolean getMeteredHint() {
- return mMeteredHint;
- }
-
- /** {@hide} */
- public void setEphemeral(boolean ephemeral) {
- mEphemeral = ephemeral;
- }
-
- /**
- * Returns true if the current Wifi network is ephemeral, false otherwise.
- * An ephemeral network is a network that is temporary and not persisted in the system.
- * Ephemeral networks cannot be forgotten, only disabled with
- * {@link WifiManager#disableEphemeralNetwork(String)}.
- *
- * @hide
- */
- @SystemApi
- public boolean isEphemeral() {
- return mEphemeral;
- }
-
- /** {@hide} */
- public void setTrusted(boolean trusted) {
- mTrusted = trusted;
- }
-
- /**
- * Returns true if the current Wifi network is a trusted network, false otherwise.
- * @see WifiNetworkSuggestion.Builder#setUntrusted(boolean).
- * {@hide}
- */
- @SystemApi
- public boolean isTrusted() {
- return mTrusted;
- }
-
- /** {@hide} */
- public void setOemPaid(boolean oemPaid) {
- mOemPaid = oemPaid;
- }
-
- /**
- * Returns true if the current Wifi network is an oem paid network, false otherwise.
- * @see WifiNetworkSuggestion.Builder#setOemPaid(boolean).
- * {@hide}
- */
- @SystemApi
- public boolean isOemPaid() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mOemPaid;
- }
-
- /** {@hide} */
- public void setOemPrivate(boolean oemPrivate) {
- mOemPrivate = oemPrivate;
- }
-
- /**
- * Returns true if the current Wifi network is an oem private network, false otherwise.
- * @see WifiNetworkSuggestion.Builder#setOemPrivate(boolean).
- * {@hide}
- */
- @SystemApi
- public boolean isOemPrivate() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mOemPrivate;
- }
-
- /**
- * {@hide}
- */
- public void setCarrierMerged(boolean carrierMerged) {
- mCarrierMerged = carrierMerged;
- }
-
- /**
- * Returns true if the current Wifi network is a carrier merged network, false otherwise.
- * @see WifiNetworkSuggestion.Builder#setCarrierMerged(boolean).
- * {@hide}
- */
- @SystemApi
- public boolean isCarrierMerged() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mCarrierMerged;
- }
-
-
- /** {@hide} */
- public void setOsuAp(boolean osuAp) {
- mOsuAp = osuAp;
- }
-
- /** {@hide} */
- @SystemApi
- public boolean isOsuAp() {
- return mOsuAp;
- }
-
- /** {@hide} */
- @SystemApi
- public boolean isPasspointAp() {
- return mFqdn != null && mProviderFriendlyName != null;
- }
-
- /** {@hide} */
- public void setFQDN(@Nullable String fqdn) {
- mFqdn = fqdn;
- }
-
- /**
- * Returns the Fully Qualified Domain Name of the network if it is a Passpoint network.
- *
- * The FQDN may be
- * {@code null} if no network currently connected, currently connected network is not
- * passpoint network or the caller has insufficient permissions to access the FQDN.
- *
- */
- public @Nullable String getPasspointFqdn() {
- return mFqdn;
- }
-
- /** {@hide} */
- public void setProviderFriendlyName(@Nullable String providerFriendlyName) {
- mProviderFriendlyName = providerFriendlyName;
- }
-
- /**
- * Returns the Provider Friendly Name of the network if it is a Passpoint network.
- *
- * The Provider Friendly Name may be
- * {@code null} if no network currently connected, currently connected network is not
- * passpoint network or the caller has insufficient permissions to access the Provider Friendly
- * Name.
- *
- */
- public @Nullable String getPasspointProviderFriendlyName() {
- return mProviderFriendlyName;
- }
-
- /** {@hide} */
- public void setRequestingPackageName(@Nullable String packageName) {
- mRequestingPackageName = packageName;
- }
-
- /**
- * If this network was created in response to an app request (e.g. through Network Suggestion
- * or Network Specifier), return the package name of the app that made the request.
- * Null otherwise.
- * @hide
- */
- @SystemApi
- public @Nullable String getRequestingPackageName() {
- return mRequestingPackageName;
- }
-
- /** {@hide} */
- public void setSubscriptionId(int subId) {
- mSubscriptionId = subId;
- }
-
- /**
- * If this network is provisioned by a carrier, returns subscription Id corresponding to the
- * associated SIM on the device. If this network is not provisioned by a carrier, returns
- * {@link android.telephony.SubscriptionManager#INVALID_SUBSCRIPTION_ID}
- *
- * @see WifiNetworkSuggestion.Builder#setSubscriptionId(int)
- * @see android.telephony.SubscriptionInfo#getSubscriptionId()
- * {@hide}
- */
- @SystemApi
- public int getSubscriptionId() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mSubscriptionId;
- }
-
-
- /** @hide */
- @UnsupportedAppUsage
- public void setNetworkId(int id) {
- mNetworkId = id;
- }
-
- /**
- * Each configured network has a unique small integer ID, used to identify
- * the network. This method returns the ID for the currently connected network.
- *
- * The networkId may be {@code -1} if there is no currently connected network or if the caller
- * has insufficient permissions to access the network ID.
- *
- *
- * @return the network ID.
- */
- public int getNetworkId() {
- return mNetworkId;
- }
-
- /**
- * Return the detailed state of the supplicant's negotiation with an
- * access point, in the form of a {@link SupplicantState SupplicantState} object.
- * @return the current {@link SupplicantState SupplicantState}
- */
- public SupplicantState getSupplicantState() {
- return mSupplicantState;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setSupplicantState(SupplicantState state) {
- mSupplicantState = state;
- }
-
- /** @hide */
- public void setInetAddress(InetAddress address) {
- mIpAddress = address;
- }
-
- public int getIpAddress() {
- int result = 0;
- if (mIpAddress instanceof Inet4Address) {
- result = Inet4AddressUtils.inet4AddressToIntHTL((Inet4Address) mIpAddress);
- }
- return result;
- }
-
- /**
- * @return {@code true} if this network does not broadcast its SSID, so an
- * SSID-specific probe request must be used for scans.
- */
- public boolean getHiddenSSID() {
- if (mWifiSsid == null) return false;
- return mWifiSsid.isHidden();
- }
-
- /**
- * Map a supplicant state into a fine-grained network connectivity state.
- * @param suppState the supplicant state
- * @return the corresponding {@link DetailedState}
- */
- public static DetailedState getDetailedStateOf(SupplicantState suppState) {
- return stateMap.get(suppState);
- }
-
- /**
- * Set the SupplicantState from the string name
- * of the state.
- * @param stateName the name of the state, as a String returned
- * in an event sent by {@code wpa_supplicant}.
- */
- @UnsupportedAppUsage
- void setSupplicantState(String stateName) {
- mSupplicantState = valueOf(stateName);
- }
-
- static SupplicantState valueOf(String stateName) {
- if ("4WAY_HANDSHAKE".equalsIgnoreCase(stateName))
- return SupplicantState.FOUR_WAY_HANDSHAKE;
- else {
- try {
- return SupplicantState.valueOf(stateName.toUpperCase(Locale.ROOT));
- } catch (IllegalArgumentException e) {
- return SupplicantState.INVALID;
- }
- }
- }
-
- /**
- * Remove double quotes (") surrounding a SSID string, if present. Otherwise, return the
- * string unmodified. Return null if the input string was null.
- * @hide
- */
- @Nullable
- @SystemApi
- public static String sanitizeSsid(@Nullable String string) {
- return removeDoubleQuotes(string);
- }
-
- /** @hide */
- @UnsupportedAppUsage
- @Nullable
- public static String removeDoubleQuotes(@Nullable String string) {
- if (string == null) return null;
- final int length = string.length();
- if ((length > 1) && (string.charAt(0) == '"') && (string.charAt(length - 1) == '"')) {
- return string.substring(1, length - 1);
- }
- return string;
- }
-
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- String none = "";
-
- sb.append("SSID: ").append(mWifiSsid == null ? WifiManager.UNKNOWN_SSID : mWifiSsid)
- .append(", BSSID: ").append(mBSSID == null ? none : mBSSID)
- .append(", MAC: ").append(mMacAddress == null ? none : mMacAddress)
- .append(", Supplicant state: ")
- .append(mSupplicantState == null ? none : mSupplicantState)
- .append(", Wi-Fi standard: ").append(mWifiStandard)
- .append(", RSSI: ").append(mRssi)
- .append(", Link speed: ").append(mLinkSpeed).append(LINK_SPEED_UNITS)
- .append(", Tx Link speed: ").append(mTxLinkSpeed).append(LINK_SPEED_UNITS)
- .append(", Max Supported Tx Link speed: ")
- .append(mMaxSupportedTxLinkSpeed).append(LINK_SPEED_UNITS)
- .append(", Rx Link speed: ").append(mRxLinkSpeed).append(LINK_SPEED_UNITS)
- .append(", Max Supported Rx Link speed: ")
- .append(mMaxSupportedRxLinkSpeed).append(LINK_SPEED_UNITS)
- .append(", Frequency: ").append(mFrequency).append(FREQUENCY_UNITS)
- .append(", Net ID: ").append(mNetworkId)
- .append(", Metered hint: ").append(mMeteredHint)
- .append(", score: ").append(Integer.toString(score));
- return sb.toString();
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mNetworkId);
- dest.writeInt(mRssi);
- dest.writeInt(mLinkSpeed);
- dest.writeInt(mTxLinkSpeed);
- dest.writeInt(mRxLinkSpeed);
- dest.writeInt(mFrequency);
- if (mIpAddress != null) {
- dest.writeByte((byte)1);
- dest.writeByteArray(mIpAddress.getAddress());
- } else {
- dest.writeByte((byte)0);
- }
- if (mWifiSsid != null) {
- dest.writeInt(1);
- mWifiSsid.writeToParcel(dest, flags);
- } else {
- dest.writeInt(0);
- }
- dest.writeString(mBSSID);
- dest.writeString(mMacAddress);
- dest.writeInt(mMeteredHint ? 1 : 0);
- dest.writeInt(mEphemeral ? 1 : 0);
- dest.writeInt(mTrusted ? 1 : 0);
- dest.writeInt(mOemPaid ? 1 : 0);
- dest.writeInt(mOemPrivate ? 1 : 0);
- dest.writeInt(mCarrierMerged ? 1 : 0);
- dest.writeInt(score);
- dest.writeLong(txSuccess);
- dest.writeDouble(mSuccessfulTxPacketsPerSecond);
- dest.writeLong(txRetries);
- dest.writeDouble(mTxRetriedTxPacketsPerSecond);
- dest.writeLong(txBad);
- dest.writeDouble(mLostTxPacketsPerSecond);
- dest.writeLong(rxSuccess);
- dest.writeDouble(mSuccessfulRxPacketsPerSecond);
- mSupplicantState.writeToParcel(dest, flags);
- dest.writeInt(mOsuAp ? 1 : 0);
- dest.writeString(mRequestingPackageName);
- dest.writeString(mFqdn);
- dest.writeString(mProviderFriendlyName);
- dest.writeInt(mWifiStandard);
- dest.writeInt(mMaxSupportedTxLinkSpeed);
- dest.writeInt(mMaxSupportedRxLinkSpeed);
- dest.writeString(mPasspointUniqueId);
- dest.writeInt(mSubscriptionId);
- }
-
- /** Implement the Parcelable interface {@hide} */
- @UnsupportedAppUsage
- public static final @android.annotation.NonNull Creator CREATOR =
- new Creator() {
- public WifiInfo createFromParcel(Parcel in) {
- WifiInfo info = new WifiInfo();
- info.setNetworkId(in.readInt());
- info.setRssi(in.readInt());
- info.setLinkSpeed(in.readInt());
- info.setTxLinkSpeedMbps(in.readInt());
- info.setRxLinkSpeedMbps(in.readInt());
- info.setFrequency(in.readInt());
- if (in.readByte() == 1) {
- try {
- info.setInetAddress(InetAddress.getByAddress(in.createByteArray()));
- } catch (UnknownHostException e) {}
- }
- if (in.readInt() == 1) {
- info.mWifiSsid = WifiSsid.CREATOR.createFromParcel(in);
- }
- info.mBSSID = in.readString();
- info.mMacAddress = in.readString();
- info.mMeteredHint = in.readInt() != 0;
- info.mEphemeral = in.readInt() != 0;
- info.mTrusted = in.readInt() != 0;
- info.mOemPaid = in.readInt() != 0;
- info.mOemPrivate = in.readInt() != 0;
- info.mCarrierMerged = in.readInt() != 0;
- info.score = in.readInt();
- info.txSuccess = in.readLong();
- info.mSuccessfulTxPacketsPerSecond = in.readDouble();
- info.txRetries = in.readLong();
- info.mTxRetriedTxPacketsPerSecond = in.readDouble();
- info.txBad = in.readLong();
- info.mLostTxPacketsPerSecond = in.readDouble();
- info.rxSuccess = in.readLong();
- info.mSuccessfulRxPacketsPerSecond = in.readDouble();
- info.mSupplicantState = SupplicantState.CREATOR.createFromParcel(in);
- info.mOsuAp = in.readInt() != 0;
- info.mRequestingPackageName = in.readString();
- info.mFqdn = in.readString();
- info.mProviderFriendlyName = in.readString();
- info.mWifiStandard = in.readInt();
- info.mMaxSupportedTxLinkSpeed = in.readInt();
- info.mMaxSupportedRxLinkSpeed = in.readInt();
- info.mPasspointUniqueId = in.readString();
- info.mSubscriptionId = in.readInt();
- return info;
- }
-
- public WifiInfo[] newArray(int size) {
- return new WifiInfo[size];
- }
- };
-
- /**
- * Set the Passpoint unique identifier for the current connection
- *
- * @param passpointUniqueId Unique identifier
- * @hide
- */
- public void setPasspointUniqueId(@Nullable String passpointUniqueId) {
- mPasspointUniqueId = passpointUniqueId;
- }
-
- /**
- * Get the Passpoint unique identifier for the current connection
- *
- * @return Passpoint unique identifier
- * @hide
- */
- public @Nullable String getPasspointUniqueId() {
- return mPasspointUniqueId;
- }
-
- @Override
- public boolean equals(Object that) {
- if (this == that) return true;
-
- // Potential API behavior change, so don't change behavior on older devices.
- if (!SdkLevel.isAtLeastS()) return false;
-
- if (!(that instanceof WifiInfo)) return false;
-
- WifiInfo thatWifiInfo = (WifiInfo) that;
- return Objects.equals(mWifiSsid, thatWifiInfo.mWifiSsid)
- && Objects.equals(mBSSID, thatWifiInfo.mBSSID)
- && Objects.equals(mNetworkId, thatWifiInfo.mNetworkId)
- && Objects.equals(mRssi, thatWifiInfo.mRssi)
- && Objects.equals(mSupplicantState, thatWifiInfo.mSupplicantState)
- && Objects.equals(mLinkSpeed, thatWifiInfo.mLinkSpeed)
- && Objects.equals(mTxLinkSpeed, thatWifiInfo.mTxLinkSpeed)
- && Objects.equals(mRxLinkSpeed, thatWifiInfo.mRxLinkSpeed)
- && Objects.equals(mFrequency, thatWifiInfo.mFrequency)
- && Objects.equals(mIpAddress, thatWifiInfo.mIpAddress)
- && Objects.equals(mMacAddress, thatWifiInfo.mMacAddress)
- && Objects.equals(mMeteredHint, thatWifiInfo.mMeteredHint)
- && Objects.equals(mEphemeral, thatWifiInfo.mEphemeral)
- && Objects.equals(mTrusted, thatWifiInfo.mTrusted)
- && Objects.equals(mOemPaid, thatWifiInfo.mOemPaid)
- && Objects.equals(mOemPrivate, thatWifiInfo.mOemPrivate)
- && Objects.equals(mCarrierMerged, thatWifiInfo.mCarrierMerged)
- && Objects.equals(mRequestingPackageName, thatWifiInfo.mRequestingPackageName)
- && Objects.equals(mOsuAp, thatWifiInfo.mOsuAp)
- && Objects.equals(mFqdn, thatWifiInfo.mFqdn)
- && Objects.equals(mProviderFriendlyName, thatWifiInfo.mProviderFriendlyName)
- && Objects.equals(mSubscriptionId, thatWifiInfo.mSubscriptionId)
- && Objects.equals(txBad, thatWifiInfo.txBad)
- && Objects.equals(txRetries, thatWifiInfo.txRetries)
- && Objects.equals(txSuccess, thatWifiInfo.txSuccess)
- && Objects.equals(rxSuccess, thatWifiInfo.rxSuccess)
- && Objects.equals(mLostTxPacketsPerSecond, thatWifiInfo.mLostTxPacketsPerSecond)
- && Objects.equals(mTxRetriedTxPacketsPerSecond,
- thatWifiInfo.mTxRetriedTxPacketsPerSecond)
- && Objects.equals(mSuccessfulTxPacketsPerSecond,
- thatWifiInfo.mSuccessfulTxPacketsPerSecond)
- && Objects.equals(mSuccessfulRxPacketsPerSecond,
- thatWifiInfo.mSuccessfulRxPacketsPerSecond)
- && Objects.equals(score, thatWifiInfo.score)
- && Objects.equals(mWifiStandard, thatWifiInfo.mWifiStandard)
- && Objects.equals(mMaxSupportedTxLinkSpeed, thatWifiInfo.mMaxSupportedTxLinkSpeed)
- && Objects.equals(mMaxSupportedRxLinkSpeed, thatWifiInfo.mMaxSupportedRxLinkSpeed)
- && Objects.equals(mPasspointUniqueId, thatWifiInfo.mPasspointUniqueId);
- }
-
- @Override
- public int hashCode() {
- // Potential API behavior change, so don't change behavior on older devices.
- if (!SdkLevel.isAtLeastS()) return System.identityHashCode(this);
-
- return Objects.hash(mWifiSsid,
- mBSSID,
- mNetworkId,
- mRssi,
- mSupplicantState,
- mLinkSpeed,
- mTxLinkSpeed,
- mRxLinkSpeed,
- mFrequency,
- mIpAddress,
- mMacAddress,
- mMeteredHint,
- mEphemeral,
- mTrusted,
- mOemPaid,
- mOemPrivate,
- mCarrierMerged,
- mRequestingPackageName,
- mOsuAp,
- mFqdn,
- mProviderFriendlyName,
- mSubscriptionId,
- txBad,
- txRetries,
- txSuccess,
- rxSuccess,
- mLostTxPacketsPerSecond,
- mTxRetriedTxPacketsPerSecond,
- mSuccessfulTxPacketsPerSecond,
- mSuccessfulRxPacketsPerSecond,
- score,
- mWifiStandard,
- mMaxSupportedTxLinkSpeed,
- mMaxSupportedRxLinkSpeed,
- mPasspointUniqueId);
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
deleted file mode 100644
index 4e336ad41bd3a..0000000000000
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ /dev/null
@@ -1,7121 +0,0 @@
-/*
- * Copyright (C) 2008 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 android.net.wifi;
-
-import static android.Manifest.permission.ACCESS_FINE_LOCATION;
-import static android.Manifest.permission.ACCESS_WIFI_STATE;
-import static android.Manifest.permission.READ_WIFI_CREDENTIAL;
-
-import android.annotation.CallbackExecutor;
-import android.annotation.IntDef;
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
-import android.annotation.SdkConstant;
-import android.annotation.SdkConstant.SdkConstantType;
-import android.annotation.SuppressLint;
-import android.annotation.SystemApi;
-import android.annotation.SystemService;
-import android.app.ActivityManager;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.content.Context;
-import android.net.ConnectivityManager;
-import android.net.ConnectivityManager.NetworkCallback;
-import android.net.DhcpInfo;
-import android.net.MacAddress;
-import android.net.Network;
-import android.net.NetworkCapabilities;
-import android.net.NetworkStack;
-import android.net.wifi.hotspot2.IProvisioningCallback;
-import android.net.wifi.hotspot2.OsuProvider;
-import android.net.wifi.hotspot2.PasspointConfiguration;
-import android.net.wifi.hotspot2.ProvisioningCallback;
-import android.os.Binder;
-import android.os.Build;
-import android.os.Handler;
-import android.os.HandlerExecutor;
-import android.os.IBinder;
-import android.os.Looper;
-import android.os.RemoteException;
-import android.os.WorkSource;
-import android.os.connectivity.WifiActivityEnergyInfo;
-import android.telephony.SubscriptionInfo;
-import android.telephony.TelephonyManager;
-import android.text.TextUtils;
-import android.util.CloseGuard;
-import android.util.Log;
-import android.util.Pair;
-import android.util.SparseArray;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.modules.utils.ParceledListSlice;
-import com.android.modules.utils.build.SdkLevel;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.ref.Reference;
-import java.lang.ref.WeakReference;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.concurrent.Executor;
-
-/**
- * This class provides the primary API for managing all aspects of Wi-Fi
- * connectivity.
- *
- * On releases before {@link android.os.Build.VERSION_CODES#N}, this object
- * should only be obtained from an {@linkplain Context#getApplicationContext()
- * application context}, and not from any other derived context to avoid memory
- * leaks within the calling process.
- *
- * It deals with several categories of items:
- *
- *
- * - The list of configured networks. The list can be viewed and updated, and
- * attributes of individual entries can be modified.
- * - The currently active Wi-Fi network, if any. Connectivity can be
- * established or torn down, and dynamic information about the state of the
- * network can be queried.
- * - Results of access point scans, containing enough information to make
- * decisions about what access point to connect to.
- * - It defines the names of various Intent actions that are broadcast upon
- * any sort of change in Wi-Fi state.
- *
- *
- * This is the API to use when performing Wi-Fi specific operations. To perform
- * operations that pertain to network connectivity at an abstract level, use
- * {@link android.net.ConnectivityManager}.
- *
- */
-@SystemService(Context.WIFI_SERVICE)
-public class WifiManager {
-
- private static final String TAG = "WifiManager";
- // Supplicant error codes:
- /**
- * The error code if there was a problem authenticating.
- * @deprecated This is no longer supported.
- */
- @Deprecated
- public static final int ERROR_AUTHENTICATING = 1;
-
- /**
- * The reason code if there is no error during authentication.
- * It could also imply that there no authentication in progress,
- * this reason code also serves as a reset value.
- * @deprecated This is no longer supported.
- * @hide
- */
- @Deprecated
- public static final int ERROR_AUTH_FAILURE_NONE = 0;
-
- /**
- * The reason code if there was a timeout authenticating.
- * @deprecated This is no longer supported.
- * @hide
- */
- @Deprecated
- public static final int ERROR_AUTH_FAILURE_TIMEOUT = 1;
-
- /**
- * The reason code if there was a wrong password while
- * authenticating.
- * @deprecated This is no longer supported.
- * @hide
- */
- @Deprecated
- public static final int ERROR_AUTH_FAILURE_WRONG_PSWD = 2;
-
- /**
- * The reason code if there was EAP failure while
- * authenticating.
- * @deprecated This is no longer supported.
- * @hide
- */
- @Deprecated
- public static final int ERROR_AUTH_FAILURE_EAP_FAILURE = 3;
-
- /** @hide */
- public static final int NETWORK_SUGGESTIONS_MAX_PER_APP_LOW_RAM = 256;
-
- /** @hide */
- public static final int NETWORK_SUGGESTIONS_MAX_PER_APP_HIGH_RAM = 1024;
-
- /**
- * Reason code if all of the network suggestions were successfully added or removed.
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_SUCCESS = 0;
-
- /**
- * Reason code if there was an internal error in the platform while processing the addition or
- * removal of suggestions.
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL = 1;
-
- /**
- * Reason code if the user has disallowed "android:change_wifi_state" app-ops from the app.
- * @see android.app.AppOpsManager#unsafeCheckOp(String, int, String).
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_APP_DISALLOWED = 2;
-
- /**
- * Reason code if one or more of the network suggestions added already exists in platform's
- * database.
- * Note: this code will not be returned with Android 11 as in-place modification is allowed,
- * please check {@link #addNetworkSuggestions(List)}.
- * @see WifiNetworkSuggestion#equals(Object)
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE = 3;
-
- /**
- * Reason code if the number of network suggestions provided by the app crosses the max
- * threshold set per app.
- * The framework will reject all suggestions provided by {@link #addNetworkSuggestions(List)} if
- * the total size exceeds the limit.
- * @see #getMaxNumberOfNetworkSuggestionsPerApp()
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_EXCEEDS_MAX_PER_APP = 4;
-
- /**
- * Reason code if one or more of the network suggestions removed does not exist in platform's
- * database.
- * The framework won't remove any suggestions if one or more of suggestions provided
- * by {@link #removeNetworkSuggestions(List)} does not exist in database.
- * @see WifiNetworkSuggestion#equals(Object)
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID = 5;
-
- /**
- * Reason code if one or more of the network suggestions added is not allowed.
- * The framework will reject all suggestions provided by {@link #addNetworkSuggestions(List)}
- * if one or more of them is not allowed.
- * This error may be caused by suggestion is using SIM-based encryption method, but calling app
- * is not carrier privileged.
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_NOT_ALLOWED = 6;
-
- /**
- * Reason code if one or more of the network suggestions added is invalid. Framework will reject
- * all the suggestions in the list.
- * The framework will reject all suggestions provided by {@link #addNetworkSuggestions(List)}
- * if one or more of them is invalid.
- * Please use {@link WifiNetworkSuggestion.Builder} to create network suggestions.
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_INVALID = 7;
-
- /** @hide */
- @IntDef(prefix = { "STATUS_NETWORK_SUGGESTIONS_" }, value = {
- STATUS_NETWORK_SUGGESTIONS_SUCCESS,
- STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL,
- STATUS_NETWORK_SUGGESTIONS_ERROR_APP_DISALLOWED,
- STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE,
- STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_EXCEEDS_MAX_PER_APP,
- STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID,
- STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_NOT_ALLOWED,
- STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_INVALID,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface NetworkSuggestionsStatusCode {}
-
- /**
- * Reason code if suggested network connection attempt failed with an unknown failure.
- */
- public static final int STATUS_SUGGESTION_CONNECTION_FAILURE_UNKNOWN = 0;
- /**
- * Reason code if suggested network connection attempt failed with association failure.
- */
- public static final int STATUS_SUGGESTION_CONNECTION_FAILURE_ASSOCIATION = 1;
- /**
- * Reason code if suggested network connection attempt failed with an authentication failure.
- */
- public static final int STATUS_SUGGESTION_CONNECTION_FAILURE_AUTHENTICATION = 2;
- /**
- * Reason code if suggested network connection attempt failed with an IP provision failure.
- */
- public static final int STATUS_SUGGESTION_CONNECTION_FAILURE_IP_PROVISIONING = 3;
-
- /** @hide */
- @IntDef(prefix = {"STATUS_SUGGESTION_CONNECTION_FAILURE_"},
- value = {STATUS_SUGGESTION_CONNECTION_FAILURE_UNKNOWN,
- STATUS_SUGGESTION_CONNECTION_FAILURE_ASSOCIATION,
- STATUS_SUGGESTION_CONNECTION_FAILURE_AUTHENTICATION,
- STATUS_SUGGESTION_CONNECTION_FAILURE_IP_PROVISIONING
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SuggestionConnectionStatusCode {}
-
- /**
- * Status code if suggestion approval status is unknown, an App which hasn't made any
- * suggestions will get this code.
- */
- public static final int STATUS_SUGGESTION_APPROVAL_UNKNOWN = 0;
-
- /**
- * Status code if the calling app is still pending user approval for suggestions.
- */
- public static final int STATUS_SUGGESTION_APPROVAL_PENDING = 1;
-
- /**
- * Status code if the calling app got the user approval for suggestions.
- */
- public static final int STATUS_SUGGESTION_APPROVAL_APPROVED_BY_USER = 2;
-
- /**
- * Status code if the calling app suggestions were rejected by the user.
- */
- public static final int STATUS_SUGGESTION_APPROVAL_REJECTED_BY_USER = 3;
-
- /**
- * Status code if the calling app was approved by virtue of being a carrier privileged app.
- * @see TelephonyManager#hasCarrierPrivileges().
- */
- public static final int STATUS_SUGGESTION_APPROVAL_APPROVED_BY_CARRIER_PRIVILEGE = 4;
-
- /** @hide */
- @IntDef(prefix = {"STATUS_SUGGESTION_APPROVAL_"},
- value = {STATUS_SUGGESTION_APPROVAL_UNKNOWN,
- STATUS_SUGGESTION_APPROVAL_PENDING,
- STATUS_SUGGESTION_APPROVAL_APPROVED_BY_USER,
- STATUS_SUGGESTION_APPROVAL_REJECTED_BY_USER,
- STATUS_SUGGESTION_APPROVAL_APPROVED_BY_CARRIER_PRIVILEGE
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SuggestionUserApprovalStatus {}
-
- /**
- * Broadcast intent action indicating whether Wi-Fi scanning is currently available.
- * Available extras:
- * - {@link #EXTRA_SCAN_AVAILABLE}
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String ACTION_WIFI_SCAN_AVAILABILITY_CHANGED =
- "android.net.wifi.action.WIFI_SCAN_AVAILABILITY_CHANGED";
-
- /**
- * A boolean extra indicating whether scanning is currently available.
- * Sent in the broadcast {@link #ACTION_WIFI_SCAN_AVAILABILITY_CHANGED}.
- * Its value is true if scanning is currently available, false otherwise.
- */
- public static final String EXTRA_SCAN_AVAILABLE = "android.net.wifi.extra.SCAN_AVAILABLE";
-
- /**
- * Broadcast intent action indicating that the credential of a Wi-Fi network
- * has been changed. One extra provides the ssid of the network. Another
- * extra provides the event type, whether the credential is saved or forgot.
- * @hide
- */
- @SystemApi
- public static final String WIFI_CREDENTIAL_CHANGED_ACTION =
- "android.net.wifi.WIFI_CREDENTIAL_CHANGED";
- /** @hide */
- @SystemApi
- public static final String EXTRA_WIFI_CREDENTIAL_EVENT_TYPE = "et";
- /** @hide */
- @SystemApi
- public static final String EXTRA_WIFI_CREDENTIAL_SSID = "ssid";
- /** @hide */
- @SystemApi
- public static final int WIFI_CREDENTIAL_SAVED = 0;
- /** @hide */
- @SystemApi
- public static final int WIFI_CREDENTIAL_FORGOT = 1;
-
- /** @hide */
- @SystemApi
- public static final int PASSPOINT_HOME_NETWORK = 0;
-
- /** @hide */
- @SystemApi
- public static final int PASSPOINT_ROAMING_NETWORK = 1;
-
- /**
- * Broadcast intent action indicating that a Passpoint provider icon has been received.
- *
- * Included extras:
- * {@link #EXTRA_BSSID_LONG}
- * {@link #EXTRA_FILENAME}
- * {@link #EXTRA_ICON}
- *
- * Receiver Required Permission: android.Manifest.permission.ACCESS_WIFI_STATE
- *
- * Note: The broadcast is only delivered to registered receivers - no manifest registered
- * components will be launched.
- *
- * @hide
- */
- public static final String ACTION_PASSPOINT_ICON = "android.net.wifi.action.PASSPOINT_ICON";
- /**
- * BSSID of an AP in long representation. The {@link #EXTRA_BSSID} contains BSSID in
- * String representation.
- *
- * Retrieve with {@link android.content.Intent#getLongExtra(String, long)}.
- *
- * @hide
- */
- public static final String EXTRA_BSSID_LONG = "android.net.wifi.extra.BSSID_LONG";
- /**
- * Icon data.
- *
- * Retrieve with {@link android.content.Intent#getParcelableExtra(String)} and cast into
- * {@link android.graphics.drawable.Icon}.
- *
- * @hide
- */
- public static final String EXTRA_ICON = "android.net.wifi.extra.ICON";
- /**
- * Name of a file.
- *
- * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
- *
- * @hide
- */
- public static final String EXTRA_FILENAME = "android.net.wifi.extra.FILENAME";
-
- /**
- * Broadcast intent action indicating a Passpoint OSU Providers List element has been received.
- *
- * Included extras:
- * {@link #EXTRA_BSSID_LONG}
- * {@link #EXTRA_ANQP_ELEMENT_DATA}
- *
- * Receiver Required Permission: android.Manifest.permission.ACCESS_WIFI_STATE
- *
- *
Note: The broadcast is only delivered to registered receivers - no manifest registered
- * components will be launched.
- *
- * @hide
- */
- public static final String ACTION_PASSPOINT_OSU_PROVIDERS_LIST =
- "android.net.wifi.action.PASSPOINT_OSU_PROVIDERS_LIST";
- /**
- * Raw binary data of an ANQP (Access Network Query Protocol) element.
- *
- * Retrieve with {@link android.content.Intent#getByteArrayExtra(String)}.
- *
- * @hide
- */
- public static final String EXTRA_ANQP_ELEMENT_DATA =
- "android.net.wifi.extra.ANQP_ELEMENT_DATA";
-
- /**
- * Broadcast intent action indicating that a Passpoint Deauth Imminent frame has been received.
- *
- * Included extras:
- * {@link #EXTRA_BSSID_LONG}
- * {@link #EXTRA_ESS}
- * {@link #EXTRA_DELAY}
- * {@link #EXTRA_URL}
- *
- * Receiver Required Permission: android.Manifest.permission.ACCESS_WIFI_STATE
- *
- *
Note: The broadcast is only delivered to registered receivers - no manifest registered
- * components will be launched.
- *
- * @hide
- */
- public static final String ACTION_PASSPOINT_DEAUTH_IMMINENT =
- "android.net.wifi.action.PASSPOINT_DEAUTH_IMMINENT";
- /**
- * Flag indicating BSS (Basic Service Set) or ESS (Extended Service Set). This will be set to
- * {@code true} for ESS.
- *
- * Retrieve with {@link android.content.Intent#getBooleanExtra(String, boolean)}.
- *
- * @hide
- */
- public static final String EXTRA_ESS = "android.net.wifi.extra.ESS";
- /**
- * Delay in seconds.
- *
- * Retrieve with {@link android.content.Intent#getIntExtra(String, int)}.
- *
- * @hide
- */
- public static final String EXTRA_DELAY = "android.net.wifi.extra.DELAY";
-
- /**
- * Broadcast intent action indicating a Passpoint subscription remediation frame has been
- * received.
- *
- * Included extras:
- * {@link #EXTRA_BSSID_LONG}
- * {@link #EXTRA_SUBSCRIPTION_REMEDIATION_METHOD}
- * {@link #EXTRA_URL}
- *
- * Receiver Required Permission: android.Manifest.permission.ACCESS_WIFI_STATE
- *
- *
Note: The broadcast is only delivered to registered receivers - no manifest registered
- * components will be launched.
- *
- * @hide
- */
- public static final String ACTION_PASSPOINT_SUBSCRIPTION_REMEDIATION =
- "android.net.wifi.action.PASSPOINT_SUBSCRIPTION_REMEDIATION";
- /**
- * The protocol supported by the subscription remediation server. The possible values are:
- * 0 - OMA DM
- * 1 - SOAP XML SPP
- *
- * Retrieve with {@link android.content.Intent#getIntExtra(String, int)}.
- *
- * @hide
- */
- public static final String EXTRA_SUBSCRIPTION_REMEDIATION_METHOD =
- "android.net.wifi.extra.SUBSCRIPTION_REMEDIATION_METHOD";
-
- /**
- * Activity Action: Receiver should launch Passpoint OSU (Online Sign Up) view.
- * Included extras:
- *
- * {@link #EXTRA_OSU_NETWORK}: {@link Network} instance associated with OSU AP.
- * {@link #EXTRA_URL}: String representation of a server URL used for OSU process.
- *
- * @hide
- */
- @SystemApi
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_PASSPOINT_LAUNCH_OSU_VIEW =
- "android.net.wifi.action.PASSPOINT_LAUNCH_OSU_VIEW";
-
- /**
- * The lookup key for a {@link android.net.Network} associated with a Passpoint OSU server.
- * Included in the {@link #ACTION_PASSPOINT_LAUNCH_OSU_VIEW} broadcast.
- *
- * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_OSU_NETWORK = "android.net.wifi.extra.OSU_NETWORK";
-
- /**
- * String representation of an URL for Passpoint OSU.
- * Included in the {@link #ACTION_PASSPOINT_LAUNCH_OSU_VIEW} broadcast.
- *
- * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_URL = "android.net.wifi.extra.URL";
-
- /**
- * Broadcast intent action indicating that Wi-Fi has been enabled, disabled,
- * enabling, disabling, or unknown. One extra provides this state as an int.
- * Another extra provides the previous state, if available. No network-related
- * permissions are required to subscribe to this broadcast.
- *
- *
This broadcast is not delivered to manifest receivers in
- * applications that target API version 26 or later.
- *
- * @see #EXTRA_WIFI_STATE
- * @see #EXTRA_PREVIOUS_WIFI_STATE
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String WIFI_STATE_CHANGED_ACTION =
- "android.net.wifi.WIFI_STATE_CHANGED";
- /**
- * The lookup key for an int that indicates whether Wi-Fi is enabled,
- * disabled, enabling, disabling, or unknown. Retrieve it with
- * {@link android.content.Intent#getIntExtra(String,int)}.
- *
- * @see #WIFI_STATE_DISABLED
- * @see #WIFI_STATE_DISABLING
- * @see #WIFI_STATE_ENABLED
- * @see #WIFI_STATE_ENABLING
- * @see #WIFI_STATE_UNKNOWN
- */
- public static final String EXTRA_WIFI_STATE = "wifi_state";
- /**
- * The previous Wi-Fi state.
- *
- * @see #EXTRA_WIFI_STATE
- */
- public static final String EXTRA_PREVIOUS_WIFI_STATE = "previous_wifi_state";
-
- /**
- * Wi-Fi is currently being disabled. The state will change to {@link #WIFI_STATE_DISABLED} if
- * it finishes successfully.
- *
- * @see #WIFI_STATE_CHANGED_ACTION
- * @see #getWifiState()
- */
- public static final int WIFI_STATE_DISABLING = 0;
- /**
- * Wi-Fi is disabled.
- *
- * @see #WIFI_STATE_CHANGED_ACTION
- * @see #getWifiState()
- */
- public static final int WIFI_STATE_DISABLED = 1;
- /**
- * Wi-Fi is currently being enabled. The state will change to {@link #WIFI_STATE_ENABLED} if
- * it finishes successfully.
- *
- * @see #WIFI_STATE_CHANGED_ACTION
- * @see #getWifiState()
- */
- public static final int WIFI_STATE_ENABLING = 2;
- /**
- * Wi-Fi is enabled.
- *
- * @see #WIFI_STATE_CHANGED_ACTION
- * @see #getWifiState()
- */
- public static final int WIFI_STATE_ENABLED = 3;
- /**
- * Wi-Fi is in an unknown state. This state will occur when an error happens while enabling
- * or disabling.
- *
- * @see #WIFI_STATE_CHANGED_ACTION
- * @see #getWifiState()
- */
- public static final int WIFI_STATE_UNKNOWN = 4;
-
- /**
- * Broadcast intent action indicating that Wi-Fi AP has been enabled, disabled,
- * enabling, disabling, or failed.
- *
- * @hide
- */
- @SystemApi
- public static final String WIFI_AP_STATE_CHANGED_ACTION =
- "android.net.wifi.WIFI_AP_STATE_CHANGED";
-
- /**
- * The lookup key for an int that indicates whether Wi-Fi AP is enabled,
- * disabled, enabling, disabling, or failed. Retrieve it with
- * {@link android.content.Intent#getIntExtra(String,int)}.
- *
- * @see #WIFI_AP_STATE_DISABLED
- * @see #WIFI_AP_STATE_DISABLING
- * @see #WIFI_AP_STATE_ENABLED
- * @see #WIFI_AP_STATE_ENABLING
- * @see #WIFI_AP_STATE_FAILED
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_WIFI_AP_STATE = "wifi_state";
-
- /**
- * An extra containing the int error code for Soft AP start failure.
- * Can be obtained from the {@link #WIFI_AP_STATE_CHANGED_ACTION} using
- * {@link android.content.Intent#getIntExtra}.
- * This extra will only be attached if {@link #EXTRA_WIFI_AP_STATE} is
- * attached and is equal to {@link #WIFI_AP_STATE_FAILED}.
- *
- * The error code will be one of:
- * {@link #SAP_START_FAILURE_GENERAL},
- * {@link #SAP_START_FAILURE_NO_CHANNEL},
- * {@link #SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_WIFI_AP_FAILURE_REASON =
- "android.net.wifi.extra.WIFI_AP_FAILURE_REASON";
- /**
- * The previous Wi-Fi state.
- *
- * @see #EXTRA_WIFI_AP_STATE
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_PREVIOUS_WIFI_AP_STATE = "previous_wifi_state";
- /**
- * The lookup key for a String extra that stores the interface name used for the Soft AP.
- * This extra is included in the broadcast {@link #WIFI_AP_STATE_CHANGED_ACTION}.
- * Retrieve its value with {@link android.content.Intent#getStringExtra(String)}.
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_WIFI_AP_INTERFACE_NAME =
- "android.net.wifi.extra.WIFI_AP_INTERFACE_NAME";
- /**
- * The lookup key for an int extra that stores the intended IP mode for this Soft AP.
- * One of {@link #IFACE_IP_MODE_TETHERED} or {@link #IFACE_IP_MODE_LOCAL_ONLY}.
- * This extra is included in the broadcast {@link #WIFI_AP_STATE_CHANGED_ACTION}.
- * Retrieve its value with {@link android.content.Intent#getIntExtra(String, int)}.
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_WIFI_AP_MODE = "android.net.wifi.extra.WIFI_AP_MODE";
-
- /** @hide */
- @IntDef(flag = false, prefix = { "WIFI_AP_STATE_" }, value = {
- WIFI_AP_STATE_DISABLING,
- WIFI_AP_STATE_DISABLED,
- WIFI_AP_STATE_ENABLING,
- WIFI_AP_STATE_ENABLED,
- WIFI_AP_STATE_FAILED,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface WifiApState {}
-
- /**
- * Wi-Fi AP is currently being disabled. The state will change to
- * {@link #WIFI_AP_STATE_DISABLED} if it finishes successfully.
- *
- * @see #WIFI_AP_STATE_CHANGED_ACTION
- * @see #getWifiApState()
- *
- * @hide
- */
- @SystemApi
- public static final int WIFI_AP_STATE_DISABLING = 10;
- /**
- * Wi-Fi AP is disabled.
- *
- * @see #WIFI_AP_STATE_CHANGED_ACTION
- * @see #getWifiState()
- *
- * @hide
- */
- @SystemApi
- public static final int WIFI_AP_STATE_DISABLED = 11;
- /**
- * Wi-Fi AP is currently being enabled. The state will change to
- * {@link #WIFI_AP_STATE_ENABLED} if it finishes successfully.
- *
- * @see #WIFI_AP_STATE_CHANGED_ACTION
- * @see #getWifiApState()
- *
- * @hide
- */
- @SystemApi
- public static final int WIFI_AP_STATE_ENABLING = 12;
- /**
- * Wi-Fi AP is enabled.
- *
- * @see #WIFI_AP_STATE_CHANGED_ACTION
- * @see #getWifiApState()
- *
- * @hide
- */
- @SystemApi
- public static final int WIFI_AP_STATE_ENABLED = 13;
- /**
- * Wi-Fi AP is in a failed state. This state will occur when an error occurs during
- * enabling or disabling
- *
- * @see #WIFI_AP_STATE_CHANGED_ACTION
- * @see #getWifiApState()
- *
- * @hide
- */
- @SystemApi
- public static final int WIFI_AP_STATE_FAILED = 14;
-
- /** @hide */
- @IntDef(flag = false, prefix = { "SAP_START_FAILURE_" }, value = {
- SAP_START_FAILURE_GENERAL,
- SAP_START_FAILURE_NO_CHANNEL,
- SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SapStartFailure {}
-
- /**
- * All other reasons for AP start failure besides {@link #SAP_START_FAILURE_NO_CHANNEL} and
- * {@link #SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}.
- *
- * @hide
- */
- @SystemApi
- public static final int SAP_START_FAILURE_GENERAL= 0;
-
- /**
- * If Wi-Fi AP start failed, this reason code means that no legal channel exists on user
- * selected band due to regulatory constraints.
- *
- * @hide
- */
- @SystemApi
- public static final int SAP_START_FAILURE_NO_CHANNEL = 1;
-
- /**
- * If Wi-Fi AP start failed, this reason code means that the specified configuration
- * is not supported by the current HAL version.
- *
- * @hide
- */
- @SystemApi
- public static final int SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION = 2;
-
-
- /** @hide */
- @IntDef(flag = false, prefix = { "SAP_CLIENT_BLOCKED_REASON_" }, value = {
- SAP_CLIENT_BLOCK_REASON_CODE_BLOCKED_BY_USER,
- SAP_CLIENT_BLOCK_REASON_CODE_NO_MORE_STAS,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SapClientBlockedReason {}
-
- /**
- * If Soft Ap client is blocked, this reason code means that client doesn't exist in the
- * specified configuration {@link SoftApConfiguration.Builder#setBlockedClientList(List)}
- * and {@link SoftApConfiguration.Builder#setAllowedClientList(List)}
- * and the {@link SoftApConfiguration.Builder#setClientControlByUserEnabled(boolean)}
- * is configured as well.
- * @hide
- */
- @SystemApi
- public static final int SAP_CLIENT_BLOCK_REASON_CODE_BLOCKED_BY_USER = 0;
-
- /**
- * If Soft Ap client is blocked, this reason code means that no more clients can be
- * associated to this AP since it reached maximum capacity. The maximum capacity is
- * the minimum of {@link SoftApConfiguration.Builder#setMaxNumberOfClients(int)} and
- * {@link SoftApCapability#getMaxSupportedClients} which get from
- * {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)}.
- *
- * @hide
- */
- @SystemApi
- public static final int SAP_CLIENT_BLOCK_REASON_CODE_NO_MORE_STAS = 1;
-
- /**
- * Client disconnected for unspecified reason. This could for example be because the AP is being
- * shut down.
- * @hide
- */
- public static final int SAP_CLIENT_DISCONNECT_REASON_CODE_UNSPECIFIED = 2;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"IFACE_IP_MODE_"}, value = {
- IFACE_IP_MODE_UNSPECIFIED,
- IFACE_IP_MODE_CONFIGURATION_ERROR,
- IFACE_IP_MODE_TETHERED,
- IFACE_IP_MODE_LOCAL_ONLY})
- public @interface IfaceIpMode {}
-
- /**
- * Interface IP mode unspecified.
- *
- * @see #updateInterfaceIpState(String, int)
- *
- * @hide
- */
- @SystemApi
- public static final int IFACE_IP_MODE_UNSPECIFIED = -1;
-
- /**
- * Interface IP mode for configuration error.
- *
- * @see #updateInterfaceIpState(String, int)
- *
- * @hide
- */
- @SystemApi
- public static final int IFACE_IP_MODE_CONFIGURATION_ERROR = 0;
-
- /**
- * Interface IP mode for tethering.
- *
- * @see #updateInterfaceIpState(String, int)
- *
- * @hide
- */
- @SystemApi
- public static final int IFACE_IP_MODE_TETHERED = 1;
-
- /**
- * Interface IP mode for Local Only Hotspot.
- *
- * @see #updateInterfaceIpState(String, int)
- *
- * @hide
- */
- @SystemApi
- public static final int IFACE_IP_MODE_LOCAL_ONLY = 2;
-
- /**
- * Broadcast intent action indicating that the wifi network settings
- * had been reset.
- *
- * Note: This intent is sent as a directed broadcast to each manifest registered receiver.
- * Intent will not be received by dynamically registered receivers.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_CARRIER_PROVISIONING)
- public static final String ACTION_NETWORK_SETTINGS_RESET =
- "android.net.wifi.action.NETWORK_SETTINGS_RESET";
-
- /**
- * Broadcast intent action indicating that a connection to the supplicant has
- * been established (and it is now possible
- * to perform Wi-Fi operations) or the connection to the supplicant has been
- * lost. One extra provides the connection state as a boolean, where {@code true}
- * means CONNECTED.
- * @deprecated This is no longer supported.
- * @see #EXTRA_SUPPLICANT_CONNECTED
- */
- @Deprecated
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String SUPPLICANT_CONNECTION_CHANGE_ACTION =
- "android.net.wifi.supplicant.CONNECTION_CHANGE";
- /**
- * The lookup key for a boolean that indicates whether a connection to
- * the supplicant daemon has been gained or lost. {@code true} means
- * a connection now exists.
- * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
- * @deprecated This is no longer supported.
- */
- @Deprecated
- public static final String EXTRA_SUPPLICANT_CONNECTED = "connected";
- /**
- * Broadcast intent action indicating that the state of Wi-Fi connectivity
- * has changed. An extra provides the new state
- * in the form of a {@link android.net.NetworkInfo} object. No network-related
- * permissions are required to subscribe to this broadcast.
- *
- *
This broadcast is not delivered to manifest receivers in
- * applications that target API version 26 or later.
- * @see #EXTRA_NETWORK_INFO
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String NETWORK_STATE_CHANGED_ACTION = "android.net.wifi.STATE_CHANGE";
- /**
- * The lookup key for a {@link android.net.NetworkInfo} object associated with the
- * Wi-Fi network. Retrieve with
- * {@link android.content.Intent#getParcelableExtra(String)}.
- */
- public static final String EXTRA_NETWORK_INFO = "networkInfo";
- /**
- * The lookup key for a String giving the BSSID of the access point to which
- * we are connected. No longer used.
- */
- @Deprecated
- public static final String EXTRA_BSSID = "bssid";
- /**
- * The lookup key for a {@link android.net.wifi.WifiInfo} object giving the
- * information about the access point to which we are connected.
- * No longer used.
- */
- @Deprecated
- public static final String EXTRA_WIFI_INFO = "wifiInfo";
- /**
- * Broadcast intent action indicating that the state of establishing a connection to
- * an access point has changed.One extra provides the new
- * {@link SupplicantState}. Note that the supplicant state is Wi-Fi specific, and
- * is not generally the most useful thing to look at if you are just interested in
- * the overall state of connectivity.
- * @see #EXTRA_NEW_STATE
- * @see #EXTRA_SUPPLICANT_ERROR
- * @deprecated This is no longer supported.
- */
- @Deprecated
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String SUPPLICANT_STATE_CHANGED_ACTION =
- "android.net.wifi.supplicant.STATE_CHANGE";
- /**
- * The lookup key for a {@link SupplicantState} describing the new state
- * Retrieve with
- * {@link android.content.Intent#getParcelableExtra(String)}.
- * @deprecated This is no longer supported.
- */
- @Deprecated
- public static final String EXTRA_NEW_STATE = "newState";
-
- /**
- * The lookup key for a {@link SupplicantState} describing the supplicant
- * error code if any
- * Retrieve with
- * {@link android.content.Intent#getIntExtra(String, int)}.
- * @see #ERROR_AUTHENTICATING
- * @deprecated This is no longer supported.
- */
- @Deprecated
- public static final String EXTRA_SUPPLICANT_ERROR = "supplicantError";
-
- /**
- * The lookup key for a {@link SupplicantState} describing the supplicant
- * error reason if any
- * Retrieve with
- * {@link android.content.Intent#getIntExtra(String, int)}.
- * @see #ERROR_AUTH_FAILURE_#REASON_CODE
- * @deprecated This is no longer supported.
- * @hide
- */
- @Deprecated
- public static final String EXTRA_SUPPLICANT_ERROR_REASON = "supplicantErrorReason";
-
- /**
- * Broadcast intent action indicating that the configured networks changed.
- * This can be as a result of adding/updating/deleting a network.
- *
- * {@link #EXTRA_CHANGE_REASON} contains whether the configuration was added/changed/removed.
- * {@link #EXTRA_WIFI_CONFIGURATION} is never set beginning in
- * {@link android.os.Build.VERSION_CODES#R}.
- * {@link #EXTRA_MULTIPLE_NETWORKS_CHANGED} is set for backwards compatibility reasons, but
- * its value is always true beginning in {@link android.os.Build.VERSION_CODES#R}, even if only
- * a single network changed.
- *
- * The {@link android.Manifest.permission#ACCESS_WIFI_STATE ACCESS_WIFI_STATE} permission is
- * required to receive this broadcast.
- *
- * @hide
- */
- @SystemApi
- public static final String CONFIGURED_NETWORKS_CHANGED_ACTION =
- "android.net.wifi.CONFIGURED_NETWORKS_CHANGE";
- /**
- * The lookup key for a {@link android.net.wifi.WifiConfiguration} object representing
- * the changed Wi-Fi configuration when the {@link #CONFIGURED_NETWORKS_CHANGED_ACTION}
- * broadcast is sent.
- * @deprecated This extra is never set beginning in {@link android.os.Build.VERSION_CODES#R},
- * regardless of the target SDK version. Use {@link #getConfiguredNetworks} to get the full list
- * of configured networks.
- * @hide
- */
- @Deprecated
- @SystemApi
- public static final String EXTRA_WIFI_CONFIGURATION = "wifiConfiguration";
- /**
- * Multiple network configurations have changed.
- * @see #CONFIGURED_NETWORKS_CHANGED_ACTION
- * @deprecated This extra's value is always true beginning in
- * {@link android.os.Build.VERSION_CODES#R}, regardless of the target SDK version.
- * @hide
- */
- @Deprecated
- @SystemApi
- public static final String EXTRA_MULTIPLE_NETWORKS_CHANGED = "multipleChanges";
- /**
- * The lookup key for an integer indicating the reason a Wi-Fi network configuration
- * has changed. One of {@link #CHANGE_REASON_ADDED}, {@link #CHANGE_REASON_REMOVED},
- * {@link #CHANGE_REASON_CONFIG_CHANGE}.
- *
- * @see #CONFIGURED_NETWORKS_CHANGED_ACTION
- * @hide
- */
- @SystemApi
- public static final String EXTRA_CHANGE_REASON = "changeReason";
- /**
- * The configuration is new and was added.
- * @hide
- */
- @SystemApi
- public static final int CHANGE_REASON_ADDED = 0;
- /**
- * The configuration was removed and is no longer present in the system's list of
- * configured networks.
- * @hide
- */
- @SystemApi
- public static final int CHANGE_REASON_REMOVED = 1;
- /**
- * The configuration has changed as a result of explicit action or because the system
- * took an automated action such as disabling a malfunctioning configuration.
- * @hide
- */
- @SystemApi
- public static final int CHANGE_REASON_CONFIG_CHANGE = 2;
- /**
- * An access point scan has completed, and results are available.
- * Call {@link #getScanResults()} to obtain the results.
- * The broadcast intent may contain an extra field with the key {@link #EXTRA_RESULTS_UPDATED}
- * and a {@code boolean} value indicating if the scan was successful.
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String SCAN_RESULTS_AVAILABLE_ACTION = "android.net.wifi.SCAN_RESULTS";
-
- /**
- * Lookup key for a {@code boolean} extra in intent {@link #SCAN_RESULTS_AVAILABLE_ACTION}
- * representing if the scan was successful or not.
- * Scans may fail for multiple reasons, these may include:
- *
- * - An app requested too many scans in a certain period of time.
- * This may lead to additional scan request rejections via "scan throttling" for both
- * foreground and background apps.
- * Note: Apps holding android.Manifest.permission.NETWORK_SETTINGS permission are
- * exempted from scan throttling.
- *
- * - The device is idle and scanning is disabled.
- * - Wifi hardware reported a scan failure.
- *
- * @return true scan was successful, results are updated
- * @return false scan was not successful, results haven't been updated since previous scan
- */
- public static final String EXTRA_RESULTS_UPDATED = "resultsUpdated";
-
- /**
- * A batch of access point scans has been completed and the results areavailable.
- * Call {@link #getBatchedScanResults()} to obtain the results.
- * @deprecated This API is nolonger supported.
- * Use {@link android.net.wifi.WifiScanner} API
- * @hide
- */
- @Deprecated
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String BATCHED_SCAN_RESULTS_AVAILABLE_ACTION =
- "android.net.wifi.BATCHED_RESULTS";
-
- /**
- * The RSSI (signal strength) has changed.
- *
- * Receiver Required Permission: android.Manifest.permission.ACCESS_WIFI_STATE
- * @see #EXTRA_NEW_RSSI
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String RSSI_CHANGED_ACTION = "android.net.wifi.RSSI_CHANGED";
- /**
- * The lookup key for an {@code int} giving the new RSSI in dBm.
- */
- public static final String EXTRA_NEW_RSSI = "newRssi";
-
- /**
- * @see #ACTION_LINK_CONFIGURATION_CHANGED
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final String LINK_CONFIGURATION_CHANGED_ACTION =
- "android.net.wifi.LINK_CONFIGURATION_CHANGED";
-
- /**
- * Broadcast intent action indicating that the link configuration changed on wifi.
- *
No permissions are required to listen to this broadcast.
- * @hide
- */
- @SystemApi
- public static final String ACTION_LINK_CONFIGURATION_CHANGED =
- // should be android.net.wifi.action.LINK_CONFIGURATION_CHANGED, but due to
- // @UnsupportedAppUsage leaving it as android.net.wifi.LINK_CONFIGURATION_CHANGED.
- LINK_CONFIGURATION_CHANGED_ACTION;
-
- /**
- * The lookup key for a {@link android.net.LinkProperties} object associated with the
- * Wi-Fi network.
- * Included in the {@link #ACTION_LINK_CONFIGURATION_CHANGED} broadcast.
- *
- * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
- *
- * @deprecated this extra is no longer populated.
- *
- * @hide
- */
- @Deprecated
- @SystemApi
- public static final String EXTRA_LINK_PROPERTIES = "android.net.wifi.extra.LINK_PROPERTIES";
-
- /**
- * The lookup key for a {@link android.net.NetworkCapabilities} object associated with the
- * Wi-Fi network. Retrieve with
- * {@link android.content.Intent#getParcelableExtra(String)}.
- * @hide
- */
- public static final String EXTRA_NETWORK_CAPABILITIES = "networkCapabilities";
-
- /**
- * The network IDs of the configured networks could have changed.
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String NETWORK_IDS_CHANGED_ACTION = "android.net.wifi.NETWORK_IDS_CHANGED";
-
- /**
- * Activity Action: Show a system activity that allows the user to enable
- * scans to be available even with Wi-Fi turned off.
- *
- * Notification of the result of this activity is posted using the
- * {@link android.app.Activity#onActivityResult} callback. The
- * resultCode
- * will be {@link android.app.Activity#RESULT_OK} if scan always mode has
- * been turned on or {@link android.app.Activity#RESULT_CANCELED} if the user
- * has rejected the request or an error has occurred.
- */
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE =
- "android.net.wifi.action.REQUEST_SCAN_ALWAYS_AVAILABLE";
-
- /**
- * Activity Action: Pick a Wi-Fi network to connect to.
- *
Input: Nothing.
- *
Output: Nothing.
- */
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_PICK_WIFI_NETWORK = "android.net.wifi.PICK_WIFI_NETWORK";
-
- /**
- * Activity Action: Receiver should show UI to get user approval to enable WiFi.
- *
Input: {@link android.content.Intent#EXTRA_PACKAGE_NAME} string extra with
- * the name of the app requesting the action.
- *
Output: Nothing.
- *
No permissions are required to send this action.
- * @hide
- */
- @SystemApi
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_REQUEST_ENABLE = "android.net.wifi.action.REQUEST_ENABLE";
-
- /**
- * Activity Action: Receiver should show UI to get user approval to disable WiFi.
- *
Input: {@link android.content.Intent#EXTRA_PACKAGE_NAME} string extra with
- * the name of the app requesting the action.
- *
Output: Nothing.
- *
No permissions are required to send this action.
- * @hide
- */
- @SystemApi
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_REQUEST_DISABLE = "android.net.wifi.action.REQUEST_DISABLE";
-
- /**
- * Directed broadcast intent action indicating that the device has connected to one of the
- * network suggestions provided by the app. This will be sent post connection to a network
- * which was created with {@link WifiNetworkSuggestion.Builder#setIsAppInteractionRequired(
- * boolean)}
- * flag set.
- *
- * Note: The broadcast is sent to the app only if it holds
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission.
- *
- * @see #EXTRA_NETWORK_SUGGESTION
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION =
- "android.net.wifi.action.WIFI_NETWORK_SUGGESTION_POST_CONNECTION";
- /**
- * Sent as as a part of {@link #ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION} that holds
- * an instance of {@link WifiNetworkSuggestion} corresponding to the connected network.
- */
- public static final String EXTRA_NETWORK_SUGGESTION =
- "android.net.wifi.extra.NETWORK_SUGGESTION";
-
- /**
- * Internally used Wi-Fi lock mode representing the case were no locks are held.
- * @hide
- */
- public static final int WIFI_MODE_NO_LOCKS_HELD = 0;
-
- /**
- * In this Wi-Fi lock mode, Wi-Fi will be kept active,
- * and will behave normally, i.e., it will attempt to automatically
- * establish a connection to a remembered access point that is
- * within range, and will do periodic scans if there are remembered
- * access points but none are in range.
- *
- * @deprecated This API is non-functional and will have no impact.
- */
- @Deprecated
- public static final int WIFI_MODE_FULL = 1;
-
- /**
- * In this Wi-Fi lock mode, Wi-Fi will be kept active,
- * but the only operation that will be supported is initiation of
- * scans, and the subsequent reporting of scan results. No attempts
- * will be made to automatically connect to remembered access points,
- * nor will periodic scans be automatically performed looking for
- * remembered access points. Scans must be explicitly requested by
- * an application in this mode.
- *
- * @deprecated This API is non-functional and will have no impact.
- */
- @Deprecated
- public static final int WIFI_MODE_SCAN_ONLY = 2;
-
- /**
- * In this Wi-Fi lock mode, Wi-Fi will not go to power save.
- * This results in operating with low packet latency.
- * The lock is only active when the device is connected to an access point.
- * The lock is active even when the device screen is off or the acquiring application is
- * running in the background.
- * This mode will consume more power and hence should be used only
- * when there is a need for this tradeoff.
- *
- * An example use case is when a voice connection needs to be
- * kept active even after the device screen goes off.
- * Holding a {@link #WIFI_MODE_FULL_HIGH_PERF} lock for the
- * duration of the voice call may improve the call quality.
- *
- * When there is no support from the hardware, the {@link #WIFI_MODE_FULL_HIGH_PERF}
- * lock will have no impact.
- */
- public static final int WIFI_MODE_FULL_HIGH_PERF = 3;
-
- /**
- * In this Wi-Fi lock mode, Wi-Fi will operate with a priority to achieve low latency.
- * {@link #WIFI_MODE_FULL_LOW_LATENCY} lock has the following limitations:
- *
- * - The lock is only active when the device is connected to an access point.
- * - The lock is only active when the screen is on.
- * - The lock is only active when the acquiring app is running in the foreground.
- *
- * Low latency mode optimizes for reduced packet latency,
- * and as a result other performance measures may suffer when there are trade-offs to make:
- *
- * - Battery life may be reduced.
- * - Throughput may be reduced.
- * - Frequency of Wi-Fi scanning may be reduced. This may result in:
- *
- * - The device may not roam or switch to the AP with highest signal quality.
- * - Location accuracy may be reduced.
- *
- *
- *
- * Example use cases are real time gaming or virtual reality applications where
- * low latency is a key factor for user experience.
- *
- * Note: For an app which acquires both {@link #WIFI_MODE_FULL_LOW_LATENCY} and
- * {@link #WIFI_MODE_FULL_HIGH_PERF} locks, {@link #WIFI_MODE_FULL_LOW_LATENCY}
- * lock will be effective when app is running in foreground and screen is on,
- * while the {@link #WIFI_MODE_FULL_HIGH_PERF} lock will take effect otherwise.
- */
- public static final int WIFI_MODE_FULL_LOW_LATENCY = 4;
-
-
- /** Anything worse than or equal to this will show 0 bars. */
- @UnsupportedAppUsage
- private static final int MIN_RSSI = -100;
-
- /** Anything better than or equal to this will show the max bars. */
- @UnsupportedAppUsage
- private static final int MAX_RSSI = -55;
-
- /**
- * Number of RSSI levels used in the framework to initiate {@link #RSSI_CHANGED_ACTION}
- * broadcast, where each level corresponds to a range of RSSI values.
- * The {@link #RSSI_CHANGED_ACTION} broadcast will only fire if the RSSI
- * change is significant enough to change the RSSI signal level.
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int RSSI_LEVELS = 5;
-
- //TODO (b/146346676): This needs to be removed, not used in the code.
- /**
- * Auto settings in the driver. The driver could choose to operate on both
- * 2.4 GHz and 5 GHz or make a dynamic decision on selecting the band.
- * @hide
- */
- @UnsupportedAppUsage
- public static final int WIFI_FREQUENCY_BAND_AUTO = 0;
-
- /**
- * Operation on 5 GHz alone
- * @hide
- */
- @UnsupportedAppUsage
- public static final int WIFI_FREQUENCY_BAND_5GHZ = 1;
-
- /**
- * Operation on 2.4 GHz alone
- * @hide
- */
- @UnsupportedAppUsage
- public static final int WIFI_FREQUENCY_BAND_2GHZ = 2;
-
- /** @hide */
- public static final boolean DEFAULT_POOR_NETWORK_AVOIDANCE_ENABLED = false;
-
- /**
- * Maximum number of active locks we allow.
- * This limit was added to prevent apps from creating a ridiculous number
- * of locks and crashing the system by overflowing the global ref table.
- */
- private static final int MAX_ACTIVE_LOCKS = 50;
-
- /** Indicates an invalid SSID. */
- public static final String UNKNOWN_SSID = "";
-
- /** @hide */
- public static final MacAddress ALL_ZEROS_MAC_ADDRESS =
- MacAddress.fromString("00:00:00:00:00:00");
-
- /* Number of currently active WifiLocks and MulticastLocks */
- @UnsupportedAppUsage
- private int mActiveLockCount;
-
- private Context mContext;
- @UnsupportedAppUsage
- IWifiManager mService;
- private final int mTargetSdkVersion;
-
- private Looper mLooper;
- private boolean mVerboseLoggingEnabled = false;
-
- private final Object mLock = new Object(); // lock guarding access to the following vars
- @GuardedBy("mLock")
- private LocalOnlyHotspotCallbackProxy mLOHSCallbackProxy;
- @GuardedBy("mLock")
- private LocalOnlyHotspotObserverProxy mLOHSObserverProxy;
-
- /**
- * Create a new WifiManager instance.
- * Applications will almost always want to use
- * {@link android.content.Context#getSystemService Context.getSystemService} to retrieve
- * the standard {@link android.content.Context#WIFI_SERVICE Context.WIFI_SERVICE}.
- *
- * @param context the application context
- * @param service the Binder interface
- * @param looper the Looper used to deliver callbacks
- * @hide - hide this because it takes in a parameter of type IWifiManager, which
- * is a system private class.
- */
- public WifiManager(@NonNull Context context, @NonNull IWifiManager service,
- @NonNull Looper looper) {
- mContext = context;
- mService = service;
- mLooper = looper;
- mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
- updateVerboseLoggingEnabledFromService();
- }
-
- /**
- * Return a list of all the networks configured for the current foreground
- * user.
- *
- * Not all fields of WifiConfiguration are returned. Only the following
- * fields are filled in:
- *
- * - networkId
- * - SSID
- * - BSSID
- * - priority
- * - allowedProtocols
- * - allowedKeyManagement
- * - allowedAuthAlgorithms
- * - allowedPairwiseCiphers
- * - allowedGroupCiphers
- * - status
- *
- * @return a list of network configurations in the form of a list
- * of {@link WifiConfiguration} objects.
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return an
- * empty list.
- *
- * Deprecation Exemptions:
- *
- * - Device Owner (DO), Profile Owner (PO) and system apps will have access to the full list.
- *
- Callers with Carrier privilege will receive a restricted list only containing
- * configurations which they created.
- *
- */
- @Deprecated
- @RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
- public List getConfiguredNetworks() {
- try {
- ParceledListSlice parceledList =
- mService.getConfiguredNetworks(mContext.getOpPackageName(),
- mContext.getAttributionTag());
- if (parceledList == null) {
- return Collections.emptyList();
- }
- return parceledList.getList();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- @SystemApi
- @RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE, READ_WIFI_CREDENTIAL})
- public List getPrivilegedConfiguredNetworks() {
- try {
- ParceledListSlice parceledList =
- mService.getPrivilegedConfiguredNetworks(mContext.getOpPackageName(),
- mContext.getAttributionTag());
- if (parceledList == null) {
- return Collections.emptyList();
- }
- return parceledList.getList();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns a list of all matching WifiConfigurations for a given list of ScanResult.
- *
- * An empty list will be returned when no configurations are installed or if no configurations
- * match the ScanResult.
- *
- * @param scanResults a list of scanResult that represents the BSSID
- * @return List that consists of {@link WifiConfiguration} and corresponding scanResults per
- * network type({@link #PASSPOINT_HOME_NETWORK} and {@link #PASSPOINT_ROAMING_NETWORK}).
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- @NonNull
- public List>>> getAllMatchingWifiConfigs(
- @NonNull List scanResults) {
- List>>> configs = new ArrayList<>();
- try {
- Map>> results =
- mService.getAllMatchingPasspointProfilesForScanResults(scanResults);
- if (results.isEmpty()) {
- return configs;
- }
- List wifiConfigurations =
- mService.getWifiConfigsForPasspointProfiles(
- new ArrayList<>(results.keySet()));
- for (WifiConfiguration configuration : wifiConfigurations) {
- Map> scanResultsPerNetworkType =
- results.get(configuration.getProfileKey());
- if (scanResultsPerNetworkType != null) {
- configs.add(Pair.create(configuration, scanResultsPerNetworkType));
- }
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
-
- return configs;
- }
-
- /**
- * Retrieve a list of {@link WifiConfiguration} for available {@link WifiNetworkSuggestion}
- * matching the given list of {@link ScanResult}.
- *
- * An available {@link WifiNetworkSuggestion} must satisfy:
- *
- * - Matching one of the {@link ScanResult} from the given list.
- *
- and {@link WifiNetworkSuggestion.Builder#setIsUserAllowedToManuallyConnect(boolean)} set
- * to true.
- *
- *
- * @param scanResults a list of scanResult.
- * @return a list of @link WifiConfiguration} for available {@link WifiNetworkSuggestion}
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- @NonNull
- public List getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(
- @NonNull List scanResults) {
- try {
- return mService.getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(scanResults);
- } catch (RemoteException e) {
- throw e.rethrowAsRuntimeException();
- }
- }
-
- /**
- * Returns a list of unique Hotspot 2.0 OSU (Online Sign-Up) providers associated with a given
- * list of ScanResult.
- *
- * An empty list will be returned if no match is found.
- *
- * @param scanResults a list of ScanResult
- * @return Map that consists {@link OsuProvider} and a list of matching {@link ScanResult}
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- @NonNull
- public Map> getMatchingOsuProviders(
- @Nullable List scanResults) {
- if (scanResults == null) {
- return new HashMap<>();
- }
- try {
- return mService.getMatchingOsuProviders(scanResults);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns the matching Passpoint R2 configurations for given OSU (Online Sign-Up) providers.
- *
- * Given a list of OSU providers, this only returns OSU providers that already have Passpoint R2
- * configurations in the device.
- * An empty map will be returned when there is no matching Passpoint R2 configuration for the
- * given OsuProviders.
- *
- * @param osuProviders a set of {@link OsuProvider}
- * @return Map that consists of {@link OsuProvider} and matching {@link PasspointConfiguration}.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- @NonNull
- public Map getMatchingPasspointConfigsForOsuProviders(
- @NonNull Set osuProviders) {
- try {
- return mService.getMatchingPasspointConfigsForOsuProviders(
- new ArrayList<>(osuProviders));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Add a new network description to the set of configured networks.
- * The {@code networkId} field of the supplied configuration object
- * is ignored.
- *
- * The new network will be marked DISABLED by default. To enable it,
- * called {@link #enableNetwork}.
- *
- * @param config the set of variables that describe the configuration,
- * contained in a {@link WifiConfiguration} object.
- * If the {@link WifiConfiguration} has an Http Proxy set
- * the calling app must be System, or be provisioned as the Profile or Device Owner.
- * @return the ID of the newly created network description. This is used in
- * other operations to specified the network to be acted upon.
- * Returns {@code -1} on failure.
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code -1}.
- *
- * Deprecation Exemptions:
- *
- * - Device Owner (DO), Profile Owner (PO) and system apps.
- *
- */
- @Deprecated
- public int addNetwork(WifiConfiguration config) {
- if (config == null) {
- return -1;
- }
- config.networkId = -1;
- return addOrUpdateNetwork(config);
- }
-
- /**
- * Update the network description of an existing configured network.
- *
- * @param config the set of variables that describe the configuration,
- * contained in a {@link WifiConfiguration} object. It may
- * be sparse, so that only the items that are being changed
- * are non-null. The {@code networkId} field
- * must be set to the ID of the existing network being updated.
- * If the {@link WifiConfiguration} has an Http Proxy set
- * the calling app must be System, or be provisioned as the Profile or Device Owner.
- * @return Returns the {@code networkId} of the supplied
- * {@code WifiConfiguration} on success.
- *
- * Returns {@code -1} on failure, including when the {@code networkId}
- * field of the {@code WifiConfiguration} does not refer to an
- * existing network.
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code -1}.
- *
- * Deprecation Exemptions:
- *
- * - Device Owner (DO), Profile Owner (PO) and system apps.
- *
- */
- @Deprecated
- public int updateNetwork(WifiConfiguration config) {
- if (config == null || config.networkId < 0) {
- return -1;
- }
- return addOrUpdateNetwork(config);
- }
-
- /**
- * Internal method for doing the RPC that creates a new network description
- * or updates an existing one.
- *
- * @param config The possibly sparse object containing the variables that
- * are to set or updated in the network description.
- * @return the ID of the network on success, {@code -1} on failure.
- */
- private int addOrUpdateNetwork(WifiConfiguration config) {
- try {
- return mService.addOrUpdateNetwork(config, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Interface for indicating user selection from the list of networks presented in the
- * {@link NetworkRequestMatchCallback#onMatch(List)}.
- *
- * The platform will implement this callback and pass it along with the
- * {@link NetworkRequestMatchCallback#onUserSelectionCallbackRegistration(
- * NetworkRequestUserSelectionCallback)}. The UI component handling
- * {@link NetworkRequestMatchCallback} will invoke {@link #select(WifiConfiguration)} or
- * {@link #reject()} to return the user's selection back to the platform via this callback.
- * @hide
- */
- @SystemApi
- public interface NetworkRequestUserSelectionCallback {
- /**
- * User selected this network to connect to.
- * @param wifiConfiguration WifiConfiguration object corresponding to the network
- * user selected.
- */
- @SuppressLint("CallbackMethodName")
- default void select(@NonNull WifiConfiguration wifiConfiguration) {}
-
- /**
- * User rejected the app's request.
- */
- @SuppressLint("CallbackMethodName")
- default void reject() {}
- }
-
- /**
- * Interface for network request callback. Should be implemented by applications and passed when
- * calling {@link #registerNetworkRequestMatchCallback(Executor,
- * WifiManager.NetworkRequestMatchCallback)}.
- *
- * This is meant to be implemented by a UI component to present the user with a list of networks
- * matching the app's request. The user is allowed to pick one of these networks to connect to
- * or reject the request by the app.
- * @hide
- */
- @SystemApi
- public interface NetworkRequestMatchCallback {
- /**
- * Invoked to register a callback to be invoked to convey user selection. The callback
- * object passed in this method is to be invoked by the UI component after the service sends
- * a list of matching scan networks using {@link #onMatch(List)} and user picks a network
- * from that list.
- *
- * @param userSelectionCallback Callback object to send back the user selection.
- */
- default void onUserSelectionCallbackRegistration(
- @NonNull NetworkRequestUserSelectionCallback userSelectionCallback) {}
-
- /**
- * Invoked when the active network request is aborted, either because
- * The app released the request, OR
- * Request was overridden by a new request
- * This signals the end of processing for the current request and should stop the UI
- * component. No subsequent calls from the UI component will be handled by the platform.
- */
- default void onAbort() {}
-
- /**
- * Invoked when a network request initiated by an app matches some networks in scan results.
- * This may be invoked multiple times for a single network request as the platform finds new
- * matching networks in scan results.
- *
- * @param scanResults List of {@link ScanResult} objects corresponding to the networks
- * matching the request.
- */
- default void onMatch(@NonNull List scanResults) {}
-
- /**
- * Invoked on a successful connection with the network that the user selected
- * via {@link NetworkRequestUserSelectionCallback}.
- *
- * @param wifiConfiguration WifiConfiguration object corresponding to the network that the
- * user selected.
- */
- default void onUserSelectionConnectSuccess(@NonNull WifiConfiguration wifiConfiguration) {}
-
- /**
- * Invoked on failure to establish connection with the network that the user selected
- * via {@link NetworkRequestUserSelectionCallback}.
- *
- * @param wifiConfiguration WifiConfiguration object corresponding to the network
- * user selected.
- */
- default void onUserSelectionConnectFailure(@NonNull WifiConfiguration wifiConfiguration) {}
- }
-
- /**
- * Callback proxy for NetworkRequestUserSelectionCallback objects.
- * @hide
- */
- private class NetworkRequestUserSelectionCallbackProxy implements
- NetworkRequestUserSelectionCallback {
- private final INetworkRequestUserSelectionCallback mCallback;
-
- NetworkRequestUserSelectionCallbackProxy(
- INetworkRequestUserSelectionCallback callback) {
- mCallback = callback;
- }
-
- @Override
- public void select(@NonNull WifiConfiguration wifiConfiguration) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestUserSelectionCallbackProxy: select "
- + "wificonfiguration: " + wifiConfiguration);
- }
- try {
- mCallback.select(wifiConfiguration);
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to invoke onSelected", e);
- throw e.rethrowFromSystemServer();
- }
- }
-
- @Override
- public void reject() {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestUserSelectionCallbackProxy: reject");
- }
- try {
- mCallback.reject();
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to invoke onRejected", e);
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Callback proxy for NetworkRequestMatchCallback objects.
- * @hide
- */
- private class NetworkRequestMatchCallbackProxy extends INetworkRequestMatchCallback.Stub {
- private final Executor mExecutor;
- private final NetworkRequestMatchCallback mCallback;
-
- NetworkRequestMatchCallbackProxy(Executor executor, NetworkRequestMatchCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void onUserSelectionCallbackRegistration(
- INetworkRequestUserSelectionCallback userSelectionCallback) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestMatchCallbackProxy: "
- + "onUserSelectionCallbackRegistration callback: " + userSelectionCallback);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onUserSelectionCallbackRegistration(
- new NetworkRequestUserSelectionCallbackProxy(userSelectionCallback));
- });
- }
-
- @Override
- public void onAbort() {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestMatchCallbackProxy: onAbort");
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onAbort();
- });
- }
-
- @Override
- public void onMatch(List scanResults) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestMatchCallbackProxy: onMatch scanResults: "
- + scanResults);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onMatch(scanResults);
- });
- }
-
- @Override
- public void onUserSelectionConnectSuccess(WifiConfiguration wifiConfiguration) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestMatchCallbackProxy: onUserSelectionConnectSuccess "
- + " wificonfiguration: " + wifiConfiguration);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onUserSelectionConnectSuccess(wifiConfiguration);
- });
- }
-
- @Override
- public void onUserSelectionConnectFailure(WifiConfiguration wifiConfiguration) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestMatchCallbackProxy: onUserSelectionConnectFailure"
- + " wificonfiguration: " + wifiConfiguration);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onUserSelectionConnectFailure(wifiConfiguration);
- });
- }
- }
-
- /**
- * Registers a callback for NetworkRequest matches. See {@link NetworkRequestMatchCallback}.
- * Caller can unregister a previously registered callback using
- * {@link #unregisterNetworkRequestMatchCallback(NetworkRequestMatchCallback)}
- *
- * Applications should have the
- * {@link android.Manifest.permission#NETWORK_SETTINGS} permission. Callers
- * without the permission will trigger a {@link java.lang.SecurityException}.
- *
- *
- * @param executor The Executor on whose thread to execute the callbacks of the {@code callback}
- * object.
- * @param callback Callback for network match events to register.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void registerNetworkRequestMatchCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull NetworkRequestMatchCallback callback) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "registerNetworkRequestMatchCallback: callback=" + callback
- + ", executor=" + executor);
-
- Binder binder = new Binder();
- try {
- mService.registerNetworkRequestMatchCallback(
- binder, new NetworkRequestMatchCallbackProxy(executor, callback),
- callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Unregisters a callback for NetworkRequest matches. See {@link NetworkRequestMatchCallback}.
- *
- * Applications should have the
- * {@link android.Manifest.permission#NETWORK_SETTINGS} permission. Callers
- * without the permission will trigger a {@link java.lang.SecurityException}.
- *
- *
- * @param callback Callback for network match events to unregister.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void unregisterNetworkRequestMatchCallback(
- @NonNull NetworkRequestMatchCallback callback) {
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "unregisterNetworkRequestMatchCallback: callback=" + callback);
-
- try {
- mService.unregisterNetworkRequestMatchCallback(callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Provide a list of network suggestions to the device. See {@link WifiNetworkSuggestion}
- * for a detailed explanation of the parameters.
- * When the device decides to connect to one of the provided network suggestions, platform sends
- * a directed broadcast {@link #ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION} to the app if
- * the network was created with
- * {@link WifiNetworkSuggestion.Builder#setIsAppInteractionRequired(boolean)} flag set and the
- * app holds {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION}
- * permission.
- *
- * NOTE:
- *
These networks are just a suggestion to the platform. The platform will ultimately
- * decide on which network the device connects to.
- * When an app is uninstalled or disabled, all its suggested networks are discarded.
- * If the device is currently connected to a suggested network which is being removed then the
- * device will disconnect from that network.
- * If user reset network settings, all added suggestions will be discarded. Apps can use
- * {@link #getNetworkSuggestions()} to check if their suggestions are in the device.
- * In-place modification of existing suggestions are allowed.
- * If the provided suggestions include any previously provided suggestions by the app,
- * previous suggestions will be updated.
- * If one of the provided suggestions marks a previously unmetered suggestion as metered and
- * the device is currently connected to that suggested network, then the device will disconnect
- * from that network. The system will immediately re-evaluate all the network candidates
- * and possibly reconnect back to the same suggestion. This disconnect is to make sure that any
- * traffic flowing over unmetered networks isn't accidentally continued over a metered network.
- *
- *
- *
- * @param networkSuggestions List of network suggestions provided by the app.
- * @return Status code for the operation. One of the STATUS_NETWORK_SUGGESTIONS_ values.
- * @throws {@link SecurityException} if the caller is missing required permissions.
- * @see WifiNetworkSuggestion#equals(Object)
- */
- @RequiresPermission(android.Manifest.permission.CHANGE_WIFI_STATE)
- public @NetworkSuggestionsStatusCode int addNetworkSuggestions(
- @NonNull List networkSuggestions) {
- try {
- return mService.addNetworkSuggestions(
- networkSuggestions, mContext.getOpPackageName(), mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Remove some or all of the network suggestions that were previously provided by the app.
- * If one of the suggestions being removed was used to establish connection to the current
- * network, then the device will immediately disconnect from that network.
- *
- * See {@link WifiNetworkSuggestion} for a detailed explanation of the parameters.
- * See {@link WifiNetworkSuggestion#equals(Object)} for the equivalence evaluation used.
- *
- * @param networkSuggestions List of network suggestions to be removed. Pass an empty list
- * to remove all the previous suggestions provided by the app.
- * @return Status code for the operation. One of the STATUS_NETWORK_SUGGESTIONS_ values.
- * Any matching suggestions are removed from the device and will not be considered for any
- * further connection attempts.
- */
- @RequiresPermission(android.Manifest.permission.CHANGE_WIFI_STATE)
- public @NetworkSuggestionsStatusCode int removeNetworkSuggestions(
- @NonNull List networkSuggestions) {
- try {
- return mService.removeNetworkSuggestions(
- networkSuggestions, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get all network suggestions provided by the calling app.
- * See {@link #addNetworkSuggestions(List)}
- * See {@link #removeNetworkSuggestions(List)}
- * @return a list of {@link WifiNetworkSuggestion}
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public @NonNull List getNetworkSuggestions() {
- try {
- return mService.getNetworkSuggestions(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowAsRuntimeException();
- }
- }
-
- /**
- * Returns the max number of network suggestions that are allowed per app on the device.
- * @see #addNetworkSuggestions(List)
- * @see #removeNetworkSuggestions(List)
- */
- public int getMaxNumberOfNetworkSuggestionsPerApp() {
- return getMaxNumberOfNetworkSuggestionsPerApp(
- mContext.getSystemService(ActivityManager.class).isLowRamDevice());
- }
-
- /** @hide */
- public static int getMaxNumberOfNetworkSuggestionsPerApp(boolean isLowRamDevice) {
- return isLowRamDevice
- ? NETWORK_SUGGESTIONS_MAX_PER_APP_LOW_RAM
- : NETWORK_SUGGESTIONS_MAX_PER_APP_HIGH_RAM;
- }
-
- /**
- * Get the Suggestion approval status of the calling app. When an app makes suggestions using
- * the {@link #addNetworkSuggestions(List)} API they may trigger a user approval flow. This API
- * provides the current approval status.
- *
- * @return Status code for the user approval. One of the STATUS_SUGGESTION_APPROVAL_ values.
- * @throws {@link SecurityException} if the caller is missing required permissions.
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public @SuggestionUserApprovalStatus int getNetworkSuggestionUserApprovalStatus() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- return mService.getNetworkSuggestionUserApprovalStatus(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowAsRuntimeException();
- }
- }
-
- /**
- * Add or update a Passpoint configuration. The configuration provides a credential
- * for connecting to Passpoint networks that are operated by the Passpoint
- * service provider specified in the configuration.
- *
- * Each configuration is uniquely identified by a unique key which depends on the contents of
- * the configuration. This allows the caller to install multiple profiles with the same FQDN
- * (Fully qualified domain name). Therefore, in order to update an existing profile, it is
- * first required to remove it using {@link WifiManager#removePasspointConfiguration(String)}.
- * Otherwise, a new profile will be added with both configuration.
- *
- * @param config The Passpoint configuration to be added
- * @throws IllegalArgumentException if configuration is invalid or Passpoint is not enabled on
- * the device.
- *
- * Deprecated for general app usage - except DO/PO apps.
- * See {@link WifiNetworkSuggestion.Builder#setPasspointConfig(PasspointConfiguration)} to
- * create a passpoint suggestion.
- * See {@link #addNetworkSuggestions(List)}, {@link #removeNetworkSuggestions(List)} for new
- * API to add Wi-Fi networks for consideration when auto-connecting to wifi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#R} or above, this API will always fail and throw
- * {@link IllegalArgumentException}.
- *
- * Deprecation Exemptions:
- *
- * - Device Owner (DO), Profile Owner (PO) and system apps.
- *
- */
- public void addOrUpdatePasspointConfiguration(PasspointConfiguration config) {
- try {
- if (!mService.addOrUpdatePasspointConfiguration(config, mContext.getOpPackageName())) {
- throw new IllegalArgumentException();
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Remove the Passpoint configuration identified by its FQDN (Fully Qualified Domain Name) added
- * by the caller.
- *
- * @param fqdn The FQDN of the Passpoint configuration added by the caller to be removed
- * @throws IllegalArgumentException if no configuration is associated with the given FQDN or
- * Passpoint is not enabled on the device.
- * @deprecated This will be non-functional in a future release.
- */
- @Deprecated
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_CARRIER_PROVISIONING
- })
- public void removePasspointConfiguration(String fqdn) {
- try {
- if (!mService.removePasspointConfiguration(fqdn, mContext.getOpPackageName())) {
- throw new IllegalArgumentException();
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return the list of installed Passpoint configurations added by the caller.
- *
- * An empty list will be returned when no configurations are installed.
- *
- * @return A list of {@link PasspointConfiguration} added by the caller
- * @deprecated This will be non-functional in a future release.
- */
- @Deprecated
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- public List getPasspointConfigurations() {
- try {
- return mService.getPasspointConfigurations(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Query for a Hotspot 2.0 release 2 OSU icon file. An {@link #ACTION_PASSPOINT_ICON} intent
- * will be broadcasted once the request is completed. The presence of the intent extra
- * {@link #EXTRA_ICON} will indicate the result of the request.
- * A missing intent extra {@link #EXTRA_ICON} will indicate a failure.
- *
- * @param bssid The BSSID of the AP
- * @param fileName Name of the icon file (remote file) to query from the AP
- *
- * @throws UnsupportedOperationException if Passpoint is not enabled on the device.
- * @hide
- */
- public void queryPasspointIcon(long bssid, String fileName) {
- try {
- mService.queryPasspointIcon(bssid, fileName);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Match the currently associated network against the SP matching the given FQDN
- * @param fqdn FQDN of the SP
- * @return ordinal [HomeProvider, RoamingProvider, Incomplete, None, Declined]
- * @hide
- */
- public int matchProviderWithCurrentNetwork(String fqdn) {
- try {
- return mService.matchProviderWithCurrentNetwork(fqdn);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Remove the specified network from the list of configured networks.
- * This may result in the asynchronous delivery of state change
- * events.
- *
- * Applications are not allowed to remove networks created by other
- * applications.
- *
- * @param netId the ID of the network as returned by {@link #addNetwork} or {@link
- * #getConfiguredNetworks}.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}.
- *
- * Deprecation Exemptions:
- *
- * - Device Owner (DO), Profile Owner (PO) and system apps.
- *
- */
- @Deprecated
- public boolean removeNetwork(int netId) {
- try {
- return mService.removeNetwork(netId, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow a previously configured network to be associated with. If
- * attemptConnect is true, an attempt to connect to the selected
- * network is initiated. This may result in the asynchronous delivery
- * of state change events.
- *
- * Note: Network communication may not use Wi-Fi even if Wi-Fi is connected;
- * traffic may instead be sent through another network, such as cellular data,
- * Bluetooth tethering, or Ethernet. For example, traffic will never use a
- * Wi-Fi network that does not provide Internet access (e.g. a wireless
- * printer), if another network that does offer Internet access (e.g.
- * cellular data) is available. Applications that need to ensure that their
- * network traffic uses Wi-Fi should use APIs such as
- * {@link Network#bindSocket(java.net.Socket)},
- * {@link Network#openConnection(java.net.URL)}, or
- * {@link ConnectivityManager#bindProcessToNetwork} to do so.
- *
- * Applications are not allowed to enable networks created by other
- * applications.
- *
- * @param netId the ID of the network as returned by {@link #addNetwork} or {@link
- * #getConfiguredNetworks}.
- * @param attemptConnect The way to select a particular network to connect to is specify
- * {@code true} for this parameter.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}.
- * Deprecation Exemptions:
- *
- * - Device Owner (DO), Profile Owner (PO) and system apps.
- *
- */
- @Deprecated
- public boolean enableNetwork(int netId, boolean attemptConnect) {
- try {
- return mService.enableNetwork(netId, attemptConnect, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Disable a configured network. The specified network will not be
- * a candidate for associating. This may result in the asynchronous
- * delivery of state change events.
- *
- * Applications are not allowed to disable networks created by other
- * applications.
- *
- * @param netId the ID of the network as returned by {@link #addNetwork} or {@link
- * #getConfiguredNetworks}.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}.
- *
- * Deprecation Exemptions:
- *
- * - Device Owner (DO), Profile Owner (PO) and system apps.
- *
- */
- @Deprecated
- public boolean disableNetwork(int netId) {
- try {
- return mService.disableNetwork(netId, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Disassociate from the currently active access point. This may result
- * in the asynchronous delivery of state change events.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}.
- *
- * Deprecation Exemptions:
- *
- * - Device Owner (DO), Profile Owner (PO) and system apps.
- *
- */
- @Deprecated
- public boolean disconnect() {
- try {
- return mService.disconnect(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Reconnect to the currently active access point, if we are currently
- * disconnected. This may result in the asynchronous delivery of state
- * change events.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}.
- *
- * Deprecation Exemptions:
- *
- * - Device Owner (DO), Profile Owner (PO) and system apps.
- *
- */
- @Deprecated
- public boolean reconnect() {
- try {
- return mService.reconnect(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Reconnect to the currently active access point, even if we are already
- * connected. This may result in the asynchronous delivery of state
- * change events.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always return false.
- */
- @Deprecated
- public boolean reassociate() {
- try {
- return mService.reassociate(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check that the supplicant daemon is responding to requests.
- * @return {@code true} if we were able to communicate with the supplicant and
- * it returned the expected response to the PING message.
- * @deprecated Will return the output of {@link #isWifiEnabled()} instead.
- */
- @Deprecated
- public boolean pingSupplicant() {
- return isWifiEnabled();
- }
-
- /** @hide */
- public static final long WIFI_FEATURE_INFRA = 0x0001L; // Basic infrastructure mode
- /** @hide */
- public static final long WIFI_FEATURE_PASSPOINT = 0x0004L; // Support for GAS/ANQP
- /** @hide */
- public static final long WIFI_FEATURE_P2P = 0x0008L; // Wifi-Direct
- /** @hide */
- public static final long WIFI_FEATURE_MOBILE_HOTSPOT = 0x0010L; // Soft AP
- /** @hide */
- public static final long WIFI_FEATURE_SCANNER = 0x0020L; // WifiScanner APIs
- /** @hide */
- public static final long WIFI_FEATURE_AWARE = 0x0040L; // Wi-Fi AWare networking
- /** @hide */
- public static final long WIFI_FEATURE_D2D_RTT = 0x0080L; // Device-to-device RTT
- /** @hide */
- public static final long WIFI_FEATURE_D2AP_RTT = 0x0100L; // Device-to-AP RTT
- /** @hide */
- public static final long WIFI_FEATURE_BATCH_SCAN = 0x0200L; // Batched Scan (deprecated)
- /** @hide */
- public static final long WIFI_FEATURE_PNO = 0x0400L; // Preferred network offload
- /** @hide */
- public static final long WIFI_FEATURE_ADDITIONAL_STA = 0x0800L; // Support for two STAs
- /** @hide */
- public static final long WIFI_FEATURE_TDLS = 0x1000L; // Tunnel directed link setup
- /** @hide */
- public static final long WIFI_FEATURE_TDLS_OFFCHANNEL = 0x2000L; // TDLS off channel
- /** @hide */
- public static final long WIFI_FEATURE_EPR = 0x4000L; // Enhanced power reporting
- /** @hide */
- public static final long WIFI_FEATURE_AP_STA = 0x8000L; // AP STA Concurrency
- /** @hide */
- public static final long WIFI_FEATURE_LINK_LAYER_STATS = 0x10000L; // Link layer stats
- /** @hide */
- public static final long WIFI_FEATURE_LOGGER = 0x20000L; // WiFi Logger
- /** @hide */
- public static final long WIFI_FEATURE_HAL_EPNO = 0x40000L; // Enhanced PNO
- /** @hide */
- public static final long WIFI_FEATURE_RSSI_MONITOR = 0x80000L; // RSSI Monitor
- /** @hide */
- public static final long WIFI_FEATURE_MKEEP_ALIVE = 0x100000L; // mkeep_alive
- /** @hide */
- public static final long WIFI_FEATURE_CONFIG_NDO = 0x200000L; // ND offload
- /** @hide */
- public static final long WIFI_FEATURE_TRANSMIT_POWER = 0x400000L; // Capture transmit power
- /** @hide */
- public static final long WIFI_FEATURE_CONTROL_ROAMING = 0x800000L; // Control firmware roaming
- /** @hide */
- public static final long WIFI_FEATURE_IE_WHITELIST = 0x1000000L; // Probe IE white listing
- /** @hide */
- public static final long WIFI_FEATURE_SCAN_RAND = 0x2000000L; // Random MAC & Probe seq
- /** @hide */
- public static final long WIFI_FEATURE_TX_POWER_LIMIT = 0x4000000L; // Set Tx power limit
- /** @hide */
- public static final long WIFI_FEATURE_WPA3_SAE = 0x8000000L; // WPA3-Personal SAE
- /** @hide */
- public static final long WIFI_FEATURE_WPA3_SUITE_B = 0x10000000L; // WPA3-Enterprise Suite-B
- /** @hide */
- public static final long WIFI_FEATURE_OWE = 0x20000000L; // Enhanced Open
- /** @hide */
- public static final long WIFI_FEATURE_LOW_LATENCY = 0x40000000L; // Low Latency modes
- /** @hide */
- public static final long WIFI_FEATURE_DPP = 0x80000000L; // DPP (Easy-Connect)
- /** @hide */
- public static final long WIFI_FEATURE_P2P_RAND_MAC = 0x100000000L; // Random P2P MAC
- /** @hide */
- public static final long WIFI_FEATURE_CONNECTED_RAND_MAC = 0x200000000L; // Random STA MAC
- /** @hide */
- public static final long WIFI_FEATURE_AP_RAND_MAC = 0x400000000L; // Random AP MAC
- /** @hide */
- public static final long WIFI_FEATURE_MBO = 0x800000000L; // MBO Support
- /** @hide */
- public static final long WIFI_FEATURE_OCE = 0x1000000000L; // OCE Support
- /** @hide */
- public static final long WIFI_FEATURE_WAPI = 0x2000000000L; // WAPI
- /** @hide */
- public static final long WIFI_FEATURE_INFRA_60G = 0x4000000000L; // 60 GHz Band Support
-
- /** @hide */
- public static final long WIFI_FEATURE_FILS_SHA256 = 0x4000000000L; // FILS-SHA256
-
- /** @hide */
- public static final long WIFI_FEATURE_FILS_SHA384 = 0x8000000000L; // FILS-SHA384
-
- /** @hide */
- public static final long WIFI_FEATURE_SAE_PK = 0x10000000000L; // SAE-PK
-
- /** @hide */
- public static final long WIFI_FEATURE_STA_BRIDGED_AP = 0x20000000000L; // STA + Bridged AP
-
- /** @hide */
- public static final long WIFI_FEATURE_BRIDGED_AP = 0x40000000000L; // Bridged AP
-
- private long getSupportedFeatures() {
- try {
- return mService.getSupportedFeatures();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- private boolean isFeatureSupported(long feature) {
- return (getSupportedFeatures() & feature) == feature;
- }
-
- /**
- * @return true if this adapter supports Passpoint
- * @hide
- */
- public boolean isPasspointSupported() {
- return isFeatureSupported(WIFI_FEATURE_PASSPOINT);
- }
-
- /**
- * @return true if this adapter supports WifiP2pManager (Wi-Fi Direct)
- */
- public boolean isP2pSupported() {
- return isFeatureSupported(WIFI_FEATURE_P2P);
- }
-
- /**
- * @return true if this adapter supports portable Wi-Fi hotspot
- * @hide
- */
- @SystemApi
- public boolean isPortableHotspotSupported() {
- return isFeatureSupported(WIFI_FEATURE_MOBILE_HOTSPOT);
- }
-
- /**
- * @return true if this adapter supports WifiScanner APIs
- * @hide
- */
- @SystemApi
- public boolean isWifiScannerSupported() {
- return isFeatureSupported(WIFI_FEATURE_SCANNER);
- }
-
- /**
- * @return true if this adapter supports Neighbour Awareness Network APIs
- * @hide
- */
- public boolean isWifiAwareSupported() {
- return isFeatureSupported(WIFI_FEATURE_AWARE);
- }
-
- /**
- * Query whether the device supports Station (STA) + Access point (AP) concurrency or not.
- *
- * @return true if this device supports STA + AP concurrency, false otherwise.
- */
- public boolean isStaApConcurrencySupported() {
- return isFeatureSupported(WIFI_FEATURE_AP_STA);
- }
-
- /**
- * Query whether the device supports 2 or more concurrent stations (STA) or not.
- *
- * @return true if this device supports multiple STA concurrency, false otherwise.
- */
- public boolean isMultiStaConcurrencySupported() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return isFeatureSupported(WIFI_FEATURE_ADDITIONAL_STA);
- }
-
- /**
- * @deprecated Please use {@link android.content.pm.PackageManager#hasSystemFeature(String)}
- * with {@link android.content.pm.PackageManager#FEATURE_WIFI_RTT} and
- * {@link android.content.pm.PackageManager#FEATURE_WIFI_AWARE}.
- *
- * @return true if this adapter supports Device-to-device RTT
- * @hide
- */
- @Deprecated
- @SystemApi
- public boolean isDeviceToDeviceRttSupported() {
- return isFeatureSupported(WIFI_FEATURE_D2D_RTT);
- }
-
- /**
- * @deprecated Please use {@link android.content.pm.PackageManager#hasSystemFeature(String)}
- * with {@link android.content.pm.PackageManager#FEATURE_WIFI_RTT}.
- *
- * @return true if this adapter supports Device-to-AP RTT
- */
- @Deprecated
- public boolean isDeviceToApRttSupported() {
- return isFeatureSupported(WIFI_FEATURE_D2AP_RTT);
- }
-
- /**
- * @return true if this adapter supports offloaded connectivity scan
- */
- public boolean isPreferredNetworkOffloadSupported() {
- return isFeatureSupported(WIFI_FEATURE_PNO);
- }
-
- /**
- * @return true if this adapter supports Tunnel Directed Link Setup
- */
- public boolean isTdlsSupported() {
- return isFeatureSupported(WIFI_FEATURE_TDLS);
- }
-
- /**
- * @return true if this adapter supports Off Channel Tunnel Directed Link Setup
- * @hide
- */
- public boolean isOffChannelTdlsSupported() {
- return isFeatureSupported(WIFI_FEATURE_TDLS_OFFCHANNEL);
- }
-
- /**
- * @return true if this adapter supports advanced power/performance counters
- */
- public boolean isEnhancedPowerReportingSupported() {
- return isFeatureSupported(WIFI_FEATURE_LINK_LAYER_STATS);
- }
-
- /**
- * @return true if this device supports connected MAC randomization.
- * @hide
- */
- @SystemApi
- public boolean isConnectedMacRandomizationSupported() {
- return isFeatureSupported(WIFI_FEATURE_CONNECTED_RAND_MAC);
- }
-
- /**
- * @return true if this device supports connected MAC randomization.
- * @hide
- */
- @SystemApi
- public boolean isApMacRandomizationSupported() {
- return isFeatureSupported(WIFI_FEATURE_AP_RAND_MAC);
- }
-
- /**
- * Check if the chipset supports 5GHz band.
- * @return {@code true} if supported, {@code false} otherwise.
- */
- public boolean is5GHzBandSupported() {
- try {
- return mService.is5GHzBandSupported();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check if the chipset supports the 60GHz frequency band.
- *
- * @return {@code true} if supported, {@code false} otherwise.
- * @hide
- */
- @SystemApi
- public boolean is60GHzBandSupported() {
- try {
- return mService.is60GHzBandSupported();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check if the chipset supports 6GHz band.
- * @return {@code true} if supported, {@code false} otherwise.
- */
- public boolean is6GHzBandSupported() {
- try {
- return mService.is6GHzBandSupported();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check if the chipset supports a certain Wi-Fi standard.
- * @param standard the IEEE 802.11 standard to check on.
- * valid values from {@link ScanResult}'s {@code WIFI_STANDARD_}
- * @return {@code true} if supported, {@code false} otherwise.
- */
- public boolean isWifiStandardSupported(@WifiAnnotations.WifiStandard int standard) {
- try {
- return mService.isWifiStandardSupported(standard);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Query whether the device supports Station (STA) + Bridged access point (AP)
- * concurrency or not.
- *
- * The bridged AP support means that the device supports AP + AP concurrency with the 2 APs
- * bridged together.
- *
- * See {@link SoftApConfiguration.Builder#setBands(int[])}
- * or {@link SoftApConfiguration.Builder#setChannels(SparseIntArray)} to configure bridged AP
- * when the bridged AP supported.
- *
- * @return true if this device supports STA + bridged AP concurrency, false otherwise.
- */
- public boolean isStaBridgedApConcurrencySupported() {
- return isFeatureSupported(WIFI_FEATURE_STA_BRIDGED_AP);
- }
-
- /**
- * Query whether the device supports Bridged Access point (AP) concurrency or not.
- *
- * The bridged AP support means that the device supports AP + AP concurrency with the 2 APs
- * bridged together.
- *
- * See {@link SoftApConfiguration.Builder#setBands(int[])}
- * or {@link SoftApConfiguration.Builder#setChannels(SparseIntArray)} to configure bridged AP
- * when the bridged AP supported.
- *
- * @return true if this device supports bridged AP concurrency, false otherwise.
- */
- public boolean isBridgedApConcurrencySupported() {
- return isFeatureSupported(WIFI_FEATURE_BRIDGED_AP);
- }
-
-
- /**
- * Interface for Wi-Fi activity energy info listener. Should be implemented by applications and
- * set when calling {@link WifiManager#getWifiActivityEnergyInfoAsync}.
- *
- * @hide
- */
- @SystemApi
- public interface OnWifiActivityEnergyInfoListener {
- /**
- * Called when Wi-Fi activity energy info is available.
- * Note: this listener is triggered at most once for each call to
- * {@link #getWifiActivityEnergyInfoAsync}.
- *
- * @param info the latest {@link WifiActivityEnergyInfo}, or null if unavailable.
- */
- void onWifiActivityEnergyInfo(@Nullable WifiActivityEnergyInfo info);
- }
-
- private static class OnWifiActivityEnergyInfoProxy
- extends IOnWifiActivityEnergyInfoListener.Stub {
- private final Object mLock = new Object();
- @Nullable @GuardedBy("mLock") private Executor mExecutor;
- @Nullable @GuardedBy("mLock") private OnWifiActivityEnergyInfoListener mListener;
-
- OnWifiActivityEnergyInfoProxy(Executor executor,
- OnWifiActivityEnergyInfoListener listener) {
- mExecutor = executor;
- mListener = listener;
- }
-
- @Override
- public void onWifiActivityEnergyInfo(WifiActivityEnergyInfo info) {
- Executor executor;
- OnWifiActivityEnergyInfoListener listener;
- synchronized (mLock) {
- if (mExecutor == null || mListener == null) {
- return;
- }
- executor = mExecutor;
- listener = mListener;
- // null out to allow garbage collection, prevent triggering listener more than once
- mExecutor = null;
- mListener = null;
- }
- Binder.clearCallingIdentity();
- executor.execute(() -> listener.onWifiActivityEnergyInfo(info));
- }
- }
-
- /**
- * Request to get the current {@link WifiActivityEnergyInfo} asynchronously.
- * Note: This method will return null if {@link #isEnhancedPowerReportingSupported()} returns
- * false.
- *
- * @param executor the executor that the listener will be invoked on
- * @param listener the listener that will receive the {@link WifiActivityEnergyInfo} object
- * when it becomes available. The listener will be triggered at most once for
- * each call to this method.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(ACCESS_WIFI_STATE)
- public void getWifiActivityEnergyInfoAsync(
- @NonNull @CallbackExecutor Executor executor,
- @NonNull OnWifiActivityEnergyInfoListener listener) {
- Objects.requireNonNull(executor, "executor cannot be null");
- Objects.requireNonNull(listener, "listener cannot be null");
- try {
- mService.getWifiActivityEnergyInfoAsync(
- new OnWifiActivityEnergyInfoProxy(executor, listener));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Request a scan for access points. Returns immediately. The availability
- * of the results is made known later by means of an asynchronous event sent
- * on completion of the scan.
- *
- * To initiate a Wi-Fi scan, declare the
- * {@link android.Manifest.permission#CHANGE_WIFI_STATE}
- * permission in the manifest, and perform these steps:
- *
- *
- * - Invoke the following method:
- * {@code ((WifiManager) getSystemService(WIFI_SERVICE)).startScan()}
- * -
- * Register a BroadcastReceiver to listen to
- * {@code SCAN_RESULTS_AVAILABLE_ACTION}.
- * - When a broadcast is received, call:
- * {@code ((WifiManager) getSystemService(WIFI_SERVICE)).getScanResults()}
- *
- * @return {@code true} if the operation succeeded, i.e., the scan was initiated.
- * @deprecated The ability for apps to trigger scan requests will be removed in a future
- * release.
- */
- @Deprecated
- public boolean startScan() {
- return startScan(null);
- }
-
- /** @hide */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
- public boolean startScan(WorkSource workSource) {
- try {
- String packageName = mContext.getOpPackageName();
- String attributionTag = mContext.getAttributionTag();
- return mService.startScan(packageName, attributionTag);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * WPS has been deprecated from Client mode operation.
- *
- * @return null
- * @hide
- * @deprecated This API is deprecated
- */
- public String getCurrentNetworkWpsNfcConfigurationToken() {
- return null;
- }
-
- /**
- * Return dynamic information about the current Wi-Fi connection, if any is active.
- *
- *
- * @return the Wi-Fi information, contained in {@link WifiInfo}.
- *
- * @deprecated Starting with {@link Build.VERSION_CODES#S}, WifiInfo retrieval is moved to
- * {@link ConnectivityManager} API surface. WifiInfo is attached in
- * {@link NetworkCapabilities#getTransportInfo()} which is available via callback in
- * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} or on-demand from
- * {@link ConnectivityManager#getNetworkCapabilities(Network)}.
- *
- *
- * Usage example:
- * {@code
- * final NetworkRequest request =
- * new NetworkRequest.Builder()
- * .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
- * .build();
- * final ConnectivityManager connectivityManager =
- * context.getSystemService(ConnectivityManager.class);
- * final NetworkCallback networkCallback = new NetworkCallback() {
- * ...
- * {@literal @}Override
- * void onAvailable(Network network) {}
- *
- * {@literal @}Override
- * void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
- * WifiInfo wifiInfo = (WifiInfo) networkCapabilities.getTransportInfo();
- * }
- * // etc.
- * };
- * connectivityManager.requestNetwork(request, networkCallback); // For request
- * connectivityManager.registerNetworkCallback(request, networkCallback); // For listen
- * }
- *
- * Compatibility Note:
- *
Apps can continue using this API, however newer features
- * such as ability to mask out location sensitive data in WifiInfo will not be supported
- * via this API.
- *
- */
- @Deprecated
- public WifiInfo getConnectionInfo() {
- try {
- return mService.getConnectionInfo(mContext.getOpPackageName(),
- mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return the results of the latest access point scan.
- * @return the list of access points found in the most recent scan. An app must hold
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission
- * in order to get valid results.
- */
- public List getScanResults() {
- try {
- return mService.getScanResults(mContext.getOpPackageName(),
- mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get the filtered ScanResults which match the network configurations specified by the
- * {@code networkSuggestionsToMatch}. Suggestions which use {@link WifiConfiguration} use
- * SSID and the security type to match. Suggestions which use {@link PasspointConfigration}
- * use the matching rules of Hotspot 2.0.
- * @param networkSuggestionsToMatch The list of {@link WifiNetworkSuggestion} to match against.
- * These may or may not be suggestions which are installed on the device.
- * @param scanResults The scan results to be filtered. Optional - if not provided(empty list),
- * the Wi-Fi service will use the most recent scan results which the system has.
- * @return The map of {@link WifiNetworkSuggestion} to the list of {@link ScanResult}
- * corresponding to networks which match them.
- * @hide
- */
- @SystemApi
- @RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
- @NonNull
- public Map> getMatchingScanResults(
- @NonNull List networkSuggestionsToMatch,
- @Nullable List scanResults) {
- if (networkSuggestionsToMatch == null) {
- throw new IllegalArgumentException("networkSuggestions must not be null.");
- }
- try {
- return mService.getMatchingScanResults(
- networkSuggestionsToMatch, scanResults,
- mContext.getOpPackageName(), mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Set if scanning is always available.
- *
- * If set to {@code true}, apps can issue {@link #startScan} and fetch scan results
- * even when Wi-Fi is turned off.
- *
- * @param isAvailable true to enable, false to disable.
- * @hide
- * @see #isScanAlwaysAvailable()
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setScanAlwaysAvailable(boolean isAvailable) {
- try {
- mService.setScanAlwaysAvailable(isAvailable, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check if scanning is always available.
- *
- * If this return {@code true}, apps can issue {@link #startScan} and fetch scan results
- * even when Wi-Fi is turned off.
- *
- * To change this setting, see {@link #ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE}.
- * @deprecated The ability for apps to trigger scan requests will be removed in a future
- * release.
- */
- @Deprecated
- public boolean isScanAlwaysAvailable() {
- try {
- return mService.isScanAlwaysAvailable();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Tell the device to persist the current list of configured networks.
- *
- * Note: It is possible for this method to change the network IDs of
- * existing networks. You should assume the network IDs can be different
- * after calling this method.
- *
- * @return {@code false}.
- * @deprecated There is no need to call this method -
- * {@link #addNetwork(WifiConfiguration)}, {@link #updateNetwork(WifiConfiguration)}
- * and {@link #removeNetwork(int)} already persist the configurations automatically.
- */
- @Deprecated
- public boolean saveConfiguration() {
- return false;
- }
-
- /**
- * Get the country code.
- * @return the country code in ISO 3166 alpha-2 (2-letter) uppercase format, or null if
- * there is no country code configured.
- * @hide
- */
- @Nullable
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public String getCountryCode() {
- try {
- return mService.getCountryCode();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return the DHCP-assigned addresses from the last successful DHCP request,
- * if any.
- * @return the DHCP information
- */
- public DhcpInfo getDhcpInfo() {
- try {
- return mService.getDhcpInfo();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Enable or disable Wi-Fi.
- *
- * Applications must have the {@link android.Manifest.permission#CHANGE_WIFI_STATE}
- * permission to toggle wifi.
- *
- * @param enabled {@code true} to enable, {@code false} to disable.
- * @return {@code false} if the request cannot be satisfied; {@code true} indicates that wifi is
- * either already in the requested state, or in progress toward the requested state.
- * @throws {@link java.lang.SecurityException} if the caller is missing required permissions.
- *
- * @deprecated Starting with Build.VERSION_CODES#Q, applications are not allowed to
- * enable/disable Wi-Fi.
- * Compatibility Note: For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}. If apps are targeting an older SDK ({@link android.os.Build.VERSION_CODES#P}
- * or below), they can continue to use this API.
- *
- * Deprecation Exemptions:
- *
- * - Device Owner (DO), Profile Owner (PO) and system apps.
- *
- */
- @Deprecated
- public boolean setWifiEnabled(boolean enabled) {
- try {
- return mService.setWifiEnabled(mContext.getOpPackageName(), enabled);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Restart the Wi-Fi subsystem.
- *
- * Restarts the Wi-Fi subsystem - effectively disabling it and re-enabling it. All existing
- * Access Point (AP) associations are torn down, all Soft APs are disabled, Wi-Fi Direct and
- * Wi-Fi Aware are disabled.
- *
- * The state of the system after restart is not guaranteed to match its state before the API is
- * called - for instance the device may associate to a different Access Point (AP), and tethered
- * hotspots may or may not be restored.
- *
- * @param reason If non-null, requests a bug report and attaches the reason string to it. A bug
- * report may still not be generated based on framework criteria - for instance,
- * build type or throttling. The WiFi subsystem is restarted whether or not a bug
- * report is requested or generated.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_AIRPLANE_MODE)
- public void restartWifiSubsystem(@Nullable String reason) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- mService.restartWifiSubsystem(reason);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Gets the Wi-Fi enabled state.
- * @return One of {@link #WIFI_STATE_DISABLED},
- * {@link #WIFI_STATE_DISABLING}, {@link #WIFI_STATE_ENABLED},
- * {@link #WIFI_STATE_ENABLING}, {@link #WIFI_STATE_UNKNOWN}
- * @see #isWifiEnabled()
- */
- public int getWifiState() {
- try {
- return mService.getWifiEnabledState();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return whether Wi-Fi is enabled or disabled.
- * @return {@code true} if Wi-Fi is enabled
- * @see #getWifiState()
- */
- public boolean isWifiEnabled() {
- return getWifiState() == WIFI_STATE_ENABLED;
- }
-
- /**
- * Calculates the level of the signal. This should be used any time a signal
- * is being shown.
- *
- * @param rssi The power of the signal measured in RSSI.
- * @param numLevels The number of levels to consider in the calculated level.
- * @return A level of the signal, given in the range of 0 to numLevels-1 (both inclusive).
- * @deprecated Callers should use {@link #calculateSignalLevel(int)} instead to get the
- * signal level using the system default RSSI thresholds, or otherwise compute the RSSI level
- * themselves using their own formula.
- */
- @Deprecated
- public static int calculateSignalLevel(int rssi, int numLevels) {
- if (rssi <= MIN_RSSI) {
- return 0;
- } else if (rssi >= MAX_RSSI) {
- return numLevels - 1;
- } else {
- float inputRange = (MAX_RSSI - MIN_RSSI);
- float outputRange = (numLevels - 1);
- return (int)((float)(rssi - MIN_RSSI) * outputRange / inputRange);
- }
- }
-
- /**
- * Given a raw RSSI, return the RSSI signal quality rating using the system default RSSI
- * quality rating thresholds.
- * @param rssi a raw RSSI value, in dBm, usually between -55 and -90
- * @return the RSSI signal quality rating, in the range
- * [0, {@link #getMaxSignalLevel()}], where 0 is the lowest (worst signal) RSSI
- * rating and {@link #getMaxSignalLevel()} is the highest (best signal) RSSI rating.
- */
- @IntRange(from = 0)
- public int calculateSignalLevel(int rssi) {
- try {
- return mService.calculateSignalLevel(rssi);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get the system default maximum signal level.
- * This is the maximum RSSI level returned by {@link #calculateSignalLevel(int)}.
- */
- @IntRange(from = 0)
- public int getMaxSignalLevel() {
- return calculateSignalLevel(Integer.MAX_VALUE);
- }
-
- /**
- * Compares two signal strengths.
- *
- * @param rssiA The power of the first signal measured in RSSI.
- * @param rssiB The power of the second signal measured in RSSI.
- * @return Returns <0 if the first signal is weaker than the second signal,
- * 0 if the two signals have the same strength, and >0 if the first
- * signal is stronger than the second signal.
- */
- public static int compareSignalLevel(int rssiA, int rssiB) {
- return rssiA - rssiB;
- }
-
- /**
- * Call allowing ConnectivityService to update WifiService with interface mode changes.
- *
- * @param ifaceName String name of the updated interface, or null to represent all interfaces
- * @param mode int representing the new mode, one of:
- * {@link #IFACE_IP_MODE_TETHERED},
- * {@link #IFACE_IP_MODE_LOCAL_ONLY},
- * {@link #IFACE_IP_MODE_CONFIGURATION_ERROR},
- * {@link #IFACE_IP_MODE_UNSPECIFIED}
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_STACK,
- NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
- })
- public void updateInterfaceIpState(@Nullable String ifaceName, @IfaceIpMode int mode) {
- try {
- mService.updateInterfaceIpState(ifaceName, mode);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /* Wi-Fi/Cellular Coex */
-
- /**
- * Mandatory coex restriction flag for Wi-Fi Direct.
- *
- * @see #setCoexUnsafeChannels(Set, int)
- *
- * @hide
- */
- @SystemApi
- public static final int COEX_RESTRICTION_WIFI_DIRECT = 0x1 << 0;
-
- /**
- * Mandatory coex restriction flag for SoftAP
- *
- * @see #setCoexUnsafeChannels(Set, int)
- *
- * @hide
- */
- @SystemApi
- public static final int COEX_RESTRICTION_SOFTAP = 0x1 << 1;
-
- /**
- * Mandatory coex restriction flag for Wi-Fi Aware.
- *
- * @see #setCoexUnsafeChannels(Set, int)
- *
- * @hide
- */
- @SystemApi
- public static final int COEX_RESTRICTION_WIFI_AWARE = 0x1 << 2;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(flag = true, prefix = {"COEX_RESTRICTION_"}, value = {
- COEX_RESTRICTION_WIFI_DIRECT,
- COEX_RESTRICTION_SOFTAP,
- COEX_RESTRICTION_WIFI_AWARE
- })
- public @interface CoexRestriction {}
-
- /**
- * @return {@code true} if the default coex algorithm is enabled. {@code false} otherwise.
- *
- * @hide
- */
- public boolean isDefaultCoexAlgorithmEnabled() {
- try {
- return mService.isDefaultCoexAlgorithmEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Specify the set of {@link CoexUnsafeChannel} to propagate through the framework for
- * Wi-Fi/Cellular coex channel avoidance if the default algorithm is disabled via overlay
- * (i.e. config_wifiCoexDefaultAlgorithmEnabled = false). Otherwise do nothing.
- *
- * @param unsafeChannels Set of {@link CoexUnsafeChannel} to avoid.
- * @param restrictions Bitmap of {@link CoexRestriction} specifying the mandatory restricted
- * uses of the specified channels. If any restrictions are set, then the
- * supplied CoexUnsafeChannels will be completely avoided for the
- * specified modes, rather than be avoided with best effort.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_COEX_UNSAFE_CHANNELS)
- public void setCoexUnsafeChannels(@NonNull Set unsafeChannels,
- int restrictions) {
- if (unsafeChannels == null) {
- throw new IllegalArgumentException("unsafeChannels must not be null");
- }
- try {
- mService.setCoexUnsafeChannels(new ArrayList<>(unsafeChannels), restrictions);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns the set of current {@link CoexUnsafeChannel} being used for Wi-Fi/Cellular coex
- * channel avoidance.
- *
- * This returns the set calculated by the default algorithm if
- * config_wifiCoexDefaultAlgorithmEnabled is {@code true}. Otherwise, returns the set supplied
- * in {@link #setCoexUnsafeChannels(Set, int)}.
- *
- * If any {@link CoexRestriction} flags are set in {@link #getCoexRestrictions()}, then the
- * CoexUnsafeChannels should be totally avoided (i.e. not best effort) for the Wi-Fi modes
- * specified by the flags.
- *
- * @return Set of current CoexUnsafeChannels.
- *
- * @hide
- */
- @NonNull
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_ACCESS_COEX_UNSAFE_CHANNELS)
- public Set getCoexUnsafeChannels() {
- try {
- return new HashSet<>(mService.getCoexUnsafeChannels());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns the current coex restrictions being used for Wi-Fi/Cellular coex
- * channel avoidance.
- *
- * This returns the restrictions calculated by the default algorithm if
- * config_wifiCoexDefaultAlgorithmEnabled is {@code true}. Otherwise, returns the value supplied
- * in {@link #setCoexUnsafeChannels(Set, int)}.
- *
- * @return int containing a bitwise-OR combination of {@link CoexRestriction}.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_ACCESS_COEX_UNSAFE_CHANNELS)
- public int getCoexRestrictions() {
- try {
- return mService.getCoexRestrictions();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Registers a CoexCallback to listen on the current CoexUnsafeChannels and restrictions being
- * used for Wi-Fi/cellular coex channel avoidance.
- * @param executor Executor to execute listener callback on
- * @param callback CoexCallback to register
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_ACCESS_COEX_UNSAFE_CHANNELS)
- public void registerCoexCallback(
- @NonNull @CallbackExecutor Executor executor, @NonNull CoexCallback callback) {
- if (executor == null) throw new IllegalArgumentException("executor must not be null");
- if (callback == null) throw new IllegalArgumentException("callback must not be null");
- CoexCallback.CoexCallbackProxy proxy = callback.getProxy();
- proxy.initProxy(executor, callback);
- try {
- mService.registerCoexCallback(proxy);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Unregisters a CoexCallback from listening on the current CoexUnsafeChannels and restrictions
- * being used for Wi-Fi/cellular coex channel avoidance.
- * @param callback CoexCallback to unregister
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_ACCESS_COEX_UNSAFE_CHANNELS)
- public void unregisterCoexCallback(@NonNull CoexCallback callback) {
- if (callback == null) throw new IllegalArgumentException("callback must not be null");
- CoexCallback.CoexCallbackProxy proxy = callback.getProxy();
- try {
- mService.unregisterCoexCallback(proxy);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- } finally {
- proxy.cleanUpProxy();
- }
- }
-
- /**
- * Abstract callback class for applications to receive updates about current CoexUnsafeChannels
- * for Wi-Fi/Cellular coex channel avoidance.
- *
- * @hide
- */
- @SystemApi
- public abstract static class CoexCallback {
- private final CoexCallbackProxy mCoexCallbackProxy;
-
- public CoexCallback() {
- mCoexCallbackProxy = new CoexCallbackProxy();
- }
-
- /*package*/ @NonNull
- CoexCallbackProxy getProxy() {
- return mCoexCallbackProxy;
- }
-
- /**
- * Indicates that the current CoexUnsafeChannels or restrictions have changed.
- * Clients should call {@link #getCoexUnsafeChannels()} and {@link #getCoexRestrictions()}
- * to get the updated values.
- */
- public abstract void onCoexUnsafeChannelsChanged();
-
- /**
- * Callback proxy for CoexCallback objects.
- */
- private static class CoexCallbackProxy extends ICoexCallback.Stub {
- private final Object mLock = new Object();
- @Nullable @GuardedBy("mLock") private Executor mExecutor;
- @Nullable @GuardedBy("mLock") private CoexCallback mCallback;
-
- CoexCallbackProxy() {
- mExecutor = null;
- mCallback = null;
- }
-
- /*package*/ void initProxy(@NonNull Executor executor,
- @NonNull CoexCallback callback) {
- synchronized (mLock) {
- mExecutor = executor;
- mCallback = callback;
- }
- }
-
- /*package*/ void cleanUpProxy() {
- synchronized (mLock) {
- mExecutor = null;
- mCallback = null;
- }
- }
-
- @Override
- public void onCoexUnsafeChannelsChanged() {
- Executor executor;
- CoexCallback callback;
- synchronized (mLock) {
- executor = mExecutor;
- callback = mCallback;
- }
- if (executor == null || callback == null) {
- return;
- }
- Binder.clearCallingIdentity();
- executor.execute(callback::onCoexUnsafeChannelsChanged);
- }
- }
- }
-
- /**
- * Start Soft AP (hotspot) mode for tethering purposes with the specified configuration.
- * Note that starting Soft AP mode may disable station mode operation if the device does not
- * support concurrency.
- * @param wifiConfig SSID, security and channel details as part of WifiConfiguration, or null to
- * use the persisted Soft AP configuration that was previously set using
- * {@link #setWifiApConfiguration(WifiConfiguration)}.
- * @return {@code true} if the operation succeeded, {@code false} otherwise
- *
- * @hide
- */
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_STACK,
- NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
- })
- public boolean startSoftAp(@Nullable WifiConfiguration wifiConfig) {
- try {
- return mService.startSoftAp(wifiConfig, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Start Soft AP (hotspot) mode for tethering purposes with the specified configuration.
- * Note that starting Soft AP mode may disable station mode operation if the device does not
- * support concurrency.
- * @param softApConfig A valid SoftApConfiguration specifying the configuration of the SAP,
- * or null to use the persisted Soft AP configuration that was previously
- * set using {@link #setSoftApConfiguration(softApConfiguration)}.
- * @return {@code true} if the operation succeeded, {@code false} otherwise
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_STACK,
- NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
- })
- public boolean startTetheredHotspot(@Nullable SoftApConfiguration softApConfig) {
- try {
- return mService.startTetheredHotspot(softApConfig, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
-
- /**
- * Stop SoftAp mode.
- * Note that stopping softap mode will restore the previous wifi mode.
- * @return {@code true} if the operation succeeds, {@code false} otherwise
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_STACK,
- NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
- })
- public boolean stopSoftAp() {
- try {
- return mService.stopSoftAp();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Request a local only hotspot that an application can use to communicate between co-located
- * devices connected to the created WiFi hotspot. The network created by this method will not
- * have Internet access. Each application can make a single request for the hotspot, but
- * multiple applications could be requesting the hotspot at the same time. When multiple
- * applications have successfully registered concurrently, they will be sharing the underlying
- * hotspot. {@link LocalOnlyHotspotCallback#onStarted(LocalOnlyHotspotReservation)} is called
- * when the hotspot is ready for use by the application.
- *
- * Each application can make a single active call to this method. The {@link
- * LocalOnlyHotspotCallback#onStarted(LocalOnlyHotspotReservation)} callback supplies the
- * requestor with a {@link LocalOnlyHotspotReservation} that contains a
- * {@link SoftApConfiguration} with the SSID, security type and credentials needed to connect
- * to the hotspot. Communicating this information is up to the application.
- *
- * If the LocalOnlyHotspot cannot be created, the {@link LocalOnlyHotspotCallback#onFailed(int)}
- * method will be called. Example failures include errors bringing up the network or if
- * there is an incompatible operating mode. For example, if the user is currently using Wifi
- * Tethering to provide an upstream to another device, LocalOnlyHotspot will not start due to
- * an incompatible mode. The possible error codes include:
- * {@link LocalOnlyHotspotCallback#ERROR_NO_CHANNEL},
- * {@link LocalOnlyHotspotCallback#ERROR_GENERIC},
- * {@link LocalOnlyHotspotCallback#ERROR_INCOMPATIBLE_MODE} and
- * {@link LocalOnlyHotspotCallback#ERROR_TETHERING_DISALLOWED}.
- *
- * Internally, requests will be tracked to prevent the hotspot from being torn down while apps
- * are still using it. The {@link LocalOnlyHotspotReservation} object passed in the {@link
- * LocalOnlyHotspotCallback#onStarted(LocalOnlyHotspotReservation)} call should be closed when
- * the LocalOnlyHotspot is no longer needed using {@link LocalOnlyHotspotReservation#close()}.
- * Since the hotspot may be shared among multiple applications, removing the final registered
- * application request will trigger the hotspot teardown. This means that applications should
- * not listen to broadcasts containing wifi state to determine if the hotspot was stopped after
- * they are done using it. Additionally, once {@link LocalOnlyHotspotReservation#close()} is
- * called, applications will not receive callbacks of any kind.
- *
- * Applications should be aware that the user may also stop the LocalOnlyHotspot through the
- * Settings UI; it is not guaranteed to stay up as long as there is a requesting application.
- * The requestors will be notified of this case via
- * {@link LocalOnlyHotspotCallback#onStopped()}. Other cases may arise where the hotspot is
- * torn down (Emergency mode, etc). Application developers should be aware that it can stop
- * unexpectedly, but they will receive a notification if they have properly registered.
- *
- * Applications should also be aware that this network will be shared with other applications.
- * Applications are responsible for protecting their data on this network (e.g., TLS).
- *
- * Applications need to have the following permissions to start LocalOnlyHotspot: {@link
- * android.Manifest.permission#CHANGE_WIFI_STATE} and {@link
- * android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION}. Callers without
- * the permissions will trigger a {@link java.lang.SecurityException}.
- *
- * @param callback LocalOnlyHotspotCallback for the application to receive updates about
- * operating status.
- * @param handler Handler to be used for callbacks. If the caller passes a null Handler, the
- * main thread will be used.
- */
- @RequiresPermission(allOf = {
- android.Manifest.permission.CHANGE_WIFI_STATE,
- android.Manifest.permission.ACCESS_FINE_LOCATION})
- public void startLocalOnlyHotspot(LocalOnlyHotspotCallback callback,
- @Nullable Handler handler) {
- Executor executor = handler == null ? null : new HandlerExecutor(handler);
- startLocalOnlyHotspotInternal(null, executor, callback);
- }
-
- /**
- * Starts a local-only hotspot with a specific configuration applied. See
- * {@link #startLocalOnlyHotspot(LocalOnlyHotspotCallback, Handler)}.
- *
- * Applications need either {@link android.Manifest.permission#NETWORK_SETUP_WIZARD} or
- * {@link android.Manifest.permission#NETWORK_SETTINGS} to call this method.
- *
- * Since custom configuration settings may be incompatible with each other, the hotspot started
- * through this method cannot coexist with another hotspot created through
- * startLocalOnlyHotspot. If this is attempted, the first hotspot request wins and others
- * receive {@link LocalOnlyHotspotCallback#ERROR_GENERIC} through
- * {@link LocalOnlyHotspotCallback#onFailed}.
- *
- * @param config Custom configuration for the hotspot. See {@link SoftApConfiguration}.
- * @param executor Executor to run callback methods on, or null to use the main thread.
- * @param callback Callback object for updates about hotspot status, or null for no updates.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void startLocalOnlyHotspot(@NonNull SoftApConfiguration config,
- @Nullable Executor executor,
- @Nullable LocalOnlyHotspotCallback callback) {
- Objects.requireNonNull(config);
- startLocalOnlyHotspotInternal(config, executor, callback);
- }
-
- /**
- * Common implementation of both configurable and non-configurable LOHS.
- *
- * @param config App-specified configuration, or null. When present, additional privileges are
- * required, and the hotspot cannot be shared with other clients.
- * @param executor Executor to run callback methods on, or null to use the main thread.
- * @param callback Callback object for updates about hotspot status, or null for no updates.
- */
- private void startLocalOnlyHotspotInternal(
- @Nullable SoftApConfiguration config,
- @Nullable Executor executor,
- @Nullable LocalOnlyHotspotCallback callback) {
- if (executor == null) {
- executor = mContext.getMainExecutor();
- }
- synchronized (mLock) {
- LocalOnlyHotspotCallbackProxy proxy =
- new LocalOnlyHotspotCallbackProxy(this, executor, callback);
- try {
- String packageName = mContext.getOpPackageName();
- String featureId = mContext.getAttributionTag();
- int returnCode = mService.startLocalOnlyHotspot(proxy, packageName, featureId,
- config);
- if (returnCode != LocalOnlyHotspotCallback.REQUEST_REGISTERED) {
- // Send message to the proxy to make sure we call back on the correct thread
- proxy.onHotspotFailed(returnCode);
- return;
- }
- mLOHSCallbackProxy = proxy;
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Cancels a pending local only hotspot request. This can be used by the calling application to
- * cancel the existing request if the provided callback has not been triggered. Calling this
- * method will be equivalent to closing the returned LocalOnlyHotspotReservation, but it is not
- * explicitly required.
- *
- * When cancelling this request, application developers should be aware that there may still be
- * outstanding local only hotspot requests and the hotspot may still start, or continue running.
- * Additionally, if a callback was registered, it will no longer be triggered after calling
- * cancel.
- *
- * @hide
- */
- @UnsupportedAppUsage
- public void cancelLocalOnlyHotspotRequest() {
- synchronized (mLock) {
- stopLocalOnlyHotspot();
- }
- }
-
- /**
- * Method used to inform WifiService that the LocalOnlyHotspot is no longer needed. This
- * method is used by WifiManager to release LocalOnlyHotspotReservations held by calling
- * applications and removes the internal tracking for the hotspot request. When all requesting
- * applications are finished using the hotspot, it will be stopped and WiFi will return to the
- * previous operational mode.
- *
- * This method should not be called by applications. Instead, they should call the close()
- * method on their LocalOnlyHotspotReservation.
- */
- private void stopLocalOnlyHotspot() {
- synchronized (mLock) {
- if (mLOHSCallbackProxy == null) {
- // nothing to do, the callback was already cleaned up.
- return;
- }
- mLOHSCallbackProxy = null;
- try {
- mService.stopLocalOnlyHotspot();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Allow callers (Settings UI) to watch LocalOnlyHotspot state changes. Callers will
- * receive a {@link LocalOnlyHotspotSubscription} object as a parameter of the
- * {@link LocalOnlyHotspotObserver#onRegistered(LocalOnlyHotspotSubscription)}. The registered
- * callers will receive the {@link LocalOnlyHotspotObserver#onStarted(SoftApConfiguration)} and
- * {@link LocalOnlyHotspotObserver#onStopped()} callbacks.
- *
- * Applications should have the
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION}
- * permission. Callers without the permission will trigger a
- * {@link java.lang.SecurityException}.
- *
- * @param observer LocalOnlyHotspotObserver callback.
- * @param handler Handler to use for callbacks
- *
- * @hide
- */
- public void watchLocalOnlyHotspot(LocalOnlyHotspotObserver observer,
- @Nullable Handler handler) {
- Executor executor = handler == null ? mContext.getMainExecutor()
- : new HandlerExecutor(handler);
- synchronized (mLock) {
- mLOHSObserverProxy =
- new LocalOnlyHotspotObserverProxy(this, executor, observer);
- try {
- mService.startWatchLocalOnlyHotspot(mLOHSObserverProxy);
- mLOHSObserverProxy.registered();
- } catch (RemoteException e) {
- mLOHSObserverProxy = null;
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Allow callers to stop watching LocalOnlyHotspot state changes. After calling this method,
- * applications will no longer receive callbacks.
- *
- * @hide
- */
- public void unregisterLocalOnlyHotspotObserver() {
- synchronized (mLock) {
- if (mLOHSObserverProxy == null) {
- // nothing to do, the callback was already cleaned up
- return;
- }
- mLOHSObserverProxy = null;
- try {
- mService.stopWatchLocalOnlyHotspot();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Gets the tethered Wi-Fi hotspot enabled state.
- * @return One of {@link #WIFI_AP_STATE_DISABLED},
- * {@link #WIFI_AP_STATE_DISABLING}, {@link #WIFI_AP_STATE_ENABLED},
- * {@link #WIFI_AP_STATE_ENABLING}, {@link #WIFI_AP_STATE_FAILED}
- * @see #isWifiApEnabled()
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
- public int getWifiApState() {
- try {
- return mService.getWifiApEnabledState();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return whether tethered Wi-Fi AP is enabled or disabled.
- * @return {@code true} if tethered Wi-Fi AP is enabled
- * @see #getWifiApState()
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
- public boolean isWifiApEnabled() {
- return getWifiApState() == WIFI_AP_STATE_ENABLED;
- }
-
- /**
- * Gets the tethered Wi-Fi AP Configuration.
- * @return AP details in WifiConfiguration
- *
- * Note that AP detail may contain configuration which is cannot be represented
- * by the legacy WifiConfiguration, in such cases a null will be returned.
- *
- * @deprecated This API is deprecated. Use {@link #getSoftApConfiguration()} instead.
- * @hide
- */
- @Nullable
- @SystemApi
- @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
- @Deprecated
- public WifiConfiguration getWifiApConfiguration() {
- try {
- return mService.getWifiApConfiguration();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Gets the Wi-Fi tethered AP Configuration.
- * @return AP details in {@link SoftApConfiguration}
- *
- * @hide
- */
- @NonNull
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.OVERRIDE_WIFI_CONFIG
- })
- public SoftApConfiguration getSoftApConfiguration() {
- try {
- return mService.getSoftApConfiguration();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Sets the tethered Wi-Fi AP Configuration.
- * @return {@code true} if the operation succeeded, {@code false} otherwise
- *
- * @deprecated This API is deprecated. Use {@link #setSoftApConfiguration(SoftApConfiguration)}
- * instead.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.CHANGE_WIFI_STATE)
- @Deprecated
- public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
- try {
- return mService.setWifiApConfiguration(wifiConfig, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Sets the tethered Wi-Fi AP Configuration.
- *
- * If the API is called while the tethered soft AP is enabled, the configuration will apply to
- * the current soft AP if the new configuration only includes
- * {@link SoftApConfiguration.Builder#setMaxNumberOfClients(int)}
- * or {@link SoftApConfiguration.Builder#setShutdownTimeoutMillis(long)}
- * or {@link SoftApConfiguration.Builder#setClientControlByUserEnabled(boolean)}
- * or {@link SoftApConfiguration.Builder#setBlockedClientList(List)}
- * or {@link SoftApConfiguration.Builder#setAllowedClientList(List)}
- *
- * Otherwise, the configuration changes will be applied when the Soft AP is next started
- * (the framework will not stop/start the AP).
- *
- * @param softApConfig A valid SoftApConfiguration specifying the configuration of the SAP.
- * @return {@code true} if the operation succeeded, {@code false} otherwise
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.OVERRIDE_WIFI_CONFIG
- })
- public boolean setSoftApConfiguration(@NonNull SoftApConfiguration softApConfig) {
- try {
- return mService.setSoftApConfiguration(
- softApConfig, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Enable/Disable TDLS on a specific local route.
- *
- *
- * TDLS enables two wireless endpoints to talk to each other directly
- * without going through the access point that is managing the local
- * network. It saves bandwidth and improves quality of the link.
- *
- *
- * This API enables/disables the option of using TDLS. If enabled, the
- * underlying hardware is free to use TDLS or a hop through the access
- * point. If disabled, existing TDLS session is torn down and
- * hardware is restricted to use access point for transferring wireless
- * packets. Default value for all routes is 'disabled', meaning restricted
- * to use access point for transferring packets.
- *
- *
- * @param remoteIPAddress IP address of the endpoint to setup TDLS with
- * @param enable true = setup and false = tear down TDLS
- */
- public void setTdlsEnabled(InetAddress remoteIPAddress, boolean enable) {
- try {
- mService.enableTdls(remoteIPAddress.getHostAddress(), enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Similar to {@link #setTdlsEnabled(InetAddress, boolean) }, except
- * this version allows you to specify remote endpoint with a MAC address.
- * @param remoteMacAddress MAC address of the remote endpoint such as 00:00:0c:9f:f2:ab
- * @param enable true = setup and false = tear down TDLS
- */
- public void setTdlsEnabledWithMacAddress(String remoteMacAddress, boolean enable) {
- try {
- mService.enableTdlsWithMacAddress(remoteMacAddress, enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed due to an internal error.
- * @hide
- */
- public static final int ERROR = 0;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation is already in progress
- * @hide
- */
- public static final int IN_PROGRESS = 1;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed because the framework is busy and
- * unable to service the request
- * @hide
- */
- public static final int BUSY = 2;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef({ERROR, IN_PROGRESS, BUSY})
- public @interface ActionListenerFailureReason {}
-
- /* WPS specific errors */
- /** WPS overlap detected
- * @deprecated This is deprecated
- */
- public static final int WPS_OVERLAP_ERROR = 3;
- /** WEP on WPS is prohibited
- * @deprecated This is deprecated
- */
- public static final int WPS_WEP_PROHIBITED = 4;
- /** TKIP only prohibited
- * @deprecated This is deprecated
- */
- public static final int WPS_TKIP_ONLY_PROHIBITED = 5;
- /** Authentication failure on WPS
- * @deprecated This is deprecated
- */
- public static final int WPS_AUTH_FAILURE = 6;
- /** WPS timed out
- * @deprecated This is deprecated
- */
- public static final int WPS_TIMED_OUT = 7;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed due to invalid inputs
- * @hide
- */
- public static final int INVALID_ARGS = 8;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed due to user permissions.
- * @hide
- */
- public static final int NOT_AUTHORIZED = 9;
-
- /**
- * Interface for callback invocation on an application action
- * @hide
- */
- @SystemApi
- public interface ActionListener {
- /**
- * The operation succeeded.
- */
- void onSuccess();
- /**
- * The operation failed.
- * @param reason The reason for failure depends on the operation.
- */
- void onFailure(@ActionListenerFailureReason int reason);
- }
-
- /** Interface for callback invocation on a start WPS action
- * @deprecated This is deprecated
- */
- public static abstract class WpsCallback {
-
- /** WPS start succeeded
- * @deprecated This API is deprecated
- */
- public abstract void onStarted(String pin);
-
- /** WPS operation completed successfully
- * @deprecated This API is deprecated
- */
- public abstract void onSucceeded();
-
- /**
- * WPS operation failed
- * @param reason The reason for failure could be one of
- * {@link #WPS_TKIP_ONLY_PROHIBITED}, {@link #WPS_OVERLAP_ERROR},
- * {@link #WPS_WEP_PROHIBITED}, {@link #WPS_TIMED_OUT} or {@link #WPS_AUTH_FAILURE}
- * and some generic errors.
- * @deprecated This API is deprecated
- */
- public abstract void onFailed(int reason);
- }
-
- /**
- * Base class for soft AP callback. Should be extended by applications and set when calling
- * {@link WifiManager#registerSoftApCallback(Executor, SoftApCallback)}.
- *
- * @hide
- */
- @SystemApi
- public interface SoftApCallback {
- /**
- * Called when soft AP state changes.
- *
- * @param state the new AP state. One of {@link #WIFI_AP_STATE_DISABLED},
- * {@link #WIFI_AP_STATE_DISABLING}, {@link #WIFI_AP_STATE_ENABLED},
- * {@link #WIFI_AP_STATE_ENABLING}, {@link #WIFI_AP_STATE_FAILED}
- * @param failureReason reason when in failed state. One of
- * {@link #SAP_START_FAILURE_GENERAL},
- * {@link #SAP_START_FAILURE_NO_CHANNEL},
- * {@link #SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}
- */
- default void onStateChanged(@WifiApState int state, @SapStartFailure int failureReason) {}
-
- /**
- * Called when the connected clients to soft AP changes.
- *
- * @param clients the currently connected clients
- */
- default void onConnectedClientsChanged(@NonNull List clients) {}
-
-
- /**
- * Called when the connected clients for a soft AP instance change.
- *
- * When the Soft AP is configured in single AP mode, this callback is invoked
- * with the same {@link SoftApInfo} for all connected clients changes.
- * When the Soft AP is configured in bridged mode, this callback is invoked with
- * the corresponding {@link SoftApInfo} for the instance in which the connected clients
- * changed.
- *
- * Use {@link #onConnectedClientsChanged(List)} if you don't care about
- * the mapping from SoftApInfo instance to connected clients.
- *
- * @param info The {@link SoftApInfo} of the AP.
- * @param clients The currently connected clients on the AP instance specified by
- * {@code info}.
- */
- default void onConnectedClientsChanged(@NonNull SoftApInfo info,
- @NonNull List clients) {}
-
- /**
- * Called when information of softap changes.
- *
- * Note: this API is only valid when the Soft AP is configured as a single AP
- * - not as a bridged AP (2 Soft APs). When the Soft AP is configured as bridged AP
- * this callback will not be triggered - use the
- * {@link #onInfoChanged(List)} callback in bridged AP mode.
- *
- * @param softApInfo is the softap information. {@link SoftApInfo}
- */
- default void onInfoChanged(@NonNull SoftApInfo softApInfo) {
- // Do nothing: can be updated to add SoftApInfo details (e.g. channel) to the UI.
- }
-
- /**
- * Called when information of softap changes.
- *
- * The number of the information elements in the list depends on Soft AP configuration
- * and state.
- * For instance, an empty list will be returned when the Soft AP is disabled.
- * One information element will be returned in the list when the Soft AP is configured
- * as a single AP, and two information elements will be returned in the list
- * when the Soft AP is configured in bridged mode.
- *
- * Note: One of the Soft APs may be shut down independently of the other by the framework,
- * for instance if no devices are connected to it for some duration.
- * In that case, one information element will be returned in the list in bridged mode.
- *
- * See {@link #isBridgedApConcurrencySupported()} for the detail of the bridged AP.
- *
- * @param softApInfoList is the list of the softap information elements. {@link SoftApInfo}
- */
- default void onInfoChanged(@NonNull List softApInfoList) {
- // Do nothing: can be updated to add SoftApInfo details (e.g. channel) to the UI.
- }
-
- /**
- * Called when capability of softap changes.
- *
- * @param softApCapability is the softap capability. {@link SoftApCapability}
- */
- default void onCapabilityChanged(@NonNull SoftApCapability softApCapability) {
- // Do nothing: can be updated to add SoftApCapability details (e.g. meximum supported
- // client number) to the UI.
- }
-
- /**
- * Called when client trying to connect but device blocked the client with specific reason.
- *
- * Can be used to ask user to update client to allowed list or blocked list
- * when reason is {@link SAP_CLIENT_BLOCK_REASON_CODE_BLOCKED_BY_USER}, or
- * indicate the block due to maximum supported client number limitation when reason is
- * {@link SAP_CLIENT_BLOCK_REASON_CODE_NO_MORE_STAS}.
- *
- * @param client the currently blocked client.
- * @param blockedReason one of blocked reason from {@link SapClientBlockedReason}
- */
- default void onBlockedClientConnecting(@NonNull WifiClient client,
- @SapClientBlockedReason int blockedReason) {
- // Do nothing: can be used to ask user to update client to allowed list or blocked list.
- }
- }
-
- /**
- * Callback proxy for SoftApCallback objects.
- *
- * @hide
- */
- private class SoftApCallbackProxy extends ISoftApCallback.Stub {
- private final Executor mExecutor;
- private final SoftApCallback mCallback;
- private Map> mCurrentClients = new HashMap<>();
- private Map mCurrentInfos = new HashMap<>();
-
- private List getConnectedClientList(Map> clientsMap) {
- List connectedClientList = new ArrayList<>();
- for (List it : clientsMap.values()) {
- connectedClientList.addAll(it);
- }
- return connectedClientList;
- }
-
- SoftApCallbackProxy(Executor executor, SoftApCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void onStateChanged(int state, int failureReason) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "SoftApCallbackProxy: onStateChanged: state=" + state
- + ", failureReason=" + failureReason);
- }
-
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onStateChanged(state, failureReason);
- });
- }
-
- @Override
- public void onConnectedClientsOrInfoChanged(Map infos,
- Map> clients, boolean isBridged, boolean isRegistration) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "SoftApCallbackProxy: onConnectedClientsOrInfoChanged: clients: "
- + clients + ", infos: " + infos + ", isBridged is " + isBridged
- + ", isRegistration is " + isRegistration);
- }
-
- List changedInfoList = new ArrayList<>(infos.values());
- Map> changedInfoClients = new HashMap<>();
- boolean isInfoChanged = infos.size() != mCurrentInfos.size();
- for (SoftApInfo info : mCurrentInfos.values()) {
- String changedInstance = info.getApInstanceIdentifier();
- if (!changedInfoList.contains(info)) {
- isInfoChanged = true;
- if (mCurrentClients.getOrDefault(changedInstance,
- Collections.emptyList()).size() > 0) {
- Log.d(TAG, "SoftApCallbackProxy: info changed on client connected"
- + " instance(Shut Down case)");
- //Here should notify client changed on old info
- changedInfoClients.put(info, Collections.emptyList());
- }
- } else {
- // info doesn't change, check client list
- List changedClientList = clients.getOrDefault(
- changedInstance, Collections.emptyList());
- if (changedClientList.size()
- != mCurrentClients
- .getOrDefault(changedInstance, Collections.emptyList()).size()) {
- // Here should notify client changed on new info(same as old info)
- changedInfoClients.put(info, changedClientList);
- Log.d(TAG, "SoftApCallbackProxy: client changed on " + info
- + " list: " + changedClientList);
- }
- }
- }
-
- if (!isInfoChanged && changedInfoClients.isEmpty()
- && !isRegistration) {
- Log.v(TAG, "SoftApCallbackProxy: No changed & Not Registration,"
- + " don't need to notify the client");
- return;
- }
- mCurrentClients = clients;
- mCurrentInfos = infos;
- Binder.clearCallingIdentity();
- // Notify the clients changed first for old info shutdown case
- for (SoftApInfo changedInfo : changedInfoClients.keySet()) {
- Log.v(TAG, "send onConnectedClientsChanged, changedInfo is " + changedInfo);
- mExecutor.execute(() -> {
- mCallback.onConnectedClientsChanged(
- changedInfo, changedInfoClients.get(changedInfo));
- });
- }
-
- if (isInfoChanged || isRegistration) {
- if (!isBridged) {
- SoftApInfo newInfo = changedInfoList.isEmpty()
- ? new SoftApInfo() : changedInfoList.get(0);
- Log.v(TAG, "SoftApCallbackProxy: send InfoChanged, newInfo: " + newInfo);
- mExecutor.execute(() -> {
- mCallback.onInfoChanged(newInfo);
- });
- }
- Log.v(TAG, "SoftApCallbackProxy: send InfoChanged, changedInfoList: "
- + changedInfoList);
- mExecutor.execute(() -> {
- mCallback.onInfoChanged(changedInfoList);
- });
- }
-
- if (isRegistration || !changedInfoClients.isEmpty()) {
- Log.v(TAG, "SoftApCallbackProxy: send onConnectedClientsChanged(clients): "
- + getConnectedClientList(clients));
- mExecutor.execute(() -> {
- mCallback.onConnectedClientsChanged(getConnectedClientList(clients));
- });
- }
- }
-
- @Override
- public void onCapabilityChanged(SoftApCapability capability) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "SoftApCallbackProxy: onCapabilityChanged: SoftApCapability="
- + capability);
- }
-
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onCapabilityChanged(capability);
- });
- }
-
- @Override
- public void onBlockedClientConnecting(@NonNull WifiClient client, int blockedReason) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "SoftApCallbackProxy: onBlockedClientConnecting: client=" + client
- + " with reason = " + blockedReason);
- }
-
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onBlockedClientConnecting(client, blockedReason);
- });
- }
- }
-
- /**
- * Registers a callback for Soft AP. See {@link SoftApCallback}. Caller will receive the
- * following callbacks on registration:
- *
- * - {@link SoftApCallback#onStateChanged(int, int)}
- * - {@link SoftApCallback#onConnectedClientsChanged(List)}
- * - {@link SoftApCallback#onInfoChanged(SoftApInfo)}
- * - {@link SoftApCallback#onInfoChanged(List)}
- * - {@link SoftApCallback#onCapabilityChanged(SoftApCapability)}
- *
- *
- * Use {@link SoftApCallback#onConnectedClientsChanged(List)} to know if there are
- * any clients connected to any of the bridged instances of this AP (if bridged AP is enabled).
- * Use {@link SoftApCallback#onConnectedClientsChanged(SoftApInfo, List)} to know
- * if there are any clients connected to a specific bridged instance of this AP
- * (if bridged AP is enabled).
- *
- * Note: Caller will receive the callback
- * {@link SoftApCallback#onConnectedClientsChangedWithApInfo(SoftApInfo, List)}
- * on registration when there are clients connected to AP.
- *
- * These will be dispatched on registration to provide the caller with the current state
- * (and are not an indication of any current change). Note that receiving an immediate
- * WIFI_AP_STATE_FAILED value for soft AP state indicates that the latest attempt to start
- * soft AP has failed. Caller can unregister a previously registered callback using
- * {@link #unregisterSoftApCallback}
- *
- * Applications should have the
- * {@link android.Manifest.permission#NETWORK_SETTINGS NETWORK_SETTINGS} permission. Callers
- * without the permission will trigger a {@link java.lang.SecurityException}.
- *
- *
- * @param executor The Executor on whose thread to execute the callbacks of the {@code callback}
- * object.
- * @param callback Callback for soft AP events
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void registerSoftApCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull SoftApCallback callback) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "registerSoftApCallback: callback=" + callback + ", executor=" + executor);
-
- Binder binder = new Binder();
- try {
- mService.registerSoftApCallback(
- binder, new SoftApCallbackProxy(executor, callback), callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow callers to unregister a previously registered callback. After calling this method,
- * applications will no longer receive soft AP events.
- *
- * @param callback Callback to unregister for soft AP events
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void unregisterSoftApCallback(@NonNull SoftApCallback callback) {
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "unregisterSoftApCallback: callback=" + callback);
-
- try {
- mService.unregisterSoftApCallback(callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * LocalOnlyHotspotReservation that contains the {@link SoftApConfiguration} for the active
- * LocalOnlyHotspot request.
- *
- * Applications requesting LocalOnlyHotspot for sharing will receive an instance of the
- * LocalOnlyHotspotReservation in the
- * {@link LocalOnlyHotspotCallback#onStarted(LocalOnlyHotspotReservation)} call. This
- * reservation contains the relevant {@link SoftApConfiguration}.
- * When an application is done with the LocalOnlyHotspot, they should call {@link
- * LocalOnlyHotspotReservation#close()}. Once this happens, the application will not receive
- * any further callbacks. If the LocalOnlyHotspot is stopped due to a
- * user triggered mode change, applications will be notified via the {@link
- * LocalOnlyHotspotCallback#onStopped()} callback.
- */
- public class LocalOnlyHotspotReservation implements AutoCloseable {
-
- private final CloseGuard mCloseGuard = new CloseGuard();
- private final SoftApConfiguration mSoftApConfig;
- private final WifiConfiguration mWifiConfig;
- private boolean mClosed = false;
-
- /** @hide */
- @VisibleForTesting
- public LocalOnlyHotspotReservation(SoftApConfiguration config) {
- mSoftApConfig = config;
- mWifiConfig = config.toWifiConfiguration();
- mCloseGuard.open("close");
- }
-
- /**
- * Returns the {@link WifiConfiguration} of the current Local Only Hotspot (LOHS).
- * May be null if hotspot enabled and security type is not
- * {@code WifiConfiguration.KeyMgmt.None} or {@code WifiConfiguration.KeyMgmt.WPA2_PSK}.
- *
- * @deprecated Use {@code WifiManager#getSoftApConfiguration()} to get the
- * LOHS configuration.
- */
- @Deprecated
- @Nullable
- public WifiConfiguration getWifiConfiguration() {
- return mWifiConfig;
- }
-
- /**
- * Returns the {@link SoftApConfiguration} of the current Local Only Hotspot (LOHS).
- */
- @NonNull
- public SoftApConfiguration getSoftApConfiguration() {
- return mSoftApConfig;
- }
-
- @Override
- public void close() {
- try {
- synchronized (mLock) {
- if (!mClosed) {
- mClosed = true;
- stopLocalOnlyHotspot();
- mCloseGuard.close();
- }
- }
- } catch (Exception e) {
- Log.e(TAG, "Failed to stop Local Only Hotspot.");
- } finally {
- Reference.reachabilityFence(this);
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- try {
- if (mCloseGuard != null) {
- mCloseGuard.warnIfOpen();
- }
- close();
- } finally {
- super.finalize();
- }
- }
- }
-
- /**
- * Callback class for applications to receive updates about the LocalOnlyHotspot status.
- */
- public static class LocalOnlyHotspotCallback {
- /** @hide */
- public static final int REQUEST_REGISTERED = 0;
-
- public static final int ERROR_NO_CHANNEL = 1;
- public static final int ERROR_GENERIC = 2;
- public static final int ERROR_INCOMPATIBLE_MODE = 3;
- public static final int ERROR_TETHERING_DISALLOWED = 4;
-
- /** LocalOnlyHotspot start succeeded. */
- public void onStarted(LocalOnlyHotspotReservation reservation) {};
-
- /**
- * LocalOnlyHotspot stopped.
- *
- * The LocalOnlyHotspot can be disabled at any time by the user. When this happens,
- * applications will be notified that it was stopped. This will not be invoked when an
- * application calls {@link LocalOnlyHotspotReservation#close()}.
- */
- public void onStopped() {};
-
- /**
- * LocalOnlyHotspot failed to start.
- *
- * Applications can attempt to call
- * {@link WifiManager#startLocalOnlyHotspot(LocalOnlyHotspotCallback, Handler)} again at
- * a later time.
- *
- * @param reason The reason for failure could be one of: {@link
- * #ERROR_TETHERING_DISALLOWED}, {@link #ERROR_INCOMPATIBLE_MODE},
- * {@link #ERROR_NO_CHANNEL}, or {@link #ERROR_GENERIC}.
- */
- public void onFailed(int reason) { };
- }
-
- /**
- * Callback proxy for LocalOnlyHotspotCallback objects.
- */
- private static class LocalOnlyHotspotCallbackProxy extends ILocalOnlyHotspotCallback.Stub {
- private final WeakReference mWifiManager;
- private final Executor mExecutor;
- private final LocalOnlyHotspotCallback mCallback;
-
- /**
- * Constructs a {@link LocalOnlyHotspotCallbackProxy} using the specified executor. All
- * callbacks will run using the given executor.
- *
- * @param manager WifiManager
- * @param executor Executor for delivering callbacks.
- * @param callback LocalOnlyHotspotCallback to notify the calling application, or null.
- */
- LocalOnlyHotspotCallbackProxy(
- @NonNull WifiManager manager,
- @NonNull Executor executor,
- @Nullable LocalOnlyHotspotCallback callback) {
- mWifiManager = new WeakReference<>(manager);
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void onHotspotStarted(SoftApConfiguration config) {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- if (config == null) {
- Log.e(TAG, "LocalOnlyHotspotCallbackProxy: config cannot be null.");
- onHotspotFailed(LocalOnlyHotspotCallback.ERROR_GENERIC);
- return;
- }
- final LocalOnlyHotspotReservation reservation =
- manager.new LocalOnlyHotspotReservation(config);
- if (mCallback == null) return;
- mExecutor.execute(() -> mCallback.onStarted(reservation));
- }
-
- @Override
- public void onHotspotStopped() {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- Log.w(TAG, "LocalOnlyHotspotCallbackProxy: hotspot stopped");
- if (mCallback == null) return;
- mExecutor.execute(() -> mCallback.onStopped());
- }
-
- @Override
- public void onHotspotFailed(int reason) {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- Log.w(TAG, "LocalOnlyHotspotCallbackProxy: failed to start. reason: "
- + reason);
- if (mCallback == null) return;
- mExecutor.execute(() -> mCallback.onFailed(reason));
- }
- }
-
- /**
- * LocalOnlyHotspotSubscription that is an AutoCloseable object for tracking applications
- * watching for LocalOnlyHotspot changes.
- *
- * @hide
- */
- public class LocalOnlyHotspotSubscription implements AutoCloseable {
- private final CloseGuard mCloseGuard = new CloseGuard();
-
- /** @hide */
- @VisibleForTesting
- public LocalOnlyHotspotSubscription() {
- mCloseGuard.open("close");
- }
-
- @Override
- public void close() {
- try {
- unregisterLocalOnlyHotspotObserver();
- mCloseGuard.close();
- } catch (Exception e) {
- Log.e(TAG, "Failed to unregister LocalOnlyHotspotObserver.");
- } finally {
- Reference.reachabilityFence(this);
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- try {
- if (mCloseGuard != null) {
- mCloseGuard.warnIfOpen();
- }
- close();
- } finally {
- super.finalize();
- }
- }
- }
-
- /**
- * Class to notify calling applications that watch for changes in LocalOnlyHotspot of updates.
- *
- * @hide
- */
- public static class LocalOnlyHotspotObserver {
- /**
- * Confirm registration for LocalOnlyHotspotChanges by returning a
- * LocalOnlyHotspotSubscription.
- */
- public void onRegistered(LocalOnlyHotspotSubscription subscription) {};
-
- /**
- * LocalOnlyHotspot started with the supplied config.
- */
- public void onStarted(SoftApConfiguration config) {};
-
- /**
- * LocalOnlyHotspot stopped.
- */
- public void onStopped() {};
- }
-
- /**
- * Callback proxy for LocalOnlyHotspotObserver objects.
- */
- private static class LocalOnlyHotspotObserverProxy extends ILocalOnlyHotspotCallback.Stub {
- private final WeakReference mWifiManager;
- private final Executor mExecutor;
- private final LocalOnlyHotspotObserver mObserver;
-
- /**
- * Constructs a {@link LocalOnlyHotspotObserverProxy} using the specified looper.
- * All callbacks will be delivered on the thread of the specified looper.
- *
- * @param manager WifiManager
- * @param executor Executor for delivering callbacks
- * @param observer LocalOnlyHotspotObserver to notify the calling application.
- */
- LocalOnlyHotspotObserverProxy(WifiManager manager, Executor executor,
- final LocalOnlyHotspotObserver observer) {
- mWifiManager = new WeakReference<>(manager);
- mExecutor = executor;
- mObserver = observer;
- }
-
- public void registered() throws RemoteException {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- mExecutor.execute(() ->
- mObserver.onRegistered(manager.new LocalOnlyHotspotSubscription()));
- }
-
- @Override
- public void onHotspotStarted(SoftApConfiguration config) {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- if (config == null) {
- Log.e(TAG, "LocalOnlyHotspotObserverProxy: config cannot be null.");
- return;
- }
- mExecutor.execute(() -> mObserver.onStarted(config));
- }
-
- @Override
- public void onHotspotStopped() {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- mExecutor.execute(() -> mObserver.onStopped());
- }
-
- @Override
- public void onHotspotFailed(int reason) {
- // do nothing
- }
- }
-
- /**
- * Callback proxy for ActionListener objects.
- */
- private class ActionListenerProxy extends IActionListener.Stub {
- private final String mActionTag;
- private final Handler mHandler;
- private final ActionListener mCallback;
-
- ActionListenerProxy(String actionTag, Looper looper, ActionListener callback) {
- mActionTag = actionTag;
- mHandler = new Handler(looper);
- mCallback = callback;
- }
-
- @Override
- public void onSuccess() {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "ActionListenerProxy:" + mActionTag + ": onSuccess");
- }
- mHandler.post(() -> {
- mCallback.onSuccess();
- });
- }
-
- @Override
- public void onFailure(@ActionListenerFailureReason int reason) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "ActionListenerProxy:" + mActionTag + ": onFailure=" + reason);
- }
- mHandler.post(() -> {
- mCallback.onFailure(reason);
- });
- }
- }
-
- private void connectInternal(@Nullable WifiConfiguration config, int networkId,
- @Nullable ActionListener listener) {
- ActionListenerProxy listenerProxy = null;
- if (listener != null) {
- listenerProxy = new ActionListenerProxy("connect", mLooper, listener);
- }
- try {
- mService.connect(config, networkId, listenerProxy);
- } catch (RemoteException e) {
- if (listenerProxy != null) listenerProxy.onFailure(ERROR);
- } catch (SecurityException e) {
- if (listenerProxy != null) listenerProxy.onFailure(NOT_AUTHORIZED);
- }
- }
-
- /**
- * Connect to a network with the given configuration. The network also
- * gets added to the list of configured networks for the foreground user.
- *
- * For a new network, this function is used instead of a
- * sequence of addNetwork(), enableNetwork(), and reconnect()
- *
- * @param config the set of variables that describe the configuration,
- * contained in a {@link WifiConfiguration} object.
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be
- * initialized again
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD,
- android.Manifest.permission.NETWORK_STACK
- })
- public void connect(@NonNull WifiConfiguration config, @Nullable ActionListener listener) {
- if (config == null) throw new IllegalArgumentException("config cannot be null");
- connectInternal(config, WifiConfiguration.INVALID_NETWORK_ID, listener);
- }
-
- /**
- * Connect to a network with the given networkId.
- *
- * This function is used instead of a enableNetwork() and reconnect()
- *
- * This API will cause reconnect if the credentials of the current active
- * connection has been changed.
- * This API will cause reconnect if the current active connection is marked metered.
- *
- * @param networkId the ID of the network as returned by {@link #addNetwork} or {@link
- * getConfiguredNetworks}.
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be
- * initialized again
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD,
- android.Manifest.permission.NETWORK_STACK
- })
- public void connect(int networkId, @Nullable ActionListener listener) {
- if (networkId < 0) throw new IllegalArgumentException("Network id cannot be negative");
- connectInternal(null, networkId, listener);
- }
-
- /**
- * Temporarily disable autojoin for all currently visible and provisioned (saved, suggested)
- * wifi networks except merged carrier networks from the provided subscription ID.
- *
- * Disabled networks will get automatically re-enabled when they are out of range for a period
- * of time, or after the maximum disable duration specified in the framework.
- *
- * Calling {@link #stopTemporarilyDisablingAllNonCarrierMergedWifi()} will immediately re-enable
- * autojoin on all disabled networks.
- *
- * @param subscriptionId the subscription ID of the carrier whose merged wifi networks won't be
- * disabled {@link android.telephony.SubscriptionInfo#getSubscriptionId()}
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void startTemporarilyDisablingAllNonCarrierMergedWifi(int subscriptionId) {
- try {
- mService.startTemporarilyDisablingAllNonCarrierMergedWifi(subscriptionId);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Re-enable autojoin for all non carrier merged wifi networks temporarily disconnected by
- * {@link #startTemporarilyDisablingAllNonCarrierMergedWifi(int)}.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void stopTemporarilyDisablingAllNonCarrierMergedWifi() {
- try {
- mService.stopTemporarilyDisablingAllNonCarrierMergedWifi();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Save the given network to the list of configured networks for the
- * foreground user. If the network already exists, the configuration
- * is updated. Any new network is enabled by default.
- *
- * For a new network, this function is used instead of a
- * sequence of addNetwork() and enableNetwork().
- *
- * For an existing network, it accomplishes the task of updateNetwork()
- *
- * This API will cause reconnect if the credentials of the current active
- * connection has been changed.
- * This API will cause disconnect if the current active connection is marked metered.
- *
- * @param config the set of variables that describe the configuration,
- * contained in a {@link WifiConfiguration} object.
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be
- * initialized again
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD,
- android.Manifest.permission.NETWORK_STACK
- })
- public void save(@NonNull WifiConfiguration config, @Nullable ActionListener listener) {
- if (config == null) throw new IllegalArgumentException("config cannot be null");
- ActionListenerProxy listenerProxy = null;
- if (listener != null) {
- listenerProxy = new ActionListenerProxy("save", mLooper, listener);
- }
- try {
- mService.save(config, listenerProxy);
- } catch (RemoteException e) {
- if (listenerProxy != null) listenerProxy.onFailure(ERROR);
- } catch (SecurityException e) {
- if (listenerProxy != null) listenerProxy.onFailure(NOT_AUTHORIZED);
- }
- }
-
- /**
- * Delete the network from the list of configured networks for the
- * foreground user.
- *
- * This function is used instead of a sequence of removeNetwork()
- *
- * @param config the set of variables that describe the configuration,
- * contained in a {@link WifiConfiguration} object.
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be
- * initialized again
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD,
- android.Manifest.permission.NETWORK_STACK
- })
- public void forget(int netId, @Nullable ActionListener listener) {
- if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
- ActionListenerProxy listenerProxy = null;
- if (listener != null) {
- listenerProxy = new ActionListenerProxy("forget", mLooper, listener);
- }
- try {
- mService.forget(netId, listenerProxy);
- } catch (RemoteException e) {
- if (listenerProxy != null) listenerProxy.onFailure(ERROR);
- } catch (SecurityException e) {
- if (listenerProxy != null) listenerProxy.onFailure(NOT_AUTHORIZED);
- }
- }
-
- /**
- * Disable network
- *
- * @param netId is the network Id
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be
- * initialized again
- * @deprecated This API is deprecated. Use {@link #disableNetwork(int)} instead.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD,
- android.Manifest.permission.NETWORK_STACK
- })
- @Deprecated
- public void disable(int netId, @Nullable ActionListener listener) {
- if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
- // Simple wrapper which forwards the call to disableNetwork. This is a temporary
- // implementation until we can remove this API completely.
- boolean status = disableNetwork(netId);
- if (listener != null) {
- if (status) {
- listener.onSuccess();
- } else {
- listener.onFailure(ERROR);
- }
- }
- }
-
- /**
- * Enable/disable auto-join globally.
- *
- * @param allowAutojoin true to allow auto-join, false to disallow auto-join
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void allowAutojoinGlobal(boolean allowAutojoin) {
- try {
- mService.allowAutojoinGlobal(allowAutojoin);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
-
- /**
- * Sets the user choice for allowing auto-join to a network.
- * The updated choice will be made available through the updated config supplied by the
- * CONFIGURED_NETWORKS_CHANGED broadcast.
- *
- * @param netId the id of the network to allow/disallow auto-join for.
- * @param allowAutojoin true to allow auto-join, false to disallow auto-join
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void allowAutojoin(int netId, boolean allowAutojoin) {
- try {
- mService.allowAutojoin(netId, allowAutojoin);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Configure auto-join settings for a Passpoint profile.
- *
- * @param fqdn the FQDN (fully qualified domain name) of the passpoint profile.
- * @param allowAutojoin true to enable auto-join, false to disable auto-join.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void allowAutojoinPasspoint(@NonNull String fqdn, boolean allowAutojoin) {
- try {
- mService.allowAutojoinPasspoint(fqdn, allowAutojoin);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Configure MAC randomization setting for a Passpoint profile.
- * MAC randomization is enabled by default.
- *
- * @param fqdn the FQDN (fully qualified domain name) of the passpoint profile.
- * @param enable true to enable MAC randomization, false to disable MAC randomization.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setMacRandomizationSettingPasspointEnabled(@NonNull String fqdn, boolean enable) {
- try {
- mService.setMacRandomizationSettingPasspointEnabled(fqdn, enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Sets the user's choice of metered override for a Passpoint profile.
- *
- * @param fqdn the FQDN (fully qualified domain name) of the passpoint profile.
- * @param meteredOverride One of three values: {@link WifiConfiguration#METERED_OVERRIDE_NONE},
- * {@link WifiConfiguration#METERED_OVERRIDE_METERED},
- * {@link WifiConfiguration#METERED_OVERRIDE_NOT_METERED}
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setPasspointMeteredOverride(@NonNull String fqdn,
- @WifiConfiguration.MeteredOverride int meteredOverride) {
- try {
- mService.setPasspointMeteredOverride(fqdn, meteredOverride);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Temporarily disable a network. Should always trigger with user disconnect network.
- *
- * @param network Input can be SSID or FQDN. And caller must ensure that the SSID passed thru
- * this API matched the WifiConfiguration.SSID rules, and thus be surrounded by
- * quotes.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_STACK
- })
- public void disableEphemeralNetwork(@NonNull String network) {
- if (TextUtils.isEmpty(network)) {
- throw new IllegalArgumentException("SSID cannot be null or empty!");
- }
- try {
- mService.disableEphemeralNetwork(network, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * WPS suport has been deprecated from Client mode and this method will immediately trigger
- * {@link WpsCallback#onFailed(int)} with a generic error.
- *
- * @param config WPS configuration (does not support {@link WpsInfo#LABEL})
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be initialized again
- * @deprecated This API is deprecated
- */
- public void startWps(WpsInfo config, WpsCallback listener) {
- if (listener != null ) {
- listener.onFailed(ERROR);
- }
- }
-
- /**
- * WPS support has been deprecated from Client mode and this method will immediately trigger
- * {@link WpsCallback#onFailed(int)} with a generic error.
- *
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be initialized again
- * @deprecated This API is deprecated
- */
- public void cancelWps(WpsCallback listener) {
- if (listener != null) {
- listener.onFailed(ERROR);
- }
- }
-
- /**
- * Allows an application to keep the Wi-Fi radio awake.
- * Normally the Wi-Fi radio may turn off when the user has not used the device in a while.
- * Acquiring a WifiLock will keep the radio on until the lock is released. Multiple
- * applications may hold WifiLocks, and the radio will only be allowed to turn off when no
- * WifiLocks are held in any application.
- *
- * Before using a WifiLock, consider carefully if your application requires Wi-Fi access, or
- * could function over a mobile network, if available. A program that needs to download large
- * files should hold a WifiLock to ensure that the download will complete, but a program whose
- * network usage is occasional or low-bandwidth should not hold a WifiLock to avoid adversely
- * affecting battery life.
- *
- * Note that WifiLocks cannot override the user-level "Wi-Fi Enabled" setting, nor Airplane
- * Mode. They simply keep the radio from turning off when Wi-Fi is already on but the device
- * is idle.
- *
- * Any application using a WifiLock must request the {@code android.permission.WAKE_LOCK}
- * permission in an {@code } element of the application's manifest.
- */
- public class WifiLock {
- private String mTag;
- private final IBinder mBinder;
- private int mRefCount;
- int mLockType;
- private boolean mRefCounted;
- private boolean mHeld;
- private WorkSource mWorkSource;
-
- private WifiLock(int lockType, String tag) {
- mTag = tag;
- mLockType = lockType;
- mBinder = new Binder();
- mRefCount = 0;
- mRefCounted = true;
- mHeld = false;
- }
-
- /**
- * Locks the Wi-Fi radio on until {@link #release} is called.
- *
- * If this WifiLock is reference-counted, each call to {@code acquire} will increment the
- * reference count, and the radio will remain locked as long as the reference count is
- * above zero.
- *
- * If this WifiLock is not reference-counted, the first call to {@code acquire} will lock
- * the radio, but subsequent calls will be ignored. Only one call to {@link #release}
- * will be required, regardless of the number of times that {@code acquire} is called.
- */
- public void acquire() {
- synchronized (mBinder) {
- if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) {
- try {
- mService.acquireWifiLock(mBinder, mLockType, mTag, mWorkSource);
- synchronized (WifiManager.this) {
- if (mActiveLockCount >= MAX_ACTIVE_LOCKS) {
- mService.releaseWifiLock(mBinder);
- throw new UnsupportedOperationException(
- "Exceeded maximum number of wifi locks");
- }
- mActiveLockCount++;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- mHeld = true;
- }
- }
- }
-
- /**
- * Unlocks the Wi-Fi radio, allowing it to turn off when the device is idle.
- *
- * If this WifiLock is reference-counted, each call to {@code release} will decrement the
- * reference count, and the radio will be unlocked only when the reference count reaches
- * zero. If the reference count goes below zero (that is, if {@code release} is called
- * a greater number of times than {@link #acquire}), an exception is thrown.
- *
- * If this WifiLock is not reference-counted, the first call to {@code release} (after
- * the radio was locked using {@link #acquire}) will unlock the radio, and subsequent
- * calls will be ignored.
- */
- public void release() {
- synchronized (mBinder) {
- if (mRefCounted ? (--mRefCount == 0) : (mHeld)) {
- try {
- mService.releaseWifiLock(mBinder);
- synchronized (WifiManager.this) {
- mActiveLockCount--;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- mHeld = false;
- }
- if (mRefCount < 0) {
- throw new RuntimeException("WifiLock under-locked " + mTag);
- }
- }
- }
-
- /**
- * Controls whether this is a reference-counted or non-reference-counted WifiLock.
- *
- * Reference-counted WifiLocks keep track of the number of calls to {@link #acquire} and
- * {@link #release}, and only allow the radio to sleep when every call to {@link #acquire}
- * has been balanced with a call to {@link #release}. Non-reference-counted WifiLocks
- * lock the radio whenever {@link #acquire} is called and it is unlocked, and unlock the
- * radio whenever {@link #release} is called and it is locked.
- *
- * @param refCounted true if this WifiLock should keep a reference count
- */
- public void setReferenceCounted(boolean refCounted) {
- mRefCounted = refCounted;
- }
-
- /**
- * Checks whether this WifiLock is currently held.
- *
- * @return true if this WifiLock is held, false otherwise
- */
- public boolean isHeld() {
- synchronized (mBinder) {
- return mHeld;
- }
- }
-
- public void setWorkSource(WorkSource ws) {
- synchronized (mBinder) {
- if (ws != null && ws.isEmpty()) {
- ws = null;
- }
- boolean changed = true;
- if (ws == null) {
- mWorkSource = null;
- } else {
- ws = ws.withoutNames();
- if (mWorkSource == null) {
- changed = mWorkSource != null;
- mWorkSource = new WorkSource(ws);
- } else {
- changed = !mWorkSource.equals(ws);
- if (changed) {
- mWorkSource.set(ws);
- }
- }
- }
- if (changed && mHeld) {
- try {
- mService.updateWifiLockWorkSource(mBinder, mWorkSource);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
- }
-
- public String toString() {
- String s1, s2, s3;
- synchronized (mBinder) {
- s1 = Integer.toHexString(System.identityHashCode(this));
- s2 = mHeld ? "held; " : "";
- if (mRefCounted) {
- s3 = "refcounted: refcount = " + mRefCount;
- } else {
- s3 = "not refcounted";
- }
- return "WifiLock{ " + s1 + "; " + s2 + s3 + " }";
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- synchronized (mBinder) {
- if (mHeld) {
- try {
- mService.releaseWifiLock(mBinder);
- synchronized (WifiManager.this) {
- mActiveLockCount--;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
- }
- }
-
- /**
- * Creates a new WifiLock.
- *
- * @param lockType the type of lock to create. See {@link #WIFI_MODE_FULL_HIGH_PERF}
- * and {@link #WIFI_MODE_FULL_LOW_LATENCY} for descriptions of the types of Wi-Fi locks.
- * @param tag a tag for the WifiLock to identify it in debugging messages. This string is
- * never shown to the user under normal conditions, but should be descriptive
- * enough to identify your application and the specific WifiLock within it, if it
- * holds multiple WifiLocks.
- *
- * @return a new, unacquired WifiLock with the given tag.
- *
- * @see WifiLock
- */
- public WifiLock createWifiLock(int lockType, String tag) {
- return new WifiLock(lockType, tag);
- }
-
- /**
- * Creates a new WifiLock.
- *
- * @param tag a tag for the WifiLock to identify it in debugging messages. This string is
- * never shown to the user under normal conditions, but should be descriptive
- * enough to identify your application and the specific WifiLock within it, if it
- * holds multiple WifiLocks.
- *
- * @return a new, unacquired WifiLock with the given tag.
- *
- * @see WifiLock
- *
- * @deprecated This API is non-functional.
- */
- @Deprecated
- public WifiLock createWifiLock(String tag) {
- return new WifiLock(WIFI_MODE_FULL, tag);
- }
-
- /**
- * Create a new MulticastLock
- *
- * @param tag a tag for the MulticastLock to identify it in debugging
- * messages. This string is never shown to the user under
- * normal conditions, but should be descriptive enough to
- * identify your application and the specific MulticastLock
- * within it, if it holds multiple MulticastLocks.
- *
- * @return a new, unacquired MulticastLock with the given tag.
- *
- * @see MulticastLock
- */
- public MulticastLock createMulticastLock(String tag) {
- return new MulticastLock(tag);
- }
-
- /**
- * Allows an application to receive Wifi Multicast packets.
- * Normally the Wifi stack filters out packets not explicitly
- * addressed to this device. Acquring a MulticastLock will
- * cause the stack to receive packets addressed to multicast
- * addresses. Processing these extra packets can cause a noticeable
- * battery drain and should be disabled when not needed.
- */
- public class MulticastLock {
- private String mTag;
- private final IBinder mBinder;
- private int mRefCount;
- private boolean mRefCounted;
- private boolean mHeld;
-
- private MulticastLock(String tag) {
- mTag = tag;
- mBinder = new Binder();
- mRefCount = 0;
- mRefCounted = true;
- mHeld = false;
- }
-
- /**
- * Locks Wifi Multicast on until {@link #release} is called.
- *
- * If this MulticastLock is reference-counted each call to
- * {@code acquire} will increment the reference count, and the
- * wifi interface will receive multicast packets as long as the
- * reference count is above zero.
- *
- * If this MulticastLock is not reference-counted, the first call to
- * {@code acquire} will turn on the multicast packets, but subsequent
- * calls will be ignored. Only one call to {@link #release} will
- * be required, regardless of the number of times that {@code acquire}
- * is called.
- *
- * Note that other applications may also lock Wifi Multicast on.
- * Only they can relinquish their lock.
- *
- * Also note that applications cannot leave Multicast locked on.
- * When an app exits or crashes, any Multicast locks will be released.
- */
- public void acquire() {
- synchronized (mBinder) {
- if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) {
- try {
- mService.acquireMulticastLock(mBinder, mTag);
- synchronized (WifiManager.this) {
- if (mActiveLockCount >= MAX_ACTIVE_LOCKS) {
- mService.releaseMulticastLock(mTag);
- throw new UnsupportedOperationException(
- "Exceeded maximum number of wifi locks");
- }
- mActiveLockCount++;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- mHeld = true;
- }
- }
- }
-
- /**
- * Unlocks Wifi Multicast, restoring the filter of packets
- * not addressed specifically to this device and saving power.
- *
- * If this MulticastLock is reference-counted, each call to
- * {@code release} will decrement the reference count, and the
- * multicast packets will only stop being received when the reference
- * count reaches zero. If the reference count goes below zero (that
- * is, if {@code release} is called a greater number of times than
- * {@link #acquire}), an exception is thrown.
- *
- * If this MulticastLock is not reference-counted, the first call to
- * {@code release} (after the radio was multicast locked using
- * {@link #acquire}) will unlock the multicast, and subsequent calls
- * will be ignored.
- *
- * Note that if any other Wifi Multicast Locks are still outstanding
- * this {@code release} call will not have an immediate effect. Only
- * when all applications have released all their Multicast Locks will
- * the Multicast filter be turned back on.
- *
- * Also note that when an app exits or crashes all of its Multicast
- * Locks will be automatically released.
- */
- public void release() {
- synchronized (mBinder) {
- if (mRefCounted ? (--mRefCount == 0) : (mHeld)) {
- try {
- mService.releaseMulticastLock(mTag);
- synchronized (WifiManager.this) {
- mActiveLockCount--;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- mHeld = false;
- }
- if (mRefCount < 0) {
- throw new RuntimeException("MulticastLock under-locked "
- + mTag);
- }
- }
- }
-
- /**
- * Controls whether this is a reference-counted or non-reference-
- * counted MulticastLock.
- *
- * Reference-counted MulticastLocks keep track of the number of calls
- * to {@link #acquire} and {@link #release}, and only stop the
- * reception of multicast packets when every call to {@link #acquire}
- * has been balanced with a call to {@link #release}. Non-reference-
- * counted MulticastLocks allow the reception of multicast packets
- * whenever {@link #acquire} is called and stop accepting multicast
- * packets whenever {@link #release} is called.
- *
- * @param refCounted true if this MulticastLock should keep a reference
- * count
- */
- public void setReferenceCounted(boolean refCounted) {
- mRefCounted = refCounted;
- }
-
- /**
- * Checks whether this MulticastLock is currently held.
- *
- * @return true if this MulticastLock is held, false otherwise
- */
- public boolean isHeld() {
- synchronized (mBinder) {
- return mHeld;
- }
- }
-
- public String toString() {
- String s1, s2, s3;
- synchronized (mBinder) {
- s1 = Integer.toHexString(System.identityHashCode(this));
- s2 = mHeld ? "held; " : "";
- if (mRefCounted) {
- s3 = "refcounted: refcount = " + mRefCount;
- } else {
- s3 = "not refcounted";
- }
- return "MulticastLock{ " + s1 + "; " + s2 + s3 + " }";
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- setReferenceCounted(false);
- release();
- }
- }
-
- /**
- * Check multicast filter status.
- *
- * @return true if multicast packets are allowed.
- *
- * @hide pending API council approval
- */
- public boolean isMulticastEnabled() {
- try {
- return mService.isMulticastEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Initialize the multicast filtering to 'on'
- * @hide no intent to publish
- */
- @UnsupportedAppUsage
- public boolean initializeMulticastFiltering() {
- try {
- mService.initializeMulticastFiltering();
- return true;
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Set Wi-Fi verbose logging level from developer settings.
- *
- * @param enable true to enable verbose logging, false to disable.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setVerboseLoggingEnabled(boolean enable) {
- enableVerboseLogging(enable ? 1 : 0);
- }
-
- /** @hide */
- @UnsupportedAppUsage(
- maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "Use {@code #setVerboseLoggingEnabled(boolean)} instead."
- )
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void enableVerboseLogging (int verbose) {
- try {
- mService.enableVerboseLogging(verbose);
- } catch (Exception e) {
- //ignore any failure here
- Log.e(TAG, "enableVerboseLogging " + e.toString());
- }
- }
-
- /**
- * Get the persisted Wi-Fi verbose logging level, set by
- * {@link #setVerboseLoggingEnabled(boolean)}.
- * No permissions are required to call this method.
- *
- * @return true to indicate that verbose logging is enabled, false to indicate that verbose
- * logging is disabled.
- *
- * @hide
- */
- @SystemApi
- public boolean isVerboseLoggingEnabled() {
- return getVerboseLoggingLevel() > 0;
- }
-
- /** @hide */
- // TODO(b/145484145): remove once SUW stops calling this via reflection
- @UnsupportedAppUsage(
- maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "Use {@code #isVerboseLoggingEnabled()} instead."
- )
- public int getVerboseLoggingLevel() {
- try {
- return mService.getVerboseLoggingLevel();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Removes all saved Wi-Fi networks, Passpoint configurations, ephemeral networks, Network
- * Requests, and Network Suggestions.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void factoryReset() {
- try {
- mService.factoryReset(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get {@link Network} object of current wifi network, or null if not connected.
- * @hide
- */
- @Nullable
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- public Network getCurrentNetwork() {
- try {
- return mService.getCurrentNetwork();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Deprecated
- * returns false
- * @hide
- * @deprecated
- */
- public boolean setEnableAutoJoinWhenAssociated(boolean enabled) {
- return false;
- }
-
- /**
- * Deprecated
- * returns false
- * @hide
- * @deprecated
- */
- public boolean getEnableAutoJoinWhenAssociated() {
- return false;
- }
-
- /**
- * Returns a byte stream representing the data that needs to be backed up to save the
- * current Wifi state.
- * This Wifi state can be restored by calling {@link #restoreBackupData(byte[])}.
- * @hide
- */
- @NonNull
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public byte[] retrieveBackupData() {
- try {
- return mService.retrieveBackupData();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Restore state from the backed up data.
- * @param data byte stream in the same format produced by {@link #retrieveBackupData()}
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void restoreBackupData(@NonNull byte[] data) {
- try {
- mService.restoreBackupData(data);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns a byte stream representing the data that needs to be backed up to save the
- * current soft ap config data.
- *
- * This soft ap config can be restored by calling {@link #restoreSoftApBackupData(byte[])}
- * @hide
- */
- @NonNull
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public byte[] retrieveSoftApBackupData() {
- try {
- return mService.retrieveSoftApBackupData();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns soft ap config from the backed up data or null if data is invalid.
- * @param data byte stream in the same format produced by {@link #retrieveSoftApBackupData()}
- *
- * @hide
- */
- @Nullable
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public SoftApConfiguration restoreSoftApBackupData(@NonNull byte[] data) {
- try {
- return mService.restoreSoftApBackupData(data);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Restore state from the older version of back up data.
- * The old backup data was essentially a backup of wpa_supplicant.conf
- * and ipconfig.txt file.
- * @param supplicantData bytes representing wpa_supplicant.conf
- * @param ipConfigData bytes representing ipconfig.txt
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void restoreSupplicantBackupData(
- @NonNull byte[] supplicantData, @NonNull byte[] ipConfigData) {
- try {
- mService.restoreSupplicantBackupData(supplicantData, ipConfigData);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Start subscription provisioning flow
- *
- * @param provider {@link OsuProvider} to provision with
- * @param executor the Executor on which to run the callback.
- * @param callback {@link ProvisioningCallback} for updates regarding provisioning flow
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- public void startSubscriptionProvisioning(@NonNull OsuProvider provider,
- @NonNull @CallbackExecutor Executor executor, @NonNull ProvisioningCallback callback) {
- // Verify arguments
- if (executor == null) {
- throw new IllegalArgumentException("executor must not be null");
- }
- if (callback == null) {
- throw new IllegalArgumentException("callback must not be null");
- }
- try {
- mService.startSubscriptionProvisioning(provider,
- new ProvisioningCallbackProxy(executor, callback));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Helper class to support OSU Provisioning callbacks
- */
- private static class ProvisioningCallbackProxy extends IProvisioningCallback.Stub {
- private final Executor mExecutor;
- private final ProvisioningCallback mCallback;
-
- ProvisioningCallbackProxy(Executor executor, ProvisioningCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void onProvisioningStatus(int status) {
- mExecutor.execute(() -> mCallback.onProvisioningStatus(status));
- }
-
- @Override
- public void onProvisioningFailure(int status) {
- mExecutor.execute(() -> mCallback.onProvisioningFailure(status));
- }
-
- @Override
- public void onProvisioningComplete() {
- mExecutor.execute(() -> mCallback.onProvisioningComplete());
- }
- }
-
- /**
- * Interface for Traffic state callback. Should be extended by applications and set when
- * calling {@link #registerTrafficStateCallback(Executor, WifiManager.TrafficStateCallback)}.
- * @hide
- */
- @SystemApi
- public interface TrafficStateCallback {
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"DATA_ACTIVITY_"}, value = {
- DATA_ACTIVITY_NONE,
- DATA_ACTIVITY_IN,
- DATA_ACTIVITY_OUT,
- DATA_ACTIVITY_INOUT})
- @interface DataActivity {}
-
- // Lowest bit indicates data reception and the second lowest bit indicates data transmitted
- /** No data in or out */
- int DATA_ACTIVITY_NONE = 0x00;
- /** Data in, no data out */
- int DATA_ACTIVITY_IN = 0x01;
- /** Data out, no data in */
- int DATA_ACTIVITY_OUT = 0x02;
- /** Data in and out */
- int DATA_ACTIVITY_INOUT = 0x03;
-
- /**
- * Callback invoked to inform clients about the current traffic state.
- *
- * @param state One of the values: {@link #DATA_ACTIVITY_NONE}, {@link #DATA_ACTIVITY_IN},
- * {@link #DATA_ACTIVITY_OUT} & {@link #DATA_ACTIVITY_INOUT}.
- */
- void onStateChanged(@DataActivity int state);
- }
-
- /**
- * Callback proxy for TrafficStateCallback objects.
- *
- * @hide
- */
- private class TrafficStateCallbackProxy extends ITrafficStateCallback.Stub {
- private final Executor mExecutor;
- private final TrafficStateCallback mCallback;
-
- TrafficStateCallbackProxy(Executor executor, TrafficStateCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void onStateChanged(int state) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "TrafficStateCallbackProxy: onStateChanged state=" + state);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onStateChanged(state);
- });
- }
- }
-
- /**
- * Registers a callback for monitoring traffic state. See {@link TrafficStateCallback}. These
- * callbacks will be invoked periodically by platform to inform clients about the current
- * traffic state. Caller can unregister a previously registered callback using
- * {@link #unregisterTrafficStateCallback(TrafficStateCallback)}
- *
- * Applications should have the
- * {@link android.Manifest.permission#NETWORK_SETTINGS NETWORK_SETTINGS} permission. Callers
- * without the permission will trigger a {@link java.lang.SecurityException}.
- *
- *
- * @param executor The Executor on whose thread to execute the callbacks of the {@code callback}
- * object.
- * @param callback Callback for traffic state events
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void registerTrafficStateCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull TrafficStateCallback callback) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "registerTrafficStateCallback: callback=" + callback + ", executor=" + executor);
-
- Binder binder = new Binder();
- try {
- mService.registerTrafficStateCallback(
- binder, new TrafficStateCallbackProxy(executor, callback), callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow callers to unregister a previously registered callback. After calling this method,
- * applications will no longer receive traffic state notifications.
- *
- * @param callback Callback to unregister for traffic state events
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void unregisterTrafficStateCallback(@NonNull TrafficStateCallback callback) {
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "unregisterTrafficStateCallback: callback=" + callback);
-
- try {
- mService.unregisterTrafficStateCallback(callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Helper method to update the local verbose logging flag based on the verbose logging
- * level from wifi service.
- */
- private void updateVerboseLoggingEnabledFromService() {
- mVerboseLoggingEnabled = isVerboseLoggingEnabled();
- }
-
- /**
- * @return true if this device supports WPA3-Personal SAE
- */
- public boolean isWpa3SaeSupported() {
- return isFeatureSupported(WIFI_FEATURE_WPA3_SAE);
- }
-
- /**
- * @return true if this device supports WPA3-Enterprise Suite-B-192
- */
- public boolean isWpa3SuiteBSupported() {
- return isFeatureSupported(WIFI_FEATURE_WPA3_SUITE_B);
- }
-
- /**
- * @return true if this device supports Wi-Fi Enhanced Open (OWE)
- */
- public boolean isEnhancedOpenSupported() {
- return isFeatureSupported(WIFI_FEATURE_OWE);
- }
-
- /**
- * Wi-Fi Easy Connect (DPP) introduces standardized mechanisms to simplify the provisioning and
- * configuration of Wi-Fi devices.
- * For more details, visit https://www.wi-fi.org/ and
- * search for "Easy Connect" or "Device Provisioning Protocol specification".
- *
- * @return true if this device supports Wi-Fi Easy-connect (Device Provisioning Protocol)
- */
- public boolean isEasyConnectSupported() {
- return isFeatureSupported(WIFI_FEATURE_DPP);
- }
-
- /**
- * @return true if this device supports WAPI.
- */
- public boolean isWapiSupported() {
- return isFeatureSupported(WIFI_FEATURE_WAPI);
- }
-
- /**
- * @return true if this device supports WPA3 AP validation.
- */
- public boolean isWpa3ApValidationSupported() {
- return isFeatureSupported(WIFI_FEATURE_SAE_PK);
- }
-
- /**
- * Gets the factory Wi-Fi MAC addresses.
- * @return Array of String representing Wi-Fi MAC addresses sorted lexically or an empty Array
- * if failed.
- * @hide
- */
- @NonNull
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public String[] getFactoryMacAddresses() {
- try {
- return mService.getFactoryMacAddresses();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"DEVICE_MOBILITY_STATE_"}, value = {
- DEVICE_MOBILITY_STATE_UNKNOWN,
- DEVICE_MOBILITY_STATE_HIGH_MVMT,
- DEVICE_MOBILITY_STATE_LOW_MVMT,
- DEVICE_MOBILITY_STATE_STATIONARY})
- public @interface DeviceMobilityState {}
-
- /**
- * Unknown device mobility state
- *
- * @see #setDeviceMobilityState(int)
- *
- * @hide
- */
- @SystemApi
- public static final int DEVICE_MOBILITY_STATE_UNKNOWN = 0;
-
- /**
- * High movement device mobility state.
- * e.g. on a bike, in a motor vehicle
- *
- * @see #setDeviceMobilityState(int)
- *
- * @hide
- */
- @SystemApi
- public static final int DEVICE_MOBILITY_STATE_HIGH_MVMT = 1;
-
- /**
- * Low movement device mobility state.
- * e.g. walking, running
- *
- * @see #setDeviceMobilityState(int)
- *
- * @hide
- */
- @SystemApi
- public static final int DEVICE_MOBILITY_STATE_LOW_MVMT = 2;
-
- /**
- * Stationary device mobility state
- *
- * @see #setDeviceMobilityState(int)
- *
- * @hide
- */
- @SystemApi
- public static final int DEVICE_MOBILITY_STATE_STATIONARY = 3;
-
- /**
- * Updates the device mobility state. Wifi uses this information to adjust the interval between
- * Wifi scans in order to balance power consumption with scan accuracy.
- * The default mobility state when the device boots is {@link #DEVICE_MOBILITY_STATE_UNKNOWN}.
- * This API should be called whenever there is a change in the mobility state.
- * @param state the updated device mobility state
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_SET_DEVICE_MOBILITY_STATE)
- public void setDeviceMobilityState(@DeviceMobilityState int state) {
- try {
- mService.setDeviceMobilityState(state);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /* Easy Connect - AKA Device Provisioning Protocol (DPP) */
-
- /**
- * Easy Connect Network role: Station.
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_NETWORK_ROLE_STA = 0;
-
- /**
- * Easy Connect Network role: Access Point.
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_NETWORK_ROLE_AP = 1;
-
- /** @hide */
- @IntDef(prefix = {"EASY_CONNECT_NETWORK_ROLE_"}, value = {
- EASY_CONNECT_NETWORK_ROLE_STA,
- EASY_CONNECT_NETWORK_ROLE_AP,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface EasyConnectNetworkRole {
- }
-
- /**
- * Easy Connect Device information maximum allowed length.
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_DEVICE_INFO_MAXIMUM_LENGTH = 40;
-
- /**
- * Easy Connect Cryptography Curve name: prime256v1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1 = 0;
-
- /**
- * Easy Connect Cryptography Curve name: secp384r1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_SECP384R1 = 1;
-
- /**
- * Easy Connect Cryptography Curve name: secp521r1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_SECP521R1 = 2;
-
-
- /**
- * Easy Connect Cryptography Curve name: brainpoolP256r1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP256R1 = 3;
-
-
- /**
- * Easy Connect Cryptography Curve name: brainpoolP384r1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP384R1 = 4;
-
-
- /**
- * Easy Connect Cryptography Curve name: brainpoolP512r1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP512R1 = 5;
-
- /**
- * Easy Connect Cryptography Curve name: default
- * This allows framework to choose manadatory curve prime256v1.
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_DEFAULT =
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1;
-
- /** @hide */
- @IntDef(prefix = {"EASY_CONNECT_CRYPTOGRAPHY_CURVE_"}, value = {
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_DEFAULT,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_SECP384R1,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_SECP521R1,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP256R1,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP384R1,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP512R1,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface EasyConnectCryptographyCurve {
- }
-
- /**
- * Start Easy Connect (DPP) in Configurator-Initiator role. The current device will initiate
- * Easy Connect bootstrapping with a peer, and configure the peer with the SSID and password of
- * the specified network using the Easy Connect protocol on an encrypted link.
- *
- * @param enrolleeUri URI of the Enrollee obtained separately (e.g. QR code scanning)
- * @param selectedNetworkId Selected network ID to be sent to the peer
- * @param enrolleeNetworkRole The network role of the enrollee
- * @param callback Callback for status updates
- * @param executor The Executor on which to run the callback.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void startEasyConnectAsConfiguratorInitiator(@NonNull String enrolleeUri,
- int selectedNetworkId, @EasyConnectNetworkRole int enrolleeNetworkRole,
- @NonNull @CallbackExecutor Executor executor,
- @NonNull EasyConnectStatusCallback callback) {
- Binder binder = new Binder();
- try {
- mService.startDppAsConfiguratorInitiator(binder, enrolleeUri, selectedNetworkId,
- enrolleeNetworkRole, new EasyConnectCallbackProxy(executor, callback));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Start Easy Connect (DPP) in Enrollee-Initiator role. The current device will initiate Easy
- * Connect bootstrapping with a peer, and receive the SSID and password from the peer
- * configurator.
- *
- * @param configuratorUri URI of the Configurator obtained separately (e.g. QR code scanning)
- * @param callback Callback for status updates
- * @param executor The Executor on which to run the callback.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void startEasyConnectAsEnrolleeInitiator(@NonNull String configuratorUri,
- @NonNull @CallbackExecutor Executor executor,
- @NonNull EasyConnectStatusCallback callback) {
- Binder binder = new Binder();
- try {
- mService.startDppAsEnrolleeInitiator(binder, configuratorUri,
- new EasyConnectCallbackProxy(executor, callback));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Start Easy Connect (DPP) in Enrollee-Responder role.
- * The device will:
- * 1. Generate a DPP bootstrap URI and return it using the
- * {@link EasyConnectStatusCallback#onBootstrapUriGenerated(String)} method.
- * 2. Start DPP as a Responder, waiting for an Initiator device to start the DPP
- * authentication process.
- * The caller should use the URI provided in step #1, for instance display it as a QR code
- * or communicate it in some other way to the initiator device.
- *
- * @param deviceInfo Device specific information to add to the DPP URI. This field allows
- * the users of the configurators to identify the device.
- * Optional - if not provided or in case of an empty string,
- * Info field (I:) will be skipped in the generated DPP URI.
- * Allowed Range of ASCII characters in deviceInfo - %x20-7E.
- * semicolon and space are not allowed.
- * Due to the limitation of maximum allowed characters in QR code,
- * framework limits to a max of
- * {@link #EASY_CONNECT_DEVICE_INFO_MAXIMUM_LENGTH} characters in
- * deviceInfo.
- * Violation of these rules will result in an exception.
- * @param curve Elliptic curve cryptography used to generate DPP
- * public/private key pair. If application is not interested in a
- * specific curve, choose default curve
- * {@link #EASY_CONNECT_CRYPTOGRAPHY_CURVE_DEFAULT}.
- * @param callback Callback for status updates
- * @param executor The Executor on which to run the callback.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void startEasyConnectAsEnrolleeResponder(@Nullable String deviceInfo,
- @EasyConnectCryptographyCurve int curve,
- @NonNull @CallbackExecutor Executor executor,
- @NonNull EasyConnectStatusCallback callback) {
- Binder binder = new Binder();
- try {
- mService.startDppAsEnrolleeResponder(binder, deviceInfo, curve,
- new EasyConnectCallbackProxy(executor, callback));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Stop or abort a current Easy Connect (DPP) session. This call, once processed, will
- * terminate any ongoing transaction, and clean up all associated resources. Caller should not
- * expect any callbacks once this call is made. However, due to the asynchronous nature of
- * this call, a callback may be fired if it was already pending in the queue.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void stopEasyConnectSession() {
- try {
- /* Request lower layers to stop/abort and clear resources */
- mService.stopDppSession();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Helper class to support Easy Connect (DPP) callbacks
- *
- * @hide
- */
- private static class EasyConnectCallbackProxy extends IDppCallback.Stub {
- private final Executor mExecutor;
- private final EasyConnectStatusCallback mEasyConnectStatusCallback;
-
- EasyConnectCallbackProxy(Executor executor,
- EasyConnectStatusCallback easyConnectStatusCallback) {
- mExecutor = executor;
- mEasyConnectStatusCallback = easyConnectStatusCallback;
- }
-
- @Override
- public void onSuccessConfigReceived(int newNetworkId) {
- Log.d(TAG, "Easy Connect onSuccessConfigReceived callback");
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mEasyConnectStatusCallback.onEnrolleeSuccess(newNetworkId);
- });
- }
-
- @Override
- public void onSuccess(int status) {
- Log.d(TAG, "Easy Connect onSuccess callback");
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mEasyConnectStatusCallback.onConfiguratorSuccess(status);
- });
- }
-
- @Override
- public void onFailure(int status, String ssid, String channelList,
- int[] operatingClassArray) {
- Log.d(TAG, "Easy Connect onFailure callback");
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- SparseArray channelListArray = parseDppChannelList(channelList);
- mEasyConnectStatusCallback.onFailure(status, ssid, channelListArray,
- operatingClassArray);
- });
- }
-
- @Override
- public void onProgress(int status) {
- Log.d(TAG, "Easy Connect onProgress callback");
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mEasyConnectStatusCallback.onProgress(status);
- });
- }
-
- @Override
- public void onBootstrapUriGenerated(String uri) {
- Log.d(TAG, "Easy Connect onBootstrapUriGenerated callback");
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mEasyConnectStatusCallback.onBootstrapUriGenerated(uri);
- });
- }
- }
-
- /**
- * Interface for Wi-Fi usability statistics listener. Should be implemented by applications and
- * set when calling {@link WifiManager#addOnWifiUsabilityStatsListener(Executor,
- * OnWifiUsabilityStatsListener)}.
- *
- * @hide
- */
- @SystemApi
- public interface OnWifiUsabilityStatsListener {
- /**
- * Called when Wi-Fi usability statistics is updated.
- *
- * @param seqNum The sequence number of statistics, used to derive the timing of updated
- * Wi-Fi usability statistics, set by framework and incremented by one after
- * each update.
- * @param isSameBssidAndFreq The flag to indicate whether the BSSID and the frequency of
- * network stays the same or not relative to the last update of
- * Wi-Fi usability stats.
- * @param stats The updated Wi-Fi usability statistics.
- */
- void onWifiUsabilityStats(int seqNum, boolean isSameBssidAndFreq,
- @NonNull WifiUsabilityStatsEntry stats);
- }
-
- /**
- * Adds a listener for Wi-Fi usability statistics. See {@link OnWifiUsabilityStatsListener}.
- * Multiple listeners can be added. Callers will be invoked periodically by framework to
- * inform clients about the current Wi-Fi usability statistics. Callers can remove a previously
- * added listener using {@link removeOnWifiUsabilityStatsListener}.
- *
- * @param executor The executor on which callback will be invoked.
- * @param listener Listener for Wifi usability statistics.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE)
- public void addOnWifiUsabilityStatsListener(@NonNull @CallbackExecutor Executor executor,
- @NonNull OnWifiUsabilityStatsListener listener) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (listener == null) throw new IllegalArgumentException("listener cannot be null");
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "addOnWifiUsabilityStatsListener: listener=" + listener);
- }
- try {
- mService.addOnWifiUsabilityStatsListener(new Binder(),
- new IOnWifiUsabilityStatsListener.Stub() {
- @Override
- public void onWifiUsabilityStats(int seqNum, boolean isSameBssidAndFreq,
- WifiUsabilityStatsEntry stats) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "OnWifiUsabilityStatsListener: "
- + "onWifiUsabilityStats: seqNum=" + seqNum);
- }
- Binder.clearCallingIdentity();
- executor.execute(() -> listener.onWifiUsabilityStats(
- seqNum, isSameBssidAndFreq, stats));
- }
- },
- listener.hashCode()
- );
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow callers to remove a previously registered listener. After calling this method,
- * applications will no longer receive Wi-Fi usability statistics.
- *
- * @param listener Listener to remove the Wi-Fi usability statistics.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE)
- public void removeOnWifiUsabilityStatsListener(@NonNull OnWifiUsabilityStatsListener listener) {
- if (listener == null) throw new IllegalArgumentException("listener cannot be null");
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "removeOnWifiUsabilityStatsListener: listener=" + listener);
- }
- try {
- mService.removeOnWifiUsabilityStatsListener(listener.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Provide a Wi-Fi usability score information to be recorded (but not acted upon) by the
- * framework. The Wi-Fi usability score is derived from {@link OnWifiUsabilityStatsListener}
- * where a score is matched to Wi-Fi usability statistics using the sequence number. The score
- * is used to quantify whether Wi-Fi is usable in a future time.
- *
- * @param seqNum Sequence number of the Wi-Fi usability score.
- * @param score The Wi-Fi usability score, expected range: [0, 100].
- * @param predictionHorizonSec Prediction horizon of the Wi-Fi usability score in second,
- * expected range: [0, 30].
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE)
- public void updateWifiUsabilityScore(int seqNum, int score, int predictionHorizonSec) {
- try {
- mService.updateWifiUsabilityScore(seqNum, score, predictionHorizonSec);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Abstract class for scan results callback. Should be extended by applications and set when
- * calling {@link WifiManager#registerScanResultsCallback(Executor, ScanResultsCallback)}.
- */
- public abstract static class ScanResultsCallback {
- private final ScanResultsCallbackProxy mScanResultsCallbackProxy;
-
- public ScanResultsCallback() {
- mScanResultsCallbackProxy = new ScanResultsCallbackProxy();
- }
-
- /**
- * Called when new scan results are available.
- * Clients should use {@link WifiManager#getScanResults()} to get the scan results.
- */
- public abstract void onScanResultsAvailable();
-
- /*package*/ @NonNull ScanResultsCallbackProxy getProxy() {
- return mScanResultsCallbackProxy;
- }
-
- private static class ScanResultsCallbackProxy extends IScanResultsCallback.Stub {
- private final Object mLock = new Object();
- @Nullable @GuardedBy("mLock") private Executor mExecutor;
- @Nullable @GuardedBy("mLock") private ScanResultsCallback mCallback;
-
- ScanResultsCallbackProxy() {
- mCallback = null;
- mExecutor = null;
- }
-
- /*package*/ void initProxy(@NonNull Executor executor,
- @NonNull ScanResultsCallback callback) {
- synchronized (mLock) {
- mExecutor = executor;
- mCallback = callback;
- }
- }
-
- /*package*/ void cleanUpProxy() {
- synchronized (mLock) {
- mExecutor = null;
- mCallback = null;
- }
- }
-
- @Override
- public void onScanResultsAvailable() {
- ScanResultsCallback callback;
- Executor executor;
- synchronized (mLock) {
- executor = mExecutor;
- callback = mCallback;
- }
- if (callback == null || executor == null) {
- return;
- }
- Binder.clearCallingIdentity();
- executor.execute(callback::onScanResultsAvailable);
- }
- }
- }
-
- /**
- * Register a callback for Scan Results. See {@link ScanResultsCallback}.
- * Caller will receive the event when scan results are available.
- * Caller should use {@link WifiManager#getScanResults()} requires
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} to get the scan results.
- * Caller can remove a previously registered callback using
- * {@link WifiManager#unregisterScanResultsCallback(ScanResultsCallback)}
- * Same caller can add multiple listeners.
- *
- * Applications should have the
- * {@link android.Manifest.permission#ACCESS_WIFI_STATE} permission. Callers
- * without the permission will trigger a {@link java.lang.SecurityException}.
- *
- *
- * @param executor The executor to execute the callback of the {@code callback} object.
- * @param callback callback for Scan Results events
- */
-
- @RequiresPermission(ACCESS_WIFI_STATE)
- public void registerScanResultsCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull ScanResultsCallback callback) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
-
- Log.v(TAG, "registerScanResultsCallback: callback=" + callback
- + ", executor=" + executor);
- ScanResultsCallback.ScanResultsCallbackProxy proxy = callback.getProxy();
- proxy.initProxy(executor, callback);
- try {
- mService.registerScanResultsCallback(proxy);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow callers to unregister a previously registered callback. After calling this method,
- * applications will no longer receive Scan Results events.
- *
- * @param callback callback to unregister for Scan Results events
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public void unregisterScanResultsCallback(@NonNull ScanResultsCallback callback) {
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "unregisterScanResultsCallback: Callback=" + callback);
- ScanResultsCallback.ScanResultsCallbackProxy proxy = callback.getProxy();
- try {
- mService.unregisterScanResultsCallback(proxy);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- } finally {
- proxy.cleanUpProxy();
- }
- }
-
- /**
- * Interface for suggestion connection status listener.
- * Should be implemented by applications and set when calling
- * {@link WifiManager#addSuggestionConnectionStatusListener(
- * Executor, SuggestionConnectionStatusListener)}.
- */
- public interface SuggestionConnectionStatusListener {
-
- /**
- * Called when the framework attempted to connect to a suggestion provided by the
- * registering app, but the connection to the suggestion failed.
- * @param wifiNetworkSuggestion The suggestion which failed to connect.
- * @param failureReason the connection failure reason code. One of
- * {@link #STATUS_SUGGESTION_CONNECTION_FAILURE_ASSOCIATION},
- * {@link #STATUS_SUGGESTION_CONNECTION_FAILURE_AUTHENTICATION},
- * {@link #STATUS_SUGGESTION_CONNECTION_FAILURE_IP_PROVISIONING}
- * {@link #STATUS_SUGGESTION_CONNECTION_FAILURE_UNKNOWN}
- */
- void onConnectionStatus(
- @NonNull WifiNetworkSuggestion wifiNetworkSuggestion,
- @SuggestionConnectionStatusCode int failureReason);
- }
-
- private class SuggestionConnectionStatusListenerProxy extends
- ISuggestionConnectionStatusListener.Stub {
- private final Executor mExecutor;
- private final SuggestionConnectionStatusListener mListener;
-
- SuggestionConnectionStatusListenerProxy(@NonNull Executor executor,
- @NonNull SuggestionConnectionStatusListener listener) {
- mExecutor = executor;
- mListener = listener;
- }
-
- @Override
- public void onConnectionStatus(@NonNull WifiNetworkSuggestion wifiNetworkSuggestion,
- int failureReason) {
- mExecutor.execute(() ->
- mListener.onConnectionStatus(wifiNetworkSuggestion, failureReason));
- }
-
- }
-
- /**
- * Add a listener for suggestion networks. See {@link SuggestionConnectionStatusListener}.
- * Caller will receive the event when suggested network have connection failure.
- * Caller can remove a previously registered listener using
- * {@link WifiManager#removeSuggestionConnectionStatusListener(
- * SuggestionConnectionStatusListener)}
- * Same caller can add multiple listeners to monitor the event.
- *
- * Applications should have the
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and
- * {@link android.Manifest.permission#ACCESS_WIFI_STATE} permissions.
- * Callers without the permission will trigger a {@link java.lang.SecurityException}.
- *
- *
- * @param executor The executor to execute the listener of the {@code listener} object.
- * @param listener listener for suggestion network connection failure.
- */
- @RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
- public void addSuggestionConnectionStatusListener(@NonNull @CallbackExecutor Executor executor,
- @NonNull SuggestionConnectionStatusListener listener) {
- if (listener == null) throw new IllegalArgumentException("Listener cannot be null");
- if (executor == null) throw new IllegalArgumentException("Executor cannot be null");
- Log.v(TAG, "addSuggestionConnectionStatusListener listener=" + listener
- + ", executor=" + executor);
- try {
- mService.registerSuggestionConnectionStatusListener(new Binder(),
- new SuggestionConnectionStatusListenerProxy(executor, listener),
- listener.hashCode(), mContext.getOpPackageName(), mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
-
- }
-
- /**
- * Allow callers to remove a previously registered listener. After calling this method,
- * applications will no longer receive suggestion connection events through that listener.
- *
- * @param listener listener to remove.
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public void removeSuggestionConnectionStatusListener(
- @NonNull SuggestionConnectionStatusListener listener) {
- if (listener == null) throw new IllegalArgumentException("Listener cannot be null");
- Log.v(TAG, "removeSuggestionConnectionStatusListener: listener=" + listener);
- try {
- mService.unregisterSuggestionConnectionStatusListener(listener.hashCode(),
- mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Parse the list of channels the DPP enrollee reports when it fails to find an AP.
- *
- * @param channelList List of channels in the format defined in the DPP specification.
- * @return A parsed sparse array, where the operating class is the key.
- * @hide
- */
- @VisibleForTesting
- public static SparseArray parseDppChannelList(String channelList) {
- SparseArray channelListArray = new SparseArray<>();
-
- if (TextUtils.isEmpty(channelList)) {
- return channelListArray;
- }
- StringTokenizer str = new StringTokenizer(channelList, ",");
- String classStr = null;
- List channelsInClass = new ArrayList<>();
-
- try {
- while (str.hasMoreElements()) {
- String cur = str.nextToken();
-
- /**
- * Example for a channel list:
- *
- * 81/1,2,3,4,5,6,7,8,9,10,11,115/36,40,44,48,118/52,56,60,64,121/100,104,108,112,
- * 116,120,124,128,132,136,140,0/144,124/149,153,157,161,125/165
- *
- * Detect operating class by the delimiter of '/' and use a string tokenizer with
- * ',' as a delimiter.
- */
- int classDelim = cur.indexOf('/');
- if (classDelim != -1) {
- if (classStr != null) {
- // Store the last channel array in the sparse array, where the operating
- // class is the key (as an integer).
- int[] channelsArray = new int[channelsInClass.size()];
- for (int i = 0; i < channelsInClass.size(); i++) {
- channelsArray[i] = channelsInClass.get(i);
- }
- channelListArray.append(Integer.parseInt(classStr), channelsArray);
- channelsInClass = new ArrayList<>();
- }
-
- // Init a new operating class and store the first channel
- classStr = cur.substring(0, classDelim);
- String channelStr = cur.substring(classDelim + 1);
- channelsInClass.add(Integer.parseInt(channelStr));
- } else {
- if (classStr == null) {
- // Invalid format
- Log.e(TAG, "Cannot parse DPP channel list");
- return new SparseArray<>();
- }
- channelsInClass.add(Integer.parseInt(cur));
- }
- }
-
- // Store the last array
- if (classStr != null) {
- int[] channelsArray = new int[channelsInClass.size()];
- for (int i = 0; i < channelsInClass.size(); i++) {
- channelsArray[i] = channelsInClass.get(i);
- }
- channelListArray.append(Integer.parseInt(classStr), channelsArray);
- }
- return channelListArray;
- } catch (NumberFormatException e) {
- Log.e(TAG, "Cannot parse DPP channel list");
- return new SparseArray<>();
- }
- }
-
- /**
- * Callback interface for framework to receive network status updates and trigger of updating
- * {@link WifiUsabilityStatsEntry}.
- *
- * @hide
- */
- @SystemApi
- public interface ScoreUpdateObserver {
- /**
- * Called by applications to indicate network status.
- *
- * @param sessionId The ID to indicate current Wi-Fi network connection obtained from
- * {@link WifiConnectedNetworkScorer#onStart(int)}.
- * @param score The score representing link quality of current Wi-Fi network connection.
- * Populated by connected network scorer in applications..
- */
- void notifyScoreUpdate(int sessionId, int score);
-
- /**
- * Called by applications to trigger an update of {@link WifiUsabilityStatsEntry}.
- * To receive update applications need to add WifiUsabilityStatsEntry listener. See
- * {@link addOnWifiUsabilityStatsListener(Executor, OnWifiUsabilityStatsListener)}.
- *
- * @param sessionId The ID to indicate current Wi-Fi network connection obtained from
- * {@link WifiConnectedNetworkScorer#onStart(int)}.
- */
- void triggerUpdateOfWifiUsabilityStats(int sessionId);
- }
-
- /**
- * Callback proxy for {@link ScoreUpdateObserver} objects.
- *
- * @hide
- */
- private class ScoreUpdateObserverProxy implements ScoreUpdateObserver {
- private final IScoreUpdateObserver mScoreUpdateObserver;
-
- private ScoreUpdateObserverProxy(IScoreUpdateObserver observer) {
- mScoreUpdateObserver = observer;
- }
-
- @Override
- public void notifyScoreUpdate(int sessionId, int score) {
- try {
- mScoreUpdateObserver.notifyScoreUpdate(sessionId, score);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- @Override
- public void triggerUpdateOfWifiUsabilityStats(int sessionId) {
- try {
- mScoreUpdateObserver.triggerUpdateOfWifiUsabilityStats(sessionId);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Interface for Wi-Fi connected network scorer. Should be implemented by applications and set
- * when calling
- * {@link WifiManager#setWifiConnectedNetworkScorer(Executor, WifiConnectedNetworkScorer)}.
- *
- * @hide
- */
- @SystemApi
- public interface WifiConnectedNetworkScorer {
- /**
- * Called by framework to indicate the start of a network connection.
- * @param sessionId The ID to indicate current Wi-Fi network connection.
- */
- void onStart(int sessionId);
-
- /**
- * Called by framework to indicate the end of a network connection.
- * @param sessionId The ID to indicate current Wi-Fi network connection obtained from
- * {@link WifiConnectedNetworkScorer#onStart(int)}.
- */
- void onStop(int sessionId);
-
- /**
- * Framework sets callback for score change events after application sets its scorer.
- * @param observerImpl The instance for {@link WifiManager#ScoreUpdateObserver}. Should be
- * implemented and instantiated by framework.
- */
- void onSetScoreUpdateObserver(@NonNull ScoreUpdateObserver observerImpl);
- }
-
- /**
- * Callback proxy for {@link WifiConnectedNetworkScorer} objects.
- *
- * @hide
- */
- private class WifiConnectedNetworkScorerProxy extends IWifiConnectedNetworkScorer.Stub {
- private Executor mExecutor;
- private WifiConnectedNetworkScorer mScorer;
-
- WifiConnectedNetworkScorerProxy(Executor executor, WifiConnectedNetworkScorer scorer) {
- mExecutor = executor;
- mScorer = scorer;
- }
-
- @Override
- public void onStart(int sessionId) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "WifiConnectedNetworkScorer: " + "onStart: sessionId=" + sessionId);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> mScorer.onStart(sessionId));
- }
-
- @Override
- public void onStop(int sessionId) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "WifiConnectedNetworkScorer: " + "onStop: sessionId=" + sessionId);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> mScorer.onStop(sessionId));
- }
-
- @Override
- public void onSetScoreUpdateObserver(IScoreUpdateObserver observerImpl) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "WifiConnectedNetworkScorer: "
- + "onSetScoreUpdateObserver: observerImpl=" + observerImpl);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> mScorer.onSetScoreUpdateObserver(
- new ScoreUpdateObserverProxy(observerImpl)));
- }
- }
-
- /**
- * Set a callback for Wi-Fi connected network scorer. See {@link WifiConnectedNetworkScorer}.
- * Only a single scorer can be set. Caller will be invoked periodically by framework to inform
- * client about start and stop of Wi-Fi connection. Caller can clear a previously set scorer
- * using {@link clearWifiConnectedNetworkScorer()}.
- *
- * @param executor The executor on which callback will be invoked.
- * @param scorer Scorer for Wi-Fi network implemented by application.
- * @return true Scorer is set successfully.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE)
- public boolean setWifiConnectedNetworkScorer(@NonNull @CallbackExecutor Executor executor,
- @NonNull WifiConnectedNetworkScorer scorer) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (scorer == null) throw new IllegalArgumentException("scorer cannot be null");
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "setWifiConnectedNetworkScorer: scorer=" + scorer);
- }
- try {
- return mService.setWifiConnectedNetworkScorer(new Binder(),
- new WifiConnectedNetworkScorerProxy(executor, scorer));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow caller to clear a previously set scorer. After calling this method,
- * client will no longer receive information about start and stop of Wi-Fi connection.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE)
- public void clearWifiConnectedNetworkScorer() {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "clearWifiConnectedNetworkScorer");
- }
- try {
- mService.clearWifiConnectedNetworkScorer();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Enable/disable wifi scan throttling from 3rd party apps.
- *
- *
- * The throttling limits for apps are described in
- *
- * https://developer.android.com/guide/topics/connectivity/wifi-scan#wifi-scan-throttling
- *
- *
- * @param enable true to allow scan throttling, false to disallow scan throttling.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setScanThrottleEnabled(boolean enable) {
- try {
- mService.setScanThrottleEnabled(enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get the persisted Wi-Fi scan throttle state. Defaults to true, unless changed by the user via
- * Developer options.
- *
- *
- * The throttling limits for apps are described in
- *
- * https://developer.android.com/guide/topics/connectivity/wifi-scan#wifi-scan-throttling
- *
- *
- * @return true to indicate that scan throttling is enabled, false to indicate that scan
- * throttling is disabled.
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public boolean isScanThrottleEnabled() {
- try {
- return mService.isScanThrottleEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Enable/disable wifi auto wakeup feature.
- *
- *
- * The feature is described in
- *
- * https://source.android.com/devices/tech/connect/wifi-infrastructure
- * #turn_on_wi-fi_automatically
- *
- *
- * @param enable true to enable, false to disable.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setAutoWakeupEnabled(boolean enable) {
- try {
- mService.setAutoWakeupEnabled(enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get the persisted Wi-Fi auto wakeup feature state. Defaults to false, unless changed by the
- * user via Settings.
- *
- *
- * The feature is described in
- *
- * https://source.android.com/devices/tech/connect/wifi-infrastructure
- * #turn_on_wi-fi_automatically
- *
- *
- * @return true to indicate that wakeup feature is enabled, false to indicate that wakeup
- * feature is disabled.
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public boolean isAutoWakeupEnabled() {
- try {
- return mService.isAutoWakeupEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Sets the state of carrier offload on merged or unmerged networks for specified subscription.
- *
- *
- * When a subscription's carrier network offload is disabled, all network suggestions related to
- * this subscription will not be considered for auto join.
- *
- * If calling app want disable all carrier network offload from a specified subscription, should
- * call this API twice to disable both merged and unmerged carrier network suggestions.
- *
- * @param subscriptionId See {@link SubscriptionInfo#getSubscriptionId()}.
- * @param merged True for carrier merged network, false otherwise.
- * See {@link WifiNetworkSuggestion.Builder#setCarrierMerged(boolean)}
- * @param enabled True for enable carrier network offload, false otherwise.
- * @see #isCarrierNetworkOffloadEnabled(int, boolean)
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void setCarrierNetworkOffloadEnabled(int subscriptionId, boolean merged,
- boolean enabled) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- mService.setCarrierNetworkOffloadEnabled(subscriptionId, merged, enabled);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get the carrier network offload state for merged or unmerged networks for specified
- * subscription.
- * @param subscriptionId subscription ID see {@link SubscriptionInfo#getSubscriptionId()}
- * @param merged True for carrier merged network, false otherwise.
- * See {@link WifiNetworkSuggestion.Builder#setCarrierMerged(boolean)}
- * @return True to indicate that carrier network offload is enabled, false otherwise.
- * @see #setCarrierNetworkOffloadEnabled(int, boolean, boolean)
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public boolean isCarrierNetworkOffloadEnabled(int subscriptionId, boolean merged) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- return mService.isCarrierNetworkOffloadEnabled(subscriptionId, merged);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Interface for network suggestion user approval status change listener.
- * Should be implemented by applications and registered using
- * {@link #addSuggestionUserApprovalStatusListener(Executor,
- * SuggestionUserApprovalStatusListener)} (
- */
- public interface SuggestionUserApprovalStatusListener {
-
- /**
- * Called when the user approval status of the App has changed. The current status can be
- * queried by {@link #getNetworkSuggestionUserApprovalStatus()}
- */
- void onUserApprovalStatusChange();
- }
-
- private class SuggestionUserApprovalStatusListenerProxy extends
- ISuggestionUserApprovalStatusListener.Stub {
- private final Executor mExecutor;
- private final SuggestionUserApprovalStatusListener mListener;
-
- SuggestionUserApprovalStatusListenerProxy(@NonNull Executor executor,
- @NonNull SuggestionUserApprovalStatusListener listener) {
- mExecutor = executor;
- mListener = listener;
- }
-
- @Override
- public void onUserApprovalStatusChange() {
- mExecutor.execute(() -> mListener.onUserApprovalStatusChange());
- }
-
- }
-
- /**
- * Add a listener for Wi-Fi network suggestion user approval status.
- * See {@link SuggestionUserApprovalStatusListener}.
- * Caller will receive a callback when the user approval status of the caller has changed.
- * Caller can remove a previously registered listener using
- * {@link WifiManager#removeSuggestionUserApprovalStatusListener(
- * SuggestionUserApprovalStatusListener)}
- * A caller can add multiple listeners to monitor the event.
- * @param executor The executor to execute the listener of the {@code listener} object.
- * @param listener listener for suggestion user approval status changes.
- * @return true if succeed otherwise false.
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public boolean addSuggestionUserApprovalStatusListener(
- @NonNull @CallbackExecutor Executor executor,
- @NonNull SuggestionUserApprovalStatusListener listener) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- if (listener == null) throw new IllegalArgumentException("Listener cannot be null");
- if (executor == null) throw new IllegalArgumentException("Executor cannot be null");
- Log.v(TAG, "addSuggestionUserApprovalStatusListener listener=" + listener
- + ", executor=" + executor);
- try {
- return mService.addSuggestionUserApprovalStatusListener(new Binder(),
- new SuggestionUserApprovalStatusListenerProxy(executor, listener),
- listener.hashCode(), mContext.getOpPackageName(), mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
-
- }
-
- /**
- * Allow callers to remove a previously registered listener using
- * {@link #addSuggestionUserApprovalStatusListener(Executor,
- * SuggestionUserApprovalStatusListener)}. After calling this method,
- * applications will no longer receive network suggestion user approval status change through
- * that listener.
- *
- * @param listener listener to remove.
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public void removeSuggestionUserApprovalStatusListener(
- @NonNull SuggestionUserApprovalStatusListener listener) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- if (listener == null) throw new IllegalArgumentException("Listener cannot be null");
- Log.v(TAG, "removeSuggestionUserApprovalStatusListener: listener=" + listener);
- try {
- mService.removeSuggestionUserApprovalStatusListener(listener.hashCode(),
- mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java b/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
deleted file mode 100644
index 0d13805a08d89..0000000000000
--- a/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2018 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 android.net.wifi;
-
-import static com.android.internal.util.Preconditions.checkNotNull;
-import static com.android.internal.util.Preconditions.checkState;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.MacAddress;
-import android.net.MatchAllNetworkSpecifier;
-import android.net.NetworkRequest;
-import android.net.NetworkSpecifier;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Objects;
-
-/**
- * Network specifier object used by wifi's {@link android.net.NetworkAgent}.
- * @hide
- */
-public final class WifiNetworkAgentSpecifier extends NetworkSpecifier implements Parcelable {
- /**
- * Security credentials for the currently connected network.
- */
- private final WifiConfiguration mWifiConfiguration;
-
- public WifiNetworkAgentSpecifier(@NonNull WifiConfiguration wifiConfiguration) {
- checkNotNull(wifiConfiguration);
-
- mWifiConfiguration = wifiConfiguration;
- }
-
- /**
- * @hide
- */
- public static final @android.annotation.NonNull Creator CREATOR =
- new Creator() {
- @Override
- public WifiNetworkAgentSpecifier createFromParcel(@NonNull Parcel in) {
- WifiConfiguration wifiConfiguration = in.readParcelable(null);
- return new WifiNetworkAgentSpecifier(wifiConfiguration);
- }
-
- @Override
- public WifiNetworkAgentSpecifier[] newArray(int size) {
- return new WifiNetworkAgentSpecifier[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeParcelable(mWifiConfiguration, flags);
- }
-
- @Override
- public boolean canBeSatisfiedBy(@Nullable NetworkSpecifier other) {
- if (this == other) {
- return true;
- }
- // Any generic requests should be satisifed by a specific wifi network.
- if (other == null || other instanceof MatchAllNetworkSpecifier) {
- return true;
- }
- if (other instanceof WifiNetworkSpecifier) {
- return satisfiesNetworkSpecifier((WifiNetworkSpecifier) other);
- }
- return equals(other);
- }
-
- /**
- * Match {@link WifiNetworkSpecifier} in app's {@link NetworkRequest} with the
- * {@link WifiNetworkAgentSpecifier} in wifi platform's {@link android.net.NetworkAgent}.
- */
- public boolean satisfiesNetworkSpecifier(@NonNull WifiNetworkSpecifier ns) {
- // None of these should be null by construction.
- // {@link WifiNetworkSpecifier.Builder} enforces non-null in {@link WifiNetworkSpecifier}.
- // {@link WifiNetworkFactory} ensures non-null in {@link WifiNetworkAgentSpecifier}.
- checkNotNull(ns);
- checkNotNull(ns.ssidPatternMatcher);
- checkNotNull(ns.bssidPatternMatcher);
- checkNotNull(ns.wifiConfiguration.allowedKeyManagement);
- checkNotNull(this.mWifiConfiguration.SSID);
- checkNotNull(this.mWifiConfiguration.BSSID);
- checkNotNull(this.mWifiConfiguration.allowedKeyManagement);
-
- final String ssidWithQuotes = this.mWifiConfiguration.SSID;
- checkState(ssidWithQuotes.startsWith("\"") && ssidWithQuotes.endsWith("\""));
- final String ssidWithoutQuotes = ssidWithQuotes.substring(1, ssidWithQuotes.length() - 1);
- if (!ns.ssidPatternMatcher.match(ssidWithoutQuotes)) {
- return false;
- }
- final MacAddress bssid = MacAddress.fromString(this.mWifiConfiguration.BSSID);
- final MacAddress matchBaseAddress = ns.bssidPatternMatcher.first;
- final MacAddress matchMask = ns.bssidPatternMatcher.second;
- if (!bssid.matches(matchBaseAddress, matchMask)) {
- return false;
- }
- if (!ns.wifiConfiguration.allowedKeyManagement.equals(
- this.mWifiConfiguration.allowedKeyManagement)) {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(
- mWifiConfiguration.SSID,
- mWifiConfiguration.BSSID,
- mWifiConfiguration.allowedKeyManagement);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof WifiNetworkAgentSpecifier)) {
- return false;
- }
- WifiNetworkAgentSpecifier lhs = (WifiNetworkAgentSpecifier) obj;
- return Objects.equals(this.mWifiConfiguration.SSID, lhs.mWifiConfiguration.SSID)
- && Objects.equals(this.mWifiConfiguration.BSSID, lhs.mWifiConfiguration.BSSID)
- && Objects.equals(this.mWifiConfiguration.allowedKeyManagement,
- lhs.mWifiConfiguration.allowedKeyManagement);
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("WifiNetworkAgentSpecifier [");
- sb.append("WifiConfiguration=")
- .append(", SSID=").append(mWifiConfiguration.SSID)
- .append(", BSSID=").append(mWifiConfiguration.BSSID)
- .append("]");
- return sb.toString();
- }
-
- @Override
- public NetworkSpecifier redact() {
- return null;
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java b/wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java
deleted file mode 100644
index 95b2e77c5c1e6..0000000000000
--- a/wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2014 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 android.net.wifi;
-
-import android.annotation.NonNull;
-import android.annotation.SystemApi;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * Connection Statistics For a WiFi Network.
- * @hide
- */
-@SystemApi
-public class WifiNetworkConnectionStatistics implements Parcelable {
- private static final String TAG = "WifiNetworkConnnectionStatistics";
-
- public int numConnection;
- public int numUsage;
-
- public WifiNetworkConnectionStatistics(int connection, int usage) {
- numConnection = connection;
- numUsage = usage;
- }
-
- public WifiNetworkConnectionStatistics() { }
-
- @NonNull
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- sbuf.append("c=").append(numConnection);
- sbuf.append(" u=").append(numUsage);
- return sbuf.toString();
- }
-
-
- /** copy constructor*/
- public WifiNetworkConnectionStatistics(WifiNetworkConnectionStatistics source) {
- numConnection = source.numConnection;
- numUsage = source.numUsage;
- }
-
- /** Implement the Parcelable interface */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface */
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(numConnection);
- dest.writeInt(numUsage);
- }
-
- /** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator CREATOR =
- new Creator() {
- public WifiNetworkConnectionStatistics createFromParcel(Parcel in) {
- int numConnection = in.readInt();
- int numUsage = in.readInt();
- WifiNetworkConnectionStatistics stats =
- new WifiNetworkConnectionStatistics(numConnection, numUsage);
- return stats;
- }
-
- public WifiNetworkConnectionStatistics[] newArray(int size) {
- return new WifiNetworkConnectionStatistics[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkSpecifier.java b/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
deleted file mode 100644
index be3b45d8c82a7..0000000000000
--- a/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
+++ /dev/null
@@ -1,655 +0,0 @@
-/*
- * Copyright (C) 2018 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 android.net.wifi;
-
-import static com.android.internal.util.Preconditions.checkNotNull;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.MacAddress;
-import android.net.NetworkRequest;
-import android.net.NetworkSpecifier;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.PatternMatcher;
-import android.text.TextUtils;
-import android.util.Pair;
-
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.StandardCharsets;
-import java.util.Objects;
-
-/**
- * Network specifier object used to request a local Wi-Fi network. Apps should use the
- * {@link WifiNetworkSpecifier.Builder} class to create an instance.
- */
-public final class WifiNetworkSpecifier extends NetworkSpecifier implements Parcelable {
- private static final String TAG = "WifiNetworkSpecifier";
-
- /**
- * Builder used to create {@link WifiNetworkSpecifier} objects.
- */
- public static final class Builder {
- private static final String MATCH_ALL_SSID_PATTERN_PATH = ".*";
- private static final String MATCH_EMPTY_SSID_PATTERN_PATH = "";
- private static final Pair MATCH_NO_BSSID_PATTERN1 =
- new Pair<>(MacAddress.BROADCAST_ADDRESS, MacAddress.BROADCAST_ADDRESS);
- private static final Pair MATCH_NO_BSSID_PATTERN2 =
- new Pair<>(WifiManager.ALL_ZEROS_MAC_ADDRESS, MacAddress.BROADCAST_ADDRESS);
- private static final Pair MATCH_ALL_BSSID_PATTERN =
- new Pair<>(WifiManager.ALL_ZEROS_MAC_ADDRESS, WifiManager.ALL_ZEROS_MAC_ADDRESS);
- private static final MacAddress MATCH_EXACT_BSSID_PATTERN_MASK =
- MacAddress.BROADCAST_ADDRESS;
-
- /**
- * Set WPA Enterprise type according to certificate security level.
- * This is for backward compatibility in R.
- */
- private static final int WPA3_ENTERPRISE_AUTO = 0;
- /** Set WPA Enterprise type to standard mode only. */
- private static final int WPA3_ENTERPRISE_STANDARD = 1;
- /** Set WPA Enterprise type to 192 bit mode only. */
- private static final int WPA3_ENTERPRISE_192_BIT = 2;
-
- /**
- * SSID pattern match specified by the app.
- */
- private @Nullable PatternMatcher mSsidPatternMatcher;
- /**
- * BSSID pattern match specified by the app.
- * Pair of .
- */
- private @Nullable Pair mBssidPatternMatcher;
- /**
- * Whether this is an OWE network or not.
- */
- private boolean mIsEnhancedOpen;
- /**
- * Pre-shared key for use with WPA-PSK networks.
- */
- private @Nullable String mWpa2PskPassphrase;
- /**
- * Pre-shared key for use with WPA3-SAE networks.
- */
- private @Nullable String mWpa3SaePassphrase;
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the WPA/WPA2-Enterprise networks.
- */
- private @Nullable WifiEnterpriseConfig mWpa2EnterpriseConfig;
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the WPA3-Enterprise networks.
- */
- private @Nullable WifiEnterpriseConfig mWpa3EnterpriseConfig;
- /**
- * Indicate what type this WPA3-Enterprise network is.
- */
- private int mWpa3EnterpriseType = WPA3_ENTERPRISE_AUTO;
- /**
- * This is a network that does not broadcast its SSID, so an
- * SSID-specific probe request must be used for scans.
- */
- private boolean mIsHiddenSSID;
-
- public Builder() {
- mSsidPatternMatcher = null;
- mBssidPatternMatcher = null;
- mIsEnhancedOpen = false;
- mWpa2PskPassphrase = null;
- mWpa3SaePassphrase = null;
- mWpa2EnterpriseConfig = null;
- mWpa3EnterpriseConfig = null;
- mIsHiddenSSID = false;
- }
-
- /**
- * Set the unicode SSID match pattern to use for filtering networks from scan results.
- *
- *
Overrides any previous value set using {@link #setSsid(String)} or
- * {@link #setSsidPattern(PatternMatcher)}.
- *
- * @param ssidPattern Instance of {@link PatternMatcher} containing the UTF-8 encoded
- * string pattern to use for matching the network's SSID.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setSsidPattern(@NonNull PatternMatcher ssidPattern) {
- checkNotNull(ssidPattern);
- mSsidPatternMatcher = ssidPattern;
- return this;
- }
-
- /**
- * Set the unicode SSID for the network.
- *
- *
Sets the SSID to use for filtering networks from scan results. Will only match
- * networks whose SSID is identical to the UTF-8 encoding of the specified value.
- * Overrides any previous value set using {@link #setSsid(String)} or
- * {@link #setSsidPattern(PatternMatcher)}.
- *
- * @param ssid The SSID of the network. It must be valid Unicode.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the SSID is not valid unicode.
- */
- public @NonNull Builder setSsid(@NonNull String ssid) {
- checkNotNull(ssid);
- final CharsetEncoder unicodeEncoder = StandardCharsets.UTF_8.newEncoder();
- if (!unicodeEncoder.canEncode(ssid)) {
- throw new IllegalArgumentException("SSID is not a valid unicode string");
- }
- mSsidPatternMatcher = new PatternMatcher(ssid, PatternMatcher.PATTERN_LITERAL);
- return this;
- }
-
- /**
- * Set the BSSID match pattern to use for filtering networks from scan results.
- * Will match all networks with BSSID which satisfies the following:
- * {@code BSSID & mask == baseAddress}.
- *
- *
Overrides any previous value set using {@link #setBssid(MacAddress)} or
- * {@link #setBssidPattern(MacAddress, MacAddress)}.
- *
- * @param baseAddress Base address for BSSID pattern.
- * @param mask Mask for BSSID pattern.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setBssidPattern(
- @NonNull MacAddress baseAddress, @NonNull MacAddress mask) {
- checkNotNull(baseAddress);
- checkNotNull(mask);
- mBssidPatternMatcher = Pair.create(baseAddress, mask);
- return this;
- }
-
- /**
- * Set the BSSID to use for filtering networks from scan results. Will only match network
- * whose BSSID is identical to the specified value.
- *
- *
Sets the BSSID to use for filtering networks from scan results. Will only match
- * networks whose BSSID is identical to specified value.
- * Overrides any previous value set using {@link #setBssid(MacAddress)} or
- * {@link #setBssidPattern(MacAddress, MacAddress)}.
- *
- * @param bssid BSSID of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setBssid(@NonNull MacAddress bssid) {
- checkNotNull(bssid);
- mBssidPatternMatcher = Pair.create(bssid, MATCH_EXACT_BSSID_PATTERN_MASK);
- return this;
- }
-
- /**
- * Specifies whether this represents an Enhanced Open (OWE) network.
- *
- * @param isEnhancedOpen {@code true} to indicate that the network uses enhanced open,
- * {@code false} otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsEnhancedOpen(boolean isEnhancedOpen) {
- mIsEnhancedOpen = isEnhancedOpen;
- return this;
- }
-
- /**
- * Set the ASCII WPA2 passphrase for this network. Needed for authenticating to
- * WPA2-PSK networks.
- *
- * @param passphrase passphrase of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
- */
- public @NonNull Builder setWpa2Passphrase(@NonNull String passphrase) {
- checkNotNull(passphrase);
- final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
- if (!asciiEncoder.canEncode(passphrase)) {
- throw new IllegalArgumentException("passphrase not ASCII encodable");
- }
- mWpa2PskPassphrase = passphrase;
- return this;
- }
-
- /**
- * Set the ASCII WPA3 passphrase for this network. Needed for authenticating to WPA3-SAE
- * networks.
- *
- * @param passphrase passphrase of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
- */
- public @NonNull Builder setWpa3Passphrase(@NonNull String passphrase) {
- checkNotNull(passphrase);
- final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
- if (!asciiEncoder.canEncode(passphrase)) {
- throw new IllegalArgumentException("passphrase not ASCII encodable");
- }
- mWpa3SaePassphrase = passphrase;
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA2-EAP networks. See {@link WifiEnterpriseConfig} for description.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setWpa2EnterpriseConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- mWpa2EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA3-Enterprise networks (standard and 192-bit security). See
- * {@link WifiEnterpriseConfig} for description. For 192-bit security networks, both the
- * client and CA certificates must be provided, and must be of type of either
- * sha384WithRSAEncryption (OID 1.2.840.113549.1.1.12) or ecdsa-with-SHA384
- * (OID 1.2.840.10045.4.3.3).
- *
- * @deprecated use {@link #setWpa3EnterpriseStandardModeConfig(WifiEnterpriseConfig)} or
- * {@link #setWpa3Enterprise192BitModeConfig(WifiEnterpriseConfig)} to specify
- * WPA3-Enterprise type explicitly.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- @Deprecated
- public @NonNull Builder setWpa3EnterpriseConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to standard WPA3-Enterprise networks. See {@link WifiEnterpriseConfig} for description.
- * For WPA3-Enterprise in 192-bit security mode networks,
- * see {@link #setWpa3Enterprise192BitModeConfig(WifiEnterpriseConfig)} for description.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setWpa3EnterpriseStandardModeConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- mWpa3EnterpriseType = WPA3_ENTERPRISE_STANDARD;
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA3-Enterprise in 192-bit security mode networks. See {@link WifiEnterpriseConfig}
- * for description. Both the client and CA certificates must be provided,
- * and must be of type of either sha384WithRSAEncryption with key length of 3072bit or
- * more (OID 1.2.840.113549.1.1.12), or ecdsa-with-SHA384 with key length of 384bit or
- * more (OID 1.2.840.10045.4.3.3).
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the EAP type or certificates do not
- * meet 192-bit mode requirements.
- */
- public @NonNull Builder setWpa3Enterprise192BitModeConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- if (enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.TLS) {
- throw new IllegalArgumentException("The 192-bit mode network type must be TLS");
- }
- if (!WifiEnterpriseConfig.isSuiteBCipherCert(
- enterpriseConfig.getClientCertificate())) {
- throw new IllegalArgumentException(
- "The client certificate does not meet 192-bit mode requirements.");
- }
- if (!WifiEnterpriseConfig.isSuiteBCipherCert(
- enterpriseConfig.getCaCertificate())) {
- throw new IllegalArgumentException(
- "The CA certificate does not meet 192-bit mode requirements.");
- }
-
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- mWpa3EnterpriseType = WPA3_ENTERPRISE_192_BIT;
- return this;
- }
-
- /**
- * Specifies whether this represents a hidden network.
- *
- *
Setting this disallows the usage of {@link #setSsidPattern(PatternMatcher)} since
- * hidden networks need to be explicitly probed for.
- * If not set, defaults to false (i.e not a hidden network).
- *
- * @param isHiddenSsid {@code true} to indicate that the network is hidden, {@code false}
- * otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsHiddenSsid(boolean isHiddenSsid) {
- mIsHiddenSSID = isHiddenSsid;
- return this;
- }
-
- private void setSecurityParamsInWifiConfiguration(
- @NonNull WifiConfiguration configuration) {
- if (!TextUtils.isEmpty(mWpa2PskPassphrase)) { // WPA-PSK network.
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_PSK);
- // WifiConfiguration.preSharedKey needs quotes around ASCII password.
- configuration.preSharedKey = "\"" + mWpa2PskPassphrase + "\"";
- } else if (!TextUtils.isEmpty(mWpa3SaePassphrase)) { // WPA3-SAE network.
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_SAE);
- // WifiConfiguration.preSharedKey needs quotes around ASCII password.
- configuration.preSharedKey = "\"" + mWpa3SaePassphrase + "\"";
- } else if (mWpa2EnterpriseConfig != null) { // WPA-EAP network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP);
- configuration.enterpriseConfig = mWpa2EnterpriseConfig;
- } else if (mWpa3EnterpriseConfig != null) { // WPA3-Enterprise
- if (mWpa3EnterpriseType == WPA3_ENTERPRISE_AUTO
- && mWpa3EnterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS
- && WifiEnterpriseConfig.isSuiteBCipherCert(
- mWpa3EnterpriseConfig.getClientCertificate())
- && WifiEnterpriseConfig.isSuiteBCipherCert(
- mWpa3EnterpriseConfig.getCaCertificate())) {
- // WPA3-Enterprise in 192-bit security mode
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT);
- } else if (mWpa3EnterpriseType == WPA3_ENTERPRISE_192_BIT) {
- // WPA3-Enterprise in 192-bit security mode
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT);
- } else {
- // WPA3-Enterprise
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE);
- }
- configuration.enterpriseConfig = mWpa3EnterpriseConfig;
- } else if (mIsEnhancedOpen) { // OWE network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OWE);
- } else { // Open network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OPEN);
- }
- }
-
- /**
- * Helper method to build WifiConfiguration object from the builder.
- * @return Instance of {@link WifiConfiguration}.
- */
- private WifiConfiguration buildWifiConfiguration() {
- final WifiConfiguration wifiConfiguration = new WifiConfiguration();
- // WifiConfiguration.SSID needs quotes around unicode SSID.
- if (mSsidPatternMatcher.getType() == PatternMatcher.PATTERN_LITERAL) {
- wifiConfiguration.SSID = "\"" + mSsidPatternMatcher.getPath() + "\"";
- }
- if (mBssidPatternMatcher.second == MATCH_EXACT_BSSID_PATTERN_MASK) {
- wifiConfiguration.BSSID = mBssidPatternMatcher.first.toString();
- }
- setSecurityParamsInWifiConfiguration(wifiConfiguration);
- wifiConfiguration.hiddenSSID = mIsHiddenSSID;
- return wifiConfiguration;
- }
-
- private boolean hasSetAnyPattern() {
- return mSsidPatternMatcher != null || mBssidPatternMatcher != null;
- }
-
- private void setMatchAnyPatternIfUnset() {
- if (mSsidPatternMatcher == null) {
- mSsidPatternMatcher = new PatternMatcher(MATCH_ALL_SSID_PATTERN_PATH,
- PatternMatcher.PATTERN_SIMPLE_GLOB);
- }
- if (mBssidPatternMatcher == null) {
- mBssidPatternMatcher = MATCH_ALL_BSSID_PATTERN;
- }
- }
-
- private boolean hasSetMatchNonePattern() {
- if (mSsidPatternMatcher.getType() != PatternMatcher.PATTERN_PREFIX
- && mSsidPatternMatcher.getPath().equals(MATCH_EMPTY_SSID_PATTERN_PATH)) {
- return true;
- }
- if (mBssidPatternMatcher.equals(MATCH_NO_BSSID_PATTERN1)) {
- return true;
- }
- if (mBssidPatternMatcher.equals(MATCH_NO_BSSID_PATTERN2)) {
- return true;
- }
- return false;
- }
-
- private boolean hasSetMatchAllPattern() {
- if ((mSsidPatternMatcher.match(MATCH_EMPTY_SSID_PATTERN_PATH))
- && mBssidPatternMatcher.equals(MATCH_ALL_BSSID_PATTERN)) {
- return true;
- }
- return false;
- }
-
- private void validateSecurityParams() {
- int numSecurityTypes = 0;
- numSecurityTypes += mIsEnhancedOpen ? 1 : 0;
- numSecurityTypes += !TextUtils.isEmpty(mWpa2PskPassphrase) ? 1 : 0;
- numSecurityTypes += !TextUtils.isEmpty(mWpa3SaePassphrase) ? 1 : 0;
- numSecurityTypes += mWpa2EnterpriseConfig != null ? 1 : 0;
- numSecurityTypes += mWpa3EnterpriseConfig != null ? 1 : 0;
- if (numSecurityTypes > 1) {
- throw new IllegalStateException("only one of setIsEnhancedOpen, setWpa2Passphrase,"
- + "setWpa3Passphrase, setWpa2EnterpriseConfig or setWpa3EnterpriseConfig"
- + " can be invoked for network specifier");
- }
- }
-
- /**
- * Create a specifier object used to request a local Wi-Fi network. The generated
- * {@link NetworkSpecifier} should be used in
- * {@link NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} when building
- * the {@link NetworkRequest}. These specifiers can only be used to request a local wifi
- * network (i.e no internet capability). So, the device will not switch it's default route
- * to wifi if there are other transports (cellular for example) available.
- *
- * Note: Apps can set a combination of network match params:
- *
SSID Pattern using {@link #setSsidPattern(PatternMatcher)} OR Specific SSID using
- * {@link #setSsid(String)}.
- * AND/OR
- * BSSID Pattern using {@link #setBssidPattern(MacAddress, MacAddress)} OR Specific
- * BSSID using {@link #setBssid(MacAddress)}
- * to trigger connection to a network that matches the set params.
- * The system will find the set of networks matching the request and present the user
- * with a system dialog which will allow the user to select a specific Wi-Fi network to
- * connect to or to deny the request.
- *
- *
- * For example:
- * To connect to an open network with a SSID prefix of "test" and a BSSID OUI of "10:03:23":
- *
- * {@code
- * final NetworkSpecifier specifier =
- * new Builder()
- * .setSsidPattern(new PatternMatcher("test", PatterMatcher.PATTERN_PREFIX))
- * .setBssidPattern(MacAddress.fromString("10:03:23:00:00:00"),
- * MacAddress.fromString("ff:ff:ff:00:00:00"))
- * .build()
- * final NetworkRequest request =
- * new NetworkRequest.Builder()
- * .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
- * .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
- * .setNetworkSpecifier(specifier)
- * .build();
- * final ConnectivityManager connectivityManager =
- * context.getSystemService(Context.CONNECTIVITY_SERVICE);
- * final NetworkCallback networkCallback = new NetworkCallback() {
- * ...
- * {@literal @}Override
- * void onAvailable(...) {}
- * // etc.
- * };
- * connectivityManager.requestNetwork(request, networkCallback);
- * }
- *
- * @return Instance of {@link NetworkSpecifier}.
- * @throws IllegalStateException on invalid params set.
- */
- public @NonNull WifiNetworkSpecifier build() {
- if (!hasSetAnyPattern()) {
- throw new IllegalStateException("one of setSsidPattern/setSsid/setBssidPattern/"
- + "setBssid should be invoked for specifier");
- }
- setMatchAnyPatternIfUnset();
- if (hasSetMatchNonePattern()) {
- throw new IllegalStateException("cannot set match-none pattern for specifier");
- }
- if (hasSetMatchAllPattern()) {
- throw new IllegalStateException("cannot set match-all pattern for specifier");
- }
- if (mIsHiddenSSID && mSsidPatternMatcher.getType() != PatternMatcher.PATTERN_LITERAL) {
- throw new IllegalStateException("setSsid should also be invoked when "
- + "setIsHiddenSsid is invoked for network specifier");
- }
- validateSecurityParams();
-
- return new WifiNetworkSpecifier(
- mSsidPatternMatcher,
- mBssidPatternMatcher,
- buildWifiConfiguration());
- }
- }
-
- /**
- * SSID pattern match specified by the app.
- * @hide
- */
- public final PatternMatcher ssidPatternMatcher;
-
- /**
- * BSSID pattern match specified by the app.
- * Pair of .
- * @hide
- */
- public final Pair bssidPatternMatcher;
-
- /**
- * Security credentials for the network.
- *
- * Note: {@link WifiConfiguration#SSID} & {@link WifiConfiguration#BSSID} fields from
- * WifiConfiguration are not used. Instead we use the {@link #ssidPatternMatcher} &
- * {@link #bssidPatternMatcher} fields embedded directly
- * within {@link WifiNetworkSpecifier}.
- * @hide
- */
- public final WifiConfiguration wifiConfiguration;
-
- /** @hide */
- public WifiNetworkSpecifier() throws IllegalAccessException {
- throw new IllegalAccessException("Use the builder to create an instance");
- }
-
- /** @hide */
- public WifiNetworkSpecifier(@NonNull PatternMatcher ssidPatternMatcher,
- @NonNull Pair bssidPatternMatcher,
- @NonNull WifiConfiguration wifiConfiguration) {
- checkNotNull(ssidPatternMatcher);
- checkNotNull(bssidPatternMatcher);
- checkNotNull(wifiConfiguration);
-
- this.ssidPatternMatcher = ssidPatternMatcher;
- this.bssidPatternMatcher = bssidPatternMatcher;
- this.wifiConfiguration = wifiConfiguration;
- }
-
- public static final @NonNull Creator CREATOR =
- new Creator() {
- @Override
- public WifiNetworkSpecifier createFromParcel(Parcel in) {
- PatternMatcher ssidPatternMatcher = in.readParcelable(/* classLoader */null);
- MacAddress baseAddress = in.readParcelable(null);
- MacAddress mask = in.readParcelable(null);
- Pair bssidPatternMatcher =
- Pair.create(baseAddress, mask);
- WifiConfiguration wifiConfiguration = in.readParcelable(null);
- return new WifiNetworkSpecifier(ssidPatternMatcher, bssidPatternMatcher,
- wifiConfiguration);
- }
-
- @Override
- public WifiNetworkSpecifier[] newArray(int size) {
- return new WifiNetworkSpecifier[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeParcelable(ssidPatternMatcher, flags);
- dest.writeParcelable(bssidPatternMatcher.first, flags);
- dest.writeParcelable(bssidPatternMatcher.second, flags);
- dest.writeParcelable(wifiConfiguration, flags);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(
- ssidPatternMatcher.getPath(), ssidPatternMatcher.getType(), bssidPatternMatcher,
- wifiConfiguration.allowedKeyManagement);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof WifiNetworkSpecifier)) {
- return false;
- }
- WifiNetworkSpecifier lhs = (WifiNetworkSpecifier) obj;
- return Objects.equals(this.ssidPatternMatcher.getPath(),
- lhs.ssidPatternMatcher.getPath())
- && Objects.equals(this.ssidPatternMatcher.getType(),
- lhs.ssidPatternMatcher.getType())
- && Objects.equals(this.bssidPatternMatcher,
- lhs.bssidPatternMatcher)
- && Objects.equals(this.wifiConfiguration.allowedKeyManagement,
- lhs.wifiConfiguration.allowedKeyManagement);
- }
-
- @Override
- public String toString() {
- return new StringBuilder()
- .append("WifiNetworkSpecifier [")
- .append(", SSID Match pattern=").append(ssidPatternMatcher)
- .append(", BSSID Match pattern=").append(bssidPatternMatcher)
- .append(", SSID=").append(wifiConfiguration.SSID)
- .append(", BSSID=").append(wifiConfiguration.BSSID)
- .append("]")
- .toString();
- }
-
- /** @hide */
- @Override
- public boolean canBeSatisfiedBy(NetworkSpecifier other) {
- if (other instanceof WifiNetworkAgentSpecifier) {
- return ((WifiNetworkAgentSpecifier) other).satisfiesNetworkSpecifier(this);
- }
- // Specific requests are checked for equality although testing for equality of 2 patterns do
- // not make much sense!
- return equals(other);
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
deleted file mode 100644
index b7450c538ff87..0000000000000
--- a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
+++ /dev/null
@@ -1,1406 +0,0 @@
-/*
- * Copyright (C) 2018 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 android.net.wifi;
-
-import static com.android.internal.util.Preconditions.checkNotNull;
-
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.net.NetworkCapabilities;
-import android.net.NetworkRequest;
-import android.net.wifi.hotspot2.PasspointConfiguration;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.telephony.SubscriptionInfo;
-import android.telephony.SubscriptionManager;
-import android.telephony.TelephonyManager;
-import android.text.TextUtils;
-
-import com.android.modules.utils.build.SdkLevel;
-
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.StandardCharsets;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * The Network Suggestion object is used to provide a Wi-Fi network for consideration when
- * auto-connecting to networks. Apps cannot directly create this object, they must use
- * {@link WifiNetworkSuggestion.Builder#build()} to obtain an instance of this object.
- *
- * Apps can provide a list of such networks to the platform using
- * {@link WifiManager#addNetworkSuggestions(List)}.
- */
-public final class WifiNetworkSuggestion implements Parcelable {
- /**
- * Builder used to create {@link WifiNetworkSuggestion} objects.
- */
- public static final class Builder {
- private static final int UNASSIGNED_PRIORITY = -1;
-
- /**
- * Set WPA Enterprise type according to certificate security level.
- * This is for backward compatibility in R.
- */
- private static final int WPA3_ENTERPRISE_AUTO = 0;
- /** Set WPA Enterprise type to standard mode only. */
- private static final int WPA3_ENTERPRISE_STANDARD = 1;
- /** Set WPA Enterprise type to 192 bit mode only. */
- private static final int WPA3_ENTERPRISE_192_BIT = 2;
-
- /**
- * SSID of the network.
- */
- private String mSsid;
- /**
- * Optional BSSID within the network.
- */
- private MacAddress mBssid;
- /**
- * Whether this is an OWE network or not.
- */
- private boolean mIsEnhancedOpen;
- /**
- * Pre-shared key for use with WPA-PSK networks.
- */
- private @Nullable String mWpa2PskPassphrase;
- /**
- * Pre-shared key for use with WPA3-SAE networks.
- */
- private @Nullable String mWpa3SaePassphrase;
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the WPA/WPA2-Enterprise networks.
- */
- private @Nullable WifiEnterpriseConfig mWpa2EnterpriseConfig;
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the WPA3-Enterprise networks.
- */
- private @Nullable WifiEnterpriseConfig mWpa3EnterpriseConfig;
- /**
- * Indicate what type this WPA3-Enterprise network is.
- */
- private int mWpa3EnterpriseType = WPA3_ENTERPRISE_AUTO;
- /**
- * The passpoint config for use with Hotspot 2.0 network
- */
- private @Nullable PasspointConfiguration mPasspointConfiguration;
- /**
- * This is a network that does not broadcast its SSID, so an
- * SSID-specific probe request must be used for scans.
- */
- private boolean mIsHiddenSSID;
- /**
- * Whether app needs to log in to captive portal to obtain Internet access.
- */
- private boolean mIsAppInteractionRequired;
- /**
- * Whether user needs to log in to captive portal to obtain Internet access.
- */
- private boolean mIsUserInteractionRequired;
- /**
- * Whether this network is metered or not.
- */
- private int mMeteredOverride;
- /**
- * Priority of this network among other network suggestions from same priority group
- * provided by the app.
- * The lower the number, the higher the priority (i.e value of 0 = highest priority).
- */
- private int mPriority;
- /**
- * Priority group ID, while suggestion priority will only effect inside the priority group.
- */
- private int mPriorityGroup;
-
- /**
- * The carrier ID identifies the operator who provides this network configuration.
- * see {@link TelephonyManager#getSimCarrierId()}
- */
- private int mCarrierId;
-
- /**
- * The Subscription ID identifies the SIM card for which this network configuration is
- * valid.
- */
- private int mSubscriptionId;
-
- /**
- * Whether this network is shared credential with user to allow user manually connect.
- */
- private boolean mIsSharedWithUser;
-
- /**
- * Whether the setCredentialSharedWithUser have been called.
- */
- private boolean mIsSharedWithUserSet;
-
- /**
- * Whether this network is initialized with auto-join enabled (the default) or not.
- */
- private boolean mIsInitialAutojoinEnabled;
-
- /**
- * Pre-shared key for use with WAPI-PSK networks.
- */
- private @Nullable String mWapiPskPassphrase;
-
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the WAPI networks.
- */
- private @Nullable WifiEnterpriseConfig mWapiEnterpriseConfig;
-
- /**
- * Whether this network will be brought up as untrusted (TRUSTED capability bit removed).
- */
- private boolean mIsNetworkUntrusted;
-
- /**
- * Whether this network will be brought up as OEM paid (OEM_PAID capability bit added).
- */
- private boolean mIsNetworkOemPaid;
-
- /**
- * Whether this network will be brought up as OEM private (OEM_PRIVATE capability bit
- * added).
- */
- private boolean mIsNetworkOemPrivate;
-
- /**
- * Whether this network is a carrier merged network.
- */
- private boolean mIsCarrierMerged;
-
- /**
- * Whether this network will use enhanced MAC randomization.
- */
- private boolean mIsEnhancedMacRandomizationEnabled;
-
- public Builder() {
- mSsid = null;
- mBssid = null;
- mIsEnhancedOpen = false;
- mWpa2PskPassphrase = null;
- mWpa3SaePassphrase = null;
- mWpa2EnterpriseConfig = null;
- mWpa3EnterpriseConfig = null;
- mPasspointConfiguration = null;
- mIsHiddenSSID = false;
- mIsAppInteractionRequired = false;
- mIsUserInteractionRequired = false;
- mMeteredOverride = WifiConfiguration.METERED_OVERRIDE_NONE;
- mIsSharedWithUser = true;
- mIsSharedWithUserSet = false;
- mIsInitialAutojoinEnabled = true;
- mPriority = UNASSIGNED_PRIORITY;
- mCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
- mWapiPskPassphrase = null;
- mWapiEnterpriseConfig = null;
- mIsNetworkUntrusted = false;
- mIsNetworkOemPaid = false;
- mIsNetworkOemPrivate = false;
- mIsCarrierMerged = false;
- mPriorityGroup = 0;
- mIsEnhancedMacRandomizationEnabled = false;
- mSubscriptionId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
- }
-
- /**
- * Set the unicode SSID for the network.
- *
- *
Overrides any previous value set using {@link #setSsid(String)}.
- *
- * @param ssid The SSID of the network. It must be valid Unicode.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the SSID is not valid unicode.
- */
- public @NonNull Builder setSsid(@NonNull String ssid) {
- checkNotNull(ssid);
- final CharsetEncoder unicodeEncoder = StandardCharsets.UTF_8.newEncoder();
- if (!unicodeEncoder.canEncode(ssid)) {
- throw new IllegalArgumentException("SSID is not a valid unicode string");
- }
- mSsid = new String(ssid);
- return this;
- }
-
- /**
- * Set the BSSID to use for filtering networks from scan results. Will only match network
- * whose BSSID is identical to the specified value.
- *
- *
If set, only the specified BSSID with the specified SSID will be considered for
- * connection.
- * If not set, all BSSIDs with the specified SSID will be considered for connection.
- *
- * Overrides any previous value set using {@link #setBssid(MacAddress)}.
- *
- * @param bssid BSSID of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setBssid(@NonNull MacAddress bssid) {
- checkNotNull(bssid);
- mBssid = MacAddress.fromBytes(bssid.toByteArray());
- return this;
- }
-
- /**
- * Specifies whether this represents an Enhanced Open (OWE) network.
- *
- * @param isEnhancedOpen {@code true} to indicate that the network used enhanced open,
- * {@code false} otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsEnhancedOpen(boolean isEnhancedOpen) {
- mIsEnhancedOpen = isEnhancedOpen;
- return this;
- }
-
- /**
- * Set the ASCII WPA2 passphrase for this network. Needed for authenticating to
- * WPA2-PSK networks.
- *
- * @param passphrase passphrase of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
- */
- public @NonNull Builder setWpa2Passphrase(@NonNull String passphrase) {
- checkNotNull(passphrase);
- final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
- if (!asciiEncoder.canEncode(passphrase)) {
- throw new IllegalArgumentException("passphrase not ASCII encodable");
- }
- mWpa2PskPassphrase = passphrase;
- return this;
- }
-
- /**
- * Set the ASCII WPA3 passphrase for this network. Needed for authenticating to WPA3-SAE
- * networks.
- *
- * @param passphrase passphrase of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
- */
- public @NonNull Builder setWpa3Passphrase(@NonNull String passphrase) {
- checkNotNull(passphrase);
- final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
- if (!asciiEncoder.canEncode(passphrase)) {
- throw new IllegalArgumentException("passphrase not ASCII encodable");
- }
- mWpa3SaePassphrase = passphrase;
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA2 enterprise networks. See {@link WifiEnterpriseConfig} for description.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if configuration CA certificate or
- * AltSubjectMatch/DomainSuffixMatch is not set.
- */
- public @NonNull Builder setWpa2EnterpriseConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- if (enterpriseConfig.isInsecure()) {
- throw new IllegalArgumentException("Enterprise configuration is insecure");
- }
- mWpa2EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA3-Enterprise networks (standard and 192-bit security). See
- * {@link WifiEnterpriseConfig} for description. For 192-bit security networks, both the
- * client and CA certificates must be provided, and must be of type of either
- * sha384WithRSAEncryption (OID 1.2.840.113549.1.1.12) or ecdsa-with-SHA384
- * (OID 1.2.840.10045.4.3.3).
- *
- * @deprecated use {@link #setWpa3EnterpriseStandardModeConfig(WifiEnterpriseConfig)} or
- * {@link #setWpa3Enterprise192BitModeConfig(WifiEnterpriseConfig)} to specify
- * WPA3-Enterprise type explicitly.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if configuration CA certificate or
- * AltSubjectMatch/DomainSuffixMatch is not set.
- */
- @Deprecated
- public @NonNull Builder setWpa3EnterpriseConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- if (enterpriseConfig.isInsecure()) {
- throw new IllegalArgumentException("Enterprise configuration is insecure");
- }
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA3-Enterprise standard networks. See {@link WifiEnterpriseConfig} for description.
- * For WPA3-Enterprise in 192-bit security mode networks,
- * see {@link #setWpa3Enterprise192BitModeConfig(WifiEnterpriseConfig)} for description.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if configuration CA certificate or
- * AltSubjectMatch/DomainSuffixMatch is not set.
- */
- public @NonNull Builder setWpa3EnterpriseStandardModeConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- if (enterpriseConfig.isInsecure()) {
- throw new IllegalArgumentException("Enterprise configuration is insecure");
- }
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- mWpa3EnterpriseType = WPA3_ENTERPRISE_STANDARD;
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA3-Enterprise in 192-bit security mode networks. See {@link WifiEnterpriseConfig}
- * for description. Both the client and CA certificates must be provided,
- * and must be of type of either sha384WithRSAEncryption with key length of 3072bit or
- * more (OID 1.2.840.113549.1.1.12), or ecdsa-with-SHA384 with key length of 384bit or
- * more (OID 1.2.840.10045.4.3.3).
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the EAP type or certificates do not
- * meet 192-bit mode requirements.
- */
- public @NonNull Builder setWpa3Enterprise192BitModeConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- if (enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.TLS) {
- throw new IllegalArgumentException("The 192-bit mode network type must be TLS");
- }
- if (!WifiEnterpriseConfig.isSuiteBCipherCert(
- enterpriseConfig.getClientCertificate())) {
- throw new IllegalArgumentException(
- "The client certificate does not meet 192-bit mode requirements.");
- }
- if (!WifiEnterpriseConfig.isSuiteBCipherCert(
- enterpriseConfig.getCaCertificate())) {
- throw new IllegalArgumentException(
- "The CA certificate does not meet 192-bit mode requirements.");
- }
-
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- mWpa3EnterpriseType = WPA3_ENTERPRISE_192_BIT;
- return this;
- }
-
- /**
- * Set the associated Passpoint configuration for this network. Needed for authenticating
- * to Hotspot 2.0 networks. See {@link PasspointConfiguration} for description.
- *
- * @param passpointConfig Instance of {@link PasspointConfiguration}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if passpoint configuration is invalid.
- */
- public @NonNull Builder setPasspointConfig(
- @NonNull PasspointConfiguration passpointConfig) {
- checkNotNull(passpointConfig);
- if (!passpointConfig.validate()) {
- throw new IllegalArgumentException("Passpoint configuration is invalid");
- }
- mPasspointConfiguration = passpointConfig;
- return this;
- }
-
- /**
- * Set the carrier ID of the network operator. The carrier ID associates a Suggested
- * network with a specific carrier (and therefore SIM). The carrier ID must be provided
- * for any network which uses the SIM-based authentication: e.g. EAP-SIM, EAP-AKA,
- * EAP-AKA', and EAP-PEAP with SIM-based phase 2 authentication.
- * @param carrierId see {@link TelephonyManager#getSimCarrierId()}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_CARRIER_PROVISIONING)
- public @NonNull Builder setCarrierId(int carrierId) {
- mCarrierId = carrierId;
- return this;
- }
-
- /**
- * Set the subscription ID of the SIM card for which this suggestion is targeted.
- * The suggestion will only apply to that SIM card.
- *
- * The subscription ID must belong to a carrier ID which meets either of the following
- * conditions:
- *
The carrier ID specified by the cross carrier provider, or
- * The carrier ID which is used to validate the suggesting carrier-privileged app, see
- * {@link TelephonyManager#hasCarrierPrivileges()}
- *
- * @param subId subscription ID see {@link SubscriptionInfo#getSubscriptionId()}
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setSubscriptionId(int subId) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mSubscriptionId = subId;
- return this;
- }
-
- /**
- * Set the priority group ID, {@link #setPriority(int)} will only impact the network
- * suggestions from the same priority group within the same app.
- *
- * @param priorityGroup priority group id, if not set default is 0.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setPriorityGroup(int priorityGroup) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mPriorityGroup = priorityGroup;
- return this;
- }
-
- /**
- * Set the ASCII WAPI passphrase for this network. Needed for authenticating to
- * WAPI-PSK networks.
- *
- * @param passphrase passphrase of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
- *
- */
- public @NonNull Builder setWapiPassphrase(@NonNull String passphrase) {
- checkNotNull(passphrase);
- final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
- if (!asciiEncoder.canEncode(passphrase)) {
- throw new IllegalArgumentException("passphrase not ASCII encodable");
- }
- mWapiPskPassphrase = passphrase;
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WAPI-CERT networks. See {@link WifiEnterpriseConfig} for description.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setWapiEnterpriseConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- mWapiEnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- return this;
- }
-
- /**
- * Specifies whether this represents a hidden network.
- *
- *
If not set, defaults to false (i.e not a hidden network).
- *
- * @param isHiddenSsid {@code true} to indicate that the network is hidden, {@code false}
- * otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsHiddenSsid(boolean isHiddenSsid) {
- mIsHiddenSSID = isHiddenSsid;
- return this;
- }
-
- /**
- * Specifies the MAC randomization method.
- *
- * Suggested networks will never use the device (factory) MAC address to associate to the
- * network - instead they use a locally generated random MAC address. This method controls
- * the strategy for generating the random MAC address:
- *
Persisted MAC randomization (false - the default): generates the MAC address from a
- * secret seed and information from the Wi-Fi configuration (SSID or Passpoint profile).
- * This means that the same generated MAC address will be used for each subsequent
- * association.
- * Enhanced MAC randomization (true): periodically generates a new MAC
- * address for new connections. Under this option, the randomized MAC address should change
- * if the suggestion is removed and then added back.
- *
- * @param enabled {@code true} to periodically change the randomized MAC address.
- * {@code false} to use the same randomized MAC for all connections to this
- * network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsEnhancedMacRandomizationEnabled(boolean enabled) {
- mIsEnhancedMacRandomizationEnabled = enabled;
- return this;
- }
-
- /**
- * Specifies whether the app needs to log in to a captive portal to obtain Internet access.
- *
- * This will dictate if the directed broadcast
- * {@link WifiManager#ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION} will be sent to the
- * app after successfully connecting to the network.
- * Use this for captive portal type networks where the app needs to authenticate the user
- * before the device can access the network.
- *
- *
If not set, defaults to false (i.e no app interaction required).
- *
- * @param isAppInteractionRequired {@code true} to indicate that app interaction is
- * required, {@code false} otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsAppInteractionRequired(boolean isAppInteractionRequired) {
- mIsAppInteractionRequired = isAppInteractionRequired;
- return this;
- }
-
- /**
- * Specifies whether the user needs to log in to a captive portal to obtain Internet access.
- *
- *
If not set, defaults to false (i.e no user interaction required).
- *
- * @param isUserInteractionRequired {@code true} to indicate that user interaction is
- * required, {@code false} otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsUserInteractionRequired(boolean isUserInteractionRequired) {
- mIsUserInteractionRequired = isUserInteractionRequired;
- return this;
- }
-
- /**
- * Specify the priority of this network among other network suggestions provided by the same
- * app (priorities have no impact on suggestions by different apps) and within the same
- * priority group, see {@link #setPriorityGroup(int)}.
- * The higher the number, the higher the priority (i.e value of 0 = lowest priority).
- *
- *
If not set, defaults a lower priority than any assigned priority.
- *
- * @param priority Integer number representing the priority among suggestions by the app.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the priority value is negative.
- */
- public @NonNull Builder setPriority(@IntRange(from = 0) int priority) {
- if (priority < 0) {
- throw new IllegalArgumentException("Invalid priority value " + priority);
- }
- mPriority = priority;
- return this;
- }
-
- /**
- * Specifies whether this network is metered.
- *
- *
If not set, defaults to detect automatically.
- *
- * @param isMetered {@code true} to indicate that the network is metered, {@code false}
- * for not metered.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsMetered(boolean isMetered) {
- if (isMetered) {
- mMeteredOverride = WifiConfiguration.METERED_OVERRIDE_METERED;
- } else {
- mMeteredOverride = WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
- }
- return this;
- }
-
- /**
- * Specifies whether the network credentials provided with this suggestion can be used by
- * the user to explicitly (manually) connect to this network. If true this network will
- * appear in the Wi-Fi Picker (in Settings) and the user will be able to select and connect
- * to it with the provided credentials. If false, the user will need to enter network
- * credentials and the resulting configuration will become a user saved network.
- *
- *
Note: Only valid for secure (non-open) networks.
- * If not set, defaults to true (i.e. allow user to manually connect) for secure
- * networks and false for open networks.
- *
- * @param isShared {@code true} to indicate that the credentials may be used by the user to
- * manually connect to the network, {@code false} otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setCredentialSharedWithUser(boolean isShared) {
- mIsSharedWithUser = isShared;
- mIsSharedWithUserSet = true;
- return this;
- }
-
- /**
- * Specifies whether the suggestion is created with auto-join enabled or disabled. The
- * user may modify the auto-join configuration of a suggestion directly once the device
- * associates to the network.
- *
- * If auto-join is initialized as disabled the user may still be able to manually connect
- * to the network. Therefore, disabling auto-join only makes sense if
- * {@link #setCredentialSharedWithUser(boolean)} is set to true (the default) which
- * itself implies a secure (non-open) network.
- *
- * If not set, defaults to true (i.e. auto-join is initialized as enabled).
- *
- * @param enabled true for initializing with auto-join enabled (the default), false to
- * initializing with auto-join disabled.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsInitialAutojoinEnabled(boolean enabled) {
- mIsInitialAutojoinEnabled = enabled;
- return this;
- }
-
- /**
- * Specifies whether the system will bring up the network (if selected) as untrusted. An
- * untrusted network has its {@link NetworkCapabilities#NET_CAPABILITY_TRUSTED}
- * capability removed. The Wi-Fi network selection process may use this information to
- * influence priority of the suggested network for Wi-Fi network selection (most likely to
- * reduce it). The connectivity service may use this information to influence the overall
- * network configuration of the device.
- *
- *
These suggestions are only considered for network selection if a
- * {@link NetworkRequest} without {@link NetworkCapabilities#NET_CAPABILITY_TRUSTED}
- * capability is filed.
- * An untrusted network's credentials may not be shared with the user using
- * {@link #setCredentialSharedWithUser(boolean)}.
- * If not set, defaults to false (i.e. network is trusted).
- *
- * @param isUntrusted Boolean indicating whether the network should be brought up untrusted
- * (if true) or trusted (if false).
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setUntrusted(boolean isUntrusted) {
- mIsNetworkUntrusted = isUntrusted;
- return this;
- }
-
- /**
- * Specifies whether the system will bring up the network (if selected) as OEM paid. An
- * OEM paid network has {@link NetworkCapabilities#NET_CAPABILITY_OEM_PAID} capability
- * added.
- * Note:
- * The connectivity service may use this information to influence the overall
- * network configuration of the device. This network is typically only available to system
- * apps.
- * On devices which do not support concurrent connection (indicated via
- * {@link WifiManager#isMultiStaConcurrencySupported()}, Wi-Fi network selection process may
- * use this information to influence priority of the suggested network for Wi-Fi network
- * selection (most likely to reduce it).
- * On devices which support more than 1 concurrent connections (indicated via
- * {@link WifiManager#isMultiStaConcurrencySupported()}, these OEM paid networks will be
- * brought up as a secondary concurrent connection (primary connection will be used
- * for networks available to the user and all apps.
- *
- *
An OEM paid network's credentials may not be shared with the user using
- * {@link #setCredentialSharedWithUser(boolean)}.
- * These suggestions are only considered for network selection if a
- * {@link NetworkRequest} with {@link NetworkCapabilities#NET_CAPABILITY_OEM_PAID}
- * capability is filed.
- * Each suggestion can have both {@link #setOemPaid(boolean)} and
- * {@link #setOemPrivate(boolean)} set if the app wants these suggestions considered
- * for creating either an OEM paid network or OEM private network determined based on
- * the {@link NetworkRequest} that is active.
- * If not set, defaults to false (i.e. network is not OEM paid).
- *
- * @param isOemPaid Boolean indicating whether the network should be brought up as OEM paid
- * (if true) or not OEM paid (if false).
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @hide
- */
- @SystemApi
- public @NonNull Builder setOemPaid(boolean isOemPaid) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mIsNetworkOemPaid = isOemPaid;
- return this;
- }
-
- /**
- * Specifies whether the system will bring up the network (if selected) as OEM private. An
- * OEM private network has {@link NetworkCapabilities#NET_CAPABILITY_OEM_PRIVATE} capability
- * added.
- * Note:
- * The connectivity service may use this information to influence the overall
- * network configuration of the device. This network is typically only available to system
- * apps.
- * On devices which do not support concurrent connection (indicated via
- * {@link WifiManager#isMultiStaConcurrencySupported()}, Wi-Fi network selection process may
- * use this information to influence priority of the suggested network for Wi-Fi network
- * selection (most likely to reduce it).
- * On devices which support more than 1 concurrent connections (indicated via
- * {@link WifiManager#isMultiStaConcurrencySupported()}, these OEM private networks will be
- * brought up as a secondary concurrent connection (primary connection will be used
- * for networks available to the user and all apps.
- *
- *
An OEM private network's credentials may not be shared with the user using
- * {@link #setCredentialSharedWithUser(boolean)}.
- * These suggestions are only considered for network selection if a
- * {@link NetworkRequest} with {@link NetworkCapabilities#NET_CAPABILITY_OEM_PRIVATE}
- * capability is filed.
- * Each suggestion can have both {@link #setOemPaid(boolean)} and
- * {@link #setOemPrivate(boolean)} set if the app wants these suggestions considered
- * for creating either an OEM paid network or OEM private network determined based on
- * the {@link NetworkRequest} that is active.
- * If not set, defaults to false (i.e. network is not OEM private).
- *
- * @param isOemPrivate Boolean indicating whether the network should be brought up as OEM
- * private (if true) or not OEM private (if false).
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @hide
- */
- @SystemApi
- public @NonNull Builder setOemPrivate(boolean isOemPrivate) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mIsNetworkOemPrivate = isOemPrivate;
- return this;
- }
-
- /**
- * Specifies whether the suggestion represents a carrier merged network. A carrier merged
- * Wi-Fi network is treated as part of the mobile carrier network. Such configuration may
- * impact the user interface and data usage accounting.
- *
- *
A suggestion marked as carrier merged must be metered enterprise network with a valid
- * subscription Id set.
- * @see #setIsMetered(boolean)
- * @see #setSubscriptionId(int)
- * @see #setWpa2EnterpriseConfig(WifiEnterpriseConfig)
- * @see #setWpa3Enterprise192BitModeConfig(WifiEnterpriseConfig)
- * @see #setWpa3EnterpriseStandardModeConfig(WifiEnterpriseConfig)
- * @see #setPasspointConfig(PasspointConfiguration)
- *
- * If not set, defaults to false (i.e. not a carrier merged network.)
- *
- * @param isCarrierMerged Boolean indicating whether the network is treated a carrier
- * merged network (if true) or non-merged network (if false);
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setCarrierMerged(boolean isCarrierMerged) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mIsCarrierMerged = isCarrierMerged;
- return this;
- }
-
- private void setSecurityParamsInWifiConfiguration(
- @NonNull WifiConfiguration configuration) {
- if (!TextUtils.isEmpty(mWpa2PskPassphrase)) { // WPA-PSK network.
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_PSK);
- // WifiConfiguration.preSharedKey needs quotes around ASCII password.
- configuration.preSharedKey = "\"" + mWpa2PskPassphrase + "\"";
- } else if (!TextUtils.isEmpty(mWpa3SaePassphrase)) { // WPA3-SAE network.
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_SAE);
- // WifiConfiguration.preSharedKey needs quotes around ASCII password.
- configuration.preSharedKey = "\"" + mWpa3SaePassphrase + "\"";
- } else if (mWpa2EnterpriseConfig != null) { // WPA-EAP network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP);
- configuration.enterpriseConfig = mWpa2EnterpriseConfig;
- } else if (mWpa3EnterpriseConfig != null) { // WPA3-Enterprise
- if (mWpa3EnterpriseType == WPA3_ENTERPRISE_AUTO
- && mWpa3EnterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS
- && WifiEnterpriseConfig.isSuiteBCipherCert(
- mWpa3EnterpriseConfig.getClientCertificate())
- && WifiEnterpriseConfig.isSuiteBCipherCert(
- mWpa3EnterpriseConfig.getCaCertificate())) {
- // WPA3-Enterprise in 192-bit security mode
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT);
- } else if (mWpa3EnterpriseType == WPA3_ENTERPRISE_192_BIT) {
- // WPA3-Enterprise in 192-bit security mode
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT);
- } else {
- // WPA3-Enterprise
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE);
- }
- configuration.enterpriseConfig = mWpa3EnterpriseConfig;
- } else if (mIsEnhancedOpen) { // OWE network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OWE);
- } else if (!TextUtils.isEmpty(mWapiPskPassphrase)) { // WAPI-PSK network.
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_WAPI_PSK);
- // WifiConfiguration.preSharedKey needs quotes around ASCII password.
- configuration.preSharedKey = "\"" + mWapiPskPassphrase + "\"";
- } else if (mWapiEnterpriseConfig != null) { // WAPI-CERT network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_WAPI_CERT);
- configuration.enterpriseConfig = mWapiEnterpriseConfig;
- } else { // Open network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OPEN);
- }
- }
-
- /**
- * Helper method to build WifiConfiguration object from the builder.
- * @return Instance of {@link WifiConfiguration}.
- */
- private WifiConfiguration buildWifiConfiguration() {
- final WifiConfiguration wifiConfiguration = new WifiConfiguration();
- // WifiConfiguration.SSID needs quotes around unicode SSID.
- wifiConfiguration.SSID = "\"" + mSsid + "\"";
- if (mBssid != null) {
- wifiConfiguration.BSSID = mBssid.toString();
- }
-
- setSecurityParamsInWifiConfiguration(wifiConfiguration);
-
- wifiConfiguration.hiddenSSID = mIsHiddenSSID;
- wifiConfiguration.priority = mPriority;
- wifiConfiguration.meteredOverride = mMeteredOverride;
- wifiConfiguration.carrierId = mCarrierId;
- wifiConfiguration.trusted = !mIsNetworkUntrusted;
- wifiConfiguration.oemPaid = mIsNetworkOemPaid;
- wifiConfiguration.oemPrivate = mIsNetworkOemPrivate;
- wifiConfiguration.carrierMerged = mIsCarrierMerged;
- wifiConfiguration.macRandomizationSetting = mIsEnhancedMacRandomizationEnabled
- ? WifiConfiguration.RANDOMIZATION_ENHANCED
- : WifiConfiguration.RANDOMIZATION_PERSISTENT;
- wifiConfiguration.subscriptionId = mSubscriptionId;
- return wifiConfiguration;
- }
-
- private void validateSecurityParams() {
- int numSecurityTypes = 0;
- numSecurityTypes += mIsEnhancedOpen ? 1 : 0;
- numSecurityTypes += !TextUtils.isEmpty(mWpa2PskPassphrase) ? 1 : 0;
- numSecurityTypes += !TextUtils.isEmpty(mWpa3SaePassphrase) ? 1 : 0;
- numSecurityTypes += !TextUtils.isEmpty(mWapiPskPassphrase) ? 1 : 0;
- numSecurityTypes += mWpa2EnterpriseConfig != null ? 1 : 0;
- numSecurityTypes += mWpa3EnterpriseConfig != null ? 1 : 0;
- numSecurityTypes += mWapiEnterpriseConfig != null ? 1 : 0;
- numSecurityTypes += mPasspointConfiguration != null ? 1 : 0;
- if (numSecurityTypes > 1) {
- throw new IllegalStateException("only one of setIsEnhancedOpen, setWpa2Passphrase,"
- + " setWpa3Passphrase, setWpa2EnterpriseConfig, setWpa3EnterpriseConfig"
- + " setWapiPassphrase, setWapiCertSuite, setIsWapiCertSuiteAuto"
- + " or setPasspointConfig can be invoked for network suggestion");
- }
- }
-
- private WifiConfiguration buildWifiConfigurationForPasspoint() {
- WifiConfiguration wifiConfiguration = new WifiConfiguration();
- wifiConfiguration.FQDN = mPasspointConfiguration.getHomeSp().getFqdn();
- wifiConfiguration.setPasspointUniqueId(mPasspointConfiguration.getUniqueId());
- wifiConfiguration.priority = mPriority;
- wifiConfiguration.meteredOverride = mMeteredOverride;
- wifiConfiguration.trusted = !mIsNetworkUntrusted;
- wifiConfiguration.oemPaid = mIsNetworkOemPaid;
- wifiConfiguration.oemPrivate = mIsNetworkOemPrivate;
- wifiConfiguration.carrierMerged = mIsCarrierMerged;
- wifiConfiguration.subscriptionId = mSubscriptionId;
- mPasspointConfiguration.setCarrierId(mCarrierId);
- mPasspointConfiguration.setSubscriptionId(mSubscriptionId);
- mPasspointConfiguration.setMeteredOverride(wifiConfiguration.meteredOverride);
- mPasspointConfiguration.setOemPrivate(mIsNetworkOemPrivate);
- mPasspointConfiguration.setOemPaid(mIsNetworkOemPaid);
- mPasspointConfiguration.setCarrierMerged(mIsCarrierMerged);
- wifiConfiguration.macRandomizationSetting = mIsEnhancedMacRandomizationEnabled
- ? WifiConfiguration.RANDOMIZATION_ENHANCED
- : WifiConfiguration.RANDOMIZATION_PERSISTENT;
- return wifiConfiguration;
- }
-
- /**
- * Create a network suggestion object for use in
- * {@link WifiManager#addNetworkSuggestions(List)}.
- *
- *
- * Note: Apps can set a combination of SSID using {@link #setSsid(String)} and BSSID
- * using {@link #setBssid(MacAddress)} to provide more fine grained network suggestions to
- * the platform.
- *
- *
- * For example:
- * To provide credentials for one open, one WPA2, one WPA3 network with their
- * corresponding SSID's and one with Passpoint config:
- *
- * {@code
- * final WifiNetworkSuggestion suggestion1 =
- * new Builder()
- * .setSsid("test111111")
- * .build();
- * final WifiNetworkSuggestion suggestion2 =
- * new Builder()
- * .setSsid("test222222")
- * .setWpa2Passphrase("test123456")
- * .build();
- * final WifiNetworkSuggestion suggestion3 =
- * new Builder()
- * .setSsid("test333333")
- * .setWpa3Passphrase("test6789")
- * .build();
- * final PasspointConfiguration passpointConfig= new PasspointConfiguration();
- * // configure passpointConfig to include a valid Passpoint configuration
- * final WifiNetworkSuggestion suggestion4 =
- * new Builder()
- * .setPasspointConfig(passpointConfig)
- * .build();
- * final List suggestionsList =
- * new ArrayList { {
- * add(suggestion1);
- * add(suggestion2);
- * add(suggestion3);
- * add(suggestion4);
- * } };
- * final WifiManager wifiManager =
- * context.getSystemService(Context.WIFI_SERVICE);
- * wifiManager.addNetworkSuggestions(suggestionsList);
- * // ...
- * }
- *
- * @return Instance of {@link WifiNetworkSuggestion}
- * @throws IllegalStateException on invalid params set
- * @see WifiNetworkSuggestion
- */
- public @NonNull WifiNetworkSuggestion build() {
- validateSecurityParams();
- WifiConfiguration wifiConfiguration;
- if (mPasspointConfiguration != null) {
- if (mSsid != null) {
- throw new IllegalStateException("setSsid should not be invoked for suggestion "
- + "with Passpoint configuration");
- }
- if (mIsHiddenSSID) {
- throw new IllegalStateException("setIsHiddenSsid should not be invoked for "
- + "suggestion with Passpoint configuration");
- }
- wifiConfiguration = buildWifiConfigurationForPasspoint();
- mPasspointConfiguration.setEnhancedMacRandomizationEnabled(
- mIsEnhancedMacRandomizationEnabled);
- } else {
- if (mSsid == null) {
- throw new IllegalStateException("setSsid should be invoked for suggestion");
- }
- if (TextUtils.isEmpty(mSsid)) {
- throw new IllegalStateException("invalid ssid for suggestion");
- }
- if (mBssid != null
- && (mBssid.equals(MacAddress.BROADCAST_ADDRESS)
- || mBssid.equals(WifiManager.ALL_ZEROS_MAC_ADDRESS))) {
- throw new IllegalStateException("invalid bssid for suggestion");
- }
- wifiConfiguration = buildWifiConfiguration();
- if (wifiConfiguration.isOpenNetwork()) {
- if (mIsSharedWithUserSet && mIsSharedWithUser) {
- throw new IllegalStateException("Open network should not be "
- + "setCredentialSharedWithUser to true");
- }
- mIsSharedWithUser = false;
- }
- }
- if (!mIsSharedWithUser && !mIsInitialAutojoinEnabled) {
- throw new IllegalStateException("Should have not a network with both "
- + "setCredentialSharedWithUser and "
- + "setIsAutojoinEnabled set to false");
- }
- if (mIsNetworkUntrusted) {
- if (mIsSharedWithUserSet && mIsSharedWithUser) {
- throw new IllegalStateException("Should not be both"
- + "setCredentialSharedWithUser and +"
- + "setUntrusted to true");
- }
- mIsSharedWithUser = false;
- }
- if (mIsNetworkOemPaid) {
- if (mIsSharedWithUserSet && mIsSharedWithUser) {
- throw new IllegalStateException("Should not be both"
- + "setCredentialSharedWithUser and +"
- + "setOemPaid to true");
- }
- mIsSharedWithUser = false;
- }
- if (mIsNetworkOemPrivate) {
- if (mIsSharedWithUserSet && mIsSharedWithUser) {
- throw new IllegalStateException("Should not be both"
- + "setCredentialSharedWithUser and +"
- + "setOemPrivate to true");
- }
- mIsSharedWithUser = false;
- }
- if (mIsCarrierMerged) {
- if (mSubscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID
- || mMeteredOverride != WifiConfiguration.METERED_OVERRIDE_METERED
- || !isEnterpriseSuggestion()) {
- throw new IllegalStateException("A carrier merged network must be a metered, "
- + "enterprise network with valid subscription Id");
- }
- }
- return new WifiNetworkSuggestion(
- wifiConfiguration,
- mPasspointConfiguration,
- mIsAppInteractionRequired,
- mIsUserInteractionRequired,
- mIsSharedWithUser,
- mIsInitialAutojoinEnabled,
- mPriorityGroup);
- }
-
- private boolean isEnterpriseSuggestion() {
- return !(mWpa2EnterpriseConfig == null && mWpa3EnterpriseConfig == null
- && mWapiEnterpriseConfig == null && mPasspointConfiguration == null);
- }
- }
-
-
-
- /**
- * Network configuration for the provided network.
- * @hide
- */
- @NonNull
- public final WifiConfiguration wifiConfiguration;
-
- /**
- * Passpoint configuration for the provided network.
- * @hide
- */
- @Nullable
- public final PasspointConfiguration passpointConfiguration;
-
- /**
- * Whether app needs to log in to captive portal to obtain Internet access.
- * @hide
- */
- public final boolean isAppInteractionRequired;
-
- /**
- * Whether user needs to log in to captive portal to obtain Internet access.
- * @hide
- */
- public final boolean isUserInteractionRequired;
-
- /**
- * Whether app share credential with the user, allow user use provided credential to
- * connect network manually.
- * @hide
- */
- public final boolean isUserAllowedToManuallyConnect;
-
- /**
- * Whether the suggestion will be initialized as auto-joined or not.
- * @hide
- */
- public final boolean isInitialAutoJoinEnabled;
-
- /**
- * Priority group ID.
- * @hide
- */
- public final int priorityGroup;
-
- /** @hide */
- public WifiNetworkSuggestion() {
- this.wifiConfiguration = new WifiConfiguration();
- this.passpointConfiguration = null;
- this.isAppInteractionRequired = false;
- this.isUserInteractionRequired = false;
- this.isUserAllowedToManuallyConnect = true;
- this.isInitialAutoJoinEnabled = true;
- this.priorityGroup = 0;
- }
-
- /** @hide */
- public WifiNetworkSuggestion(@NonNull WifiConfiguration networkConfiguration,
- @Nullable PasspointConfiguration passpointConfiguration,
- boolean isAppInteractionRequired,
- boolean isUserInteractionRequired,
- boolean isUserAllowedToManuallyConnect,
- boolean isInitialAutoJoinEnabled, int priorityGroup) {
- checkNotNull(networkConfiguration);
- this.wifiConfiguration = networkConfiguration;
- this.passpointConfiguration = passpointConfiguration;
-
- this.isAppInteractionRequired = isAppInteractionRequired;
- this.isUserInteractionRequired = isUserInteractionRequired;
- this.isUserAllowedToManuallyConnect = isUserAllowedToManuallyConnect;
- this.isInitialAutoJoinEnabled = isInitialAutoJoinEnabled;
- this.priorityGroup = priorityGroup;
- }
-
- public static final @NonNull Creator CREATOR =
- new Creator() {
- @Override
- public WifiNetworkSuggestion createFromParcel(Parcel in) {
- return new WifiNetworkSuggestion(
- in.readParcelable(null), // wifiConfiguration
- in.readParcelable(null), // PasspointConfiguration
- in.readBoolean(), // isAppInteractionRequired
- in.readBoolean(), // isUserInteractionRequired
- in.readBoolean(), // isSharedCredentialWithUser
- in.readBoolean(), // isAutojoinEnabled
- in.readInt() // priorityGroup
- );
- }
-
- @Override
- public WifiNetworkSuggestion[] newArray(int size) {
- return new WifiNetworkSuggestion[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeParcelable(wifiConfiguration, flags);
- dest.writeParcelable(passpointConfiguration, flags);
- dest.writeBoolean(isAppInteractionRequired);
- dest.writeBoolean(isUserInteractionRequired);
- dest.writeBoolean(isUserAllowedToManuallyConnect);
- dest.writeBoolean(isInitialAutoJoinEnabled);
- dest.writeInt(priorityGroup);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(wifiConfiguration.SSID, wifiConfiguration.BSSID,
- wifiConfiguration.getDefaultSecurityType(),
- wifiConfiguration.getPasspointUniqueId(),
- wifiConfiguration.subscriptionId, wifiConfiguration.carrierId);
- }
-
- /**
- * Equals for network suggestions.
- */
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof WifiNetworkSuggestion)) {
- return false;
- }
- WifiNetworkSuggestion lhs = (WifiNetworkSuggestion) obj;
- if (this.passpointConfiguration == null ^ lhs.passpointConfiguration == null) {
- return false;
- }
-
- return TextUtils.equals(this.wifiConfiguration.SSID, lhs.wifiConfiguration.SSID)
- && TextUtils.equals(this.wifiConfiguration.BSSID, lhs.wifiConfiguration.BSSID)
- && TextUtils.equals(this.wifiConfiguration.getDefaultSecurityType(),
- lhs.wifiConfiguration.getDefaultSecurityType())
- && TextUtils.equals(this.wifiConfiguration.getPasspointUniqueId(),
- lhs.wifiConfiguration.getPasspointUniqueId())
- && this.wifiConfiguration.carrierId == lhs.wifiConfiguration.carrierId
- && this.wifiConfiguration.subscriptionId == lhs.wifiConfiguration.subscriptionId;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("WifiNetworkSuggestion[ ")
- .append("SSID=").append(wifiConfiguration.SSID)
- .append(", BSSID=").append(wifiConfiguration.BSSID)
- .append(", FQDN=").append(wifiConfiguration.FQDN)
- .append(", isAppInteractionRequired=").append(isAppInteractionRequired)
- .append(", isUserInteractionRequired=").append(isUserInteractionRequired)
- .append(", isCredentialSharedWithUser=").append(isUserAllowedToManuallyConnect)
- .append(", isInitialAutoJoinEnabled=").append(isInitialAutoJoinEnabled)
- .append(", isUnTrusted=").append(!wifiConfiguration.trusted)
- .append(", isOemPaid=").append(wifiConfiguration.oemPaid)
- .append(", isOemPrivate=").append(wifiConfiguration.oemPrivate)
- .append(", isCarrierMerged").append(wifiConfiguration.carrierMerged)
- .append(", priorityGroup=").append(priorityGroup)
- .append(" ]");
- return sb.toString();
- }
-
- /**
- * Get the {@link WifiConfiguration} associated with this Suggestion.
- * @hide
- */
- @SystemApi
- @NonNull
- public WifiConfiguration getWifiConfiguration() {
- return wifiConfiguration;
- }
-
- /**
- * Get the BSSID, or null if unset.
- * @see Builder#setBssid(MacAddress)
- */
- @Nullable
- public MacAddress getBssid() {
- if (wifiConfiguration.BSSID == null) {
- return null;
- }
- return MacAddress.fromString(wifiConfiguration.BSSID);
- }
-
- /** @see Builder#setCredentialSharedWithUser(boolean) */
- public boolean isCredentialSharedWithUser() {
- return isUserAllowedToManuallyConnect;
- }
-
- /** @see Builder#setIsAppInteractionRequired(boolean) */
- public boolean isAppInteractionRequired() {
- return isAppInteractionRequired;
- }
-
- /** @see Builder#setIsEnhancedOpen(boolean) */
- public boolean isEnhancedOpen() {
- return wifiConfiguration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.OWE);
- }
-
- /** @see Builder#setIsHiddenSsid(boolean) */
- public boolean isHiddenSsid() {
- return wifiConfiguration.hiddenSSID;
- }
-
- /** @see Builder#setIsInitialAutojoinEnabled(boolean) */
- public boolean isInitialAutojoinEnabled() {
- return isInitialAutoJoinEnabled;
- }
-
- /** @see Builder#setIsMetered(boolean) */
- public boolean isMetered() {
- return wifiConfiguration.meteredOverride == WifiConfiguration.METERED_OVERRIDE_METERED;
- }
-
- /** @see Builder#setIsUserInteractionRequired(boolean) */
- public boolean isUserInteractionRequired() {
- return isUserInteractionRequired;
- }
-
- /**
- * Get the {@link PasspointConfiguration} associated with this Suggestion, or null if this
- * Suggestion is not for a Passpoint network.
- */
- @Nullable
- public PasspointConfiguration getPasspointConfig() {
- return passpointConfiguration;
- }
-
- /** @see Builder#setPriority(int) */
- @IntRange(from = 0)
- public int getPriority() {
- return wifiConfiguration.priority;
- }
-
- /**
- * Return the SSID of the network, or null if this is a Passpoint network.
- * @see Builder#setSsid(String)
- */
- @Nullable
- public String getSsid() {
- if (wifiConfiguration.SSID == null) {
- return null;
- }
- return WifiInfo.sanitizeSsid(wifiConfiguration.SSID);
- }
-
- /** @see Builder#setUntrusted(boolean) */
- public boolean isUntrusted() {
- return !wifiConfiguration.trusted;
- }
-
- /**
- * @see Builder#setOemPaid(boolean)
- * @hide
- */
- @SystemApi
- public boolean isOemPaid() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return wifiConfiguration.oemPaid;
- }
-
- /**
- * @see Builder#setOemPrivate(boolean)
- * @hide
- */
- @SystemApi
- public boolean isOemPrivate() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return wifiConfiguration.oemPrivate;
- }
-
- /**
- * @see Builder#setCarrierMerged(boolean)
- */
- public boolean isCarrierMerged() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return wifiConfiguration.carrierMerged;
- }
-
- /**
- * Get the WifiEnterpriseConfig, or null if unset.
- * @see Builder#setWapiEnterpriseConfig(WifiEnterpriseConfig)
- * @see Builder#setWpa2EnterpriseConfig(WifiEnterpriseConfig)
- * @see Builder#setWpa3EnterpriseConfig(WifiEnterpriseConfig)
- */
- @Nullable
- public WifiEnterpriseConfig getEnterpriseConfig() {
- if (!wifiConfiguration.isEnterprise()) {
- return null;
- }
- return wifiConfiguration.enterpriseConfig;
- }
-
- /**
- * Get the passphrase, or null if unset.
- * @see Builder#setWapiPassphrase(String)
- * @see Builder#setWpa2Passphrase(String)
- * @see Builder#setWpa3Passphrase(String)
- */
- @Nullable
- public String getPassphrase() {
- if (wifiConfiguration.preSharedKey == null) {
- return null;
- }
- return WifiInfo.removeDoubleQuotes(wifiConfiguration.preSharedKey);
- }
-
- /**
- * @see Builder#setPriorityGroup(int)
- */
- public int getPriorityGroup() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return priorityGroup;
- }
-
- /**
- * @see Builder#setSubscriptionId(int)
- */
- public int getSubscriptionId() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return wifiConfiguration.subscriptionId;
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiScanner.java b/wifi/java/android/net/wifi/WifiScanner.java
deleted file mode 100644
index 7c051f0962c4e..0000000000000
--- a/wifi/java/android/net/wifi/WifiScanner.java
+++ /dev/null
@@ -1,1704 +0,0 @@
-/*
- * Copyright (C) 2008 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 android.net.wifi;
-
-import android.Manifest;
-import android.annotation.CallbackExecutor;
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
-import android.annotation.SuppressLint;
-import android.annotation.SystemApi;
-import android.annotation.SystemService;
-import android.content.Context;
-import android.os.Binder;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.os.Messenger;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.RemoteException;
-import android.os.WorkSource;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.SparseArray;
-
-import com.android.internal.util.AsyncChannel;
-import com.android.internal.util.Protocol;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Objects;
-import java.util.concurrent.Executor;
-
-/**
- * This class provides a way to scan the Wifi universe around the device
- * @hide
- */
-@SystemApi
-@SystemService(Context.WIFI_SCANNING_SERVICE)
-public class WifiScanner {
-
- /** @hide */
- public static final int WIFI_BAND_INDEX_24_GHZ = 0;
- /** @hide */
- public static final int WIFI_BAND_INDEX_5_GHZ = 1;
- /** @hide */
- public static final int WIFI_BAND_INDEX_5_GHZ_DFS_ONLY = 2;
- /** @hide */
- public static final int WIFI_BAND_INDEX_6_GHZ = 3;
- /** @hide */
- public static final int WIFI_BAND_INDEX_60_GHZ = 4;
- /** @hide */
- public static final int WIFI_BAND_COUNT = 5;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"WIFI_BAND_INDEX_"}, value = {
- WIFI_BAND_INDEX_24_GHZ,
- WIFI_BAND_INDEX_5_GHZ,
- WIFI_BAND_INDEX_5_GHZ_DFS_ONLY,
- WIFI_BAND_INDEX_6_GHZ,
- WIFI_BAND_INDEX_60_GHZ})
- public @interface WifiBandIndex {}
-
- /** no band specified; use channel list instead */
- public static final int WIFI_BAND_UNSPECIFIED = 0;
- /** 2.4 GHz band */
- public static final int WIFI_BAND_24_GHZ = 1 << WIFI_BAND_INDEX_24_GHZ;
- /** 5 GHz band excluding DFS channels */
- public static final int WIFI_BAND_5_GHZ = 1 << WIFI_BAND_INDEX_5_GHZ;
- /** DFS channels from 5 GHz band only */
- public static final int WIFI_BAND_5_GHZ_DFS_ONLY = 1 << WIFI_BAND_INDEX_5_GHZ_DFS_ONLY;
- /** 6 GHz band */
- public static final int WIFI_BAND_6_GHZ = 1 << WIFI_BAND_INDEX_6_GHZ;
- /** 60 GHz band */
- public static final int WIFI_BAND_60_GHZ = 1 << WIFI_BAND_INDEX_60_GHZ;
-
- /**
- * Combination of bands
- * Note that those are only the common band combinations,
- * other combinations can be created by combining any of the basic bands above
- */
- /** Both 2.4 GHz band and 5 GHz band; no DFS channels */
- public static final int WIFI_BAND_BOTH = WIFI_BAND_24_GHZ | WIFI_BAND_5_GHZ;
- /**
- * 2.4Ghz band + DFS channels from 5 GHz band only
- * @hide
- */
- public static final int WIFI_BAND_24_GHZ_WITH_5GHZ_DFS =
- WIFI_BAND_24_GHZ | WIFI_BAND_5_GHZ_DFS_ONLY;
- /** 5 GHz band including DFS channels */
- public static final int WIFI_BAND_5_GHZ_WITH_DFS = WIFI_BAND_5_GHZ | WIFI_BAND_5_GHZ_DFS_ONLY;
- /** Both 2.4 GHz band and 5 GHz band; with DFS channels */
- public static final int WIFI_BAND_BOTH_WITH_DFS =
- WIFI_BAND_24_GHZ | WIFI_BAND_5_GHZ | WIFI_BAND_5_GHZ_DFS_ONLY;
- /** 2.4 GHz band and 5 GHz band (no DFS channels) and 6 GHz */
- public static final int WIFI_BAND_24_5_6_GHZ = WIFI_BAND_BOTH | WIFI_BAND_6_GHZ;
- /** 2.4 GHz band and 5 GHz band; with DFS channels and 6 GHz */
- public static final int WIFI_BAND_24_5_WITH_DFS_6_GHZ =
- WIFI_BAND_BOTH_WITH_DFS | WIFI_BAND_6_GHZ;
- /** @hide */
- public static final int WIFI_BAND_24_5_6_60_GHZ =
- WIFI_BAND_24_5_6_GHZ | WIFI_BAND_60_GHZ;
- /** @hide */
- public static final int WIFI_BAND_24_5_WITH_DFS_6_60_GHZ =
- WIFI_BAND_24_5_6_60_GHZ | WIFI_BAND_5_GHZ_DFS_ONLY;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"WIFI_BAND_"}, value = {
- WIFI_BAND_UNSPECIFIED,
- WIFI_BAND_24_GHZ,
- WIFI_BAND_5_GHZ,
- WIFI_BAND_BOTH,
- WIFI_BAND_5_GHZ_DFS_ONLY,
- WIFI_BAND_24_GHZ_WITH_5GHZ_DFS,
- WIFI_BAND_5_GHZ_WITH_DFS,
- WIFI_BAND_BOTH_WITH_DFS,
- WIFI_BAND_6_GHZ,
- WIFI_BAND_24_5_6_GHZ,
- WIFI_BAND_24_5_WITH_DFS_6_GHZ,
- WIFI_BAND_60_GHZ,
- WIFI_BAND_24_5_6_60_GHZ,
- WIFI_BAND_24_5_WITH_DFS_6_60_GHZ})
- public @interface WifiBand {}
-
- /**
- * All bands
- * @hide
- */
- public static final int WIFI_BAND_ALL = (1 << WIFI_BAND_COUNT) - 1;
-
- /** Minimum supported scanning period */
- public static final int MIN_SCAN_PERIOD_MS = 1000;
- /** Maximum supported scanning period */
- public static final int MAX_SCAN_PERIOD_MS = 1024000;
-
- /** No Error */
- public static final int REASON_SUCCEEDED = 0;
- /** Unknown error */
- public static final int REASON_UNSPECIFIED = -1;
- /** Invalid listener */
- public static final int REASON_INVALID_LISTENER = -2;
- /** Invalid request */
- public static final int REASON_INVALID_REQUEST = -3;
- /** Invalid request */
- public static final int REASON_NOT_AUTHORIZED = -4;
- /** An outstanding request with the same listener hasn't finished yet. */
- public static final int REASON_DUPLICATE_REQEUST = -5;
-
- /** @hide */
- public static final String GET_AVAILABLE_CHANNELS_EXTRA = "Channels";
-
- /**
- * Generic action callback invocation interface
- * @hide
- */
- @SystemApi
- public static interface ActionListener {
- public void onSuccess();
- public void onFailure(int reason, String description);
- }
-
- /**
- * Test if scan is a full scan. i.e. scanning all available bands.
- * For backward compatibility, since some apps don't include 6GHz in their requests yet,
- * lacking 6GHz band does not cause the result to be false.
- *
- * @param bandScanned bands that are fully scanned
- * @param excludeDfs when true, DFS band is excluded from the check
- * @return true if all bands are scanned, false otherwise
- *
- * @hide
- */
- public static boolean isFullBandScan(@WifiBand int bandScanned, boolean excludeDfs) {
- return (bandScanned | WIFI_BAND_6_GHZ | WIFI_BAND_60_GHZ
- | (excludeDfs ? WIFI_BAND_5_GHZ_DFS_ONLY : 0))
- == WIFI_BAND_ALL;
- }
-
- /**
- * Returns a list of all the possible channels for the given band(s).
- *
- * @param band one of the WifiScanner#WIFI_BAND_* constants, e.g. {@link #WIFI_BAND_24_GHZ}
- * @return a list of all the frequencies, in MHz, for the given band(s) e.g. channel 1 is
- * 2412, or null if an error occurred.
- *
- * @hide
- */
- @SystemApi
- @NonNull
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public List getAvailableChannels(int band) {
- try {
- Bundle bundle = mService.getAvailableChannels(band, mContext.getOpPackageName(),
- mContext.getAttributionTag());
- List channels = bundle.getIntegerArrayList(GET_AVAILABLE_CHANNELS_EXTRA);
- return channels == null ? new ArrayList<>() : channels;
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * provides channel specification for scanning
- */
- public static class ChannelSpec {
- /**
- * channel frequency in MHz; for example channel 1 is specified as 2412
- */
- public int frequency;
- /**
- * if true, scan this channel in passive fashion.
- * This flag is ignored on DFS channel specification.
- * @hide
- */
- public boolean passive; /* ignored on DFS channels */
- /**
- * how long to dwell on this channel
- * @hide
- */
- public int dwellTimeMS; /* not supported for now */
-
- /**
- * default constructor for channel spec
- */
- public ChannelSpec(int frequency) {
- this.frequency = frequency;
- passive = false;
- dwellTimeMS = 0;
- }
- }
-
- /**
- * reports {@link ScanListener#onResults} when underlying buffers are full
- * this is simply the lack of the {@link #REPORT_EVENT_AFTER_EACH_SCAN} flag
- * @deprecated It is not supported anymore.
- */
- @Deprecated
- public static final int REPORT_EVENT_AFTER_BUFFER_FULL = 0;
- /**
- * reports {@link ScanListener#onResults} after each scan
- */
- public static final int REPORT_EVENT_AFTER_EACH_SCAN = (1 << 0);
- /**
- * reports {@link ScanListener#onFullResult} whenever each beacon is discovered
- */
- public static final int REPORT_EVENT_FULL_SCAN_RESULT = (1 << 1);
- /**
- * Do not place scans in the chip's scan history buffer
- */
- public static final int REPORT_EVENT_NO_BATCH = (1 << 2);
-
- /**
- * Optimize the scan for lower latency.
- * @see ScanSettings#type
- */
- public static final int SCAN_TYPE_LOW_LATENCY = 0;
- /**
- * Optimize the scan for lower power usage.
- * @see ScanSettings#type
- */
- public static final int SCAN_TYPE_LOW_POWER = 1;
- /**
- * Optimize the scan for higher accuracy.
- * @see ScanSettings#type
- */
- public static final int SCAN_TYPE_HIGH_ACCURACY = 2;
-
- /** {@hide} */
- public static final String SCAN_PARAMS_SCAN_SETTINGS_KEY = "ScanSettings";
- /** {@hide} */
- public static final String SCAN_PARAMS_WORK_SOURCE_KEY = "WorkSource";
- /** {@hide} */
- public static final String REQUEST_PACKAGE_NAME_KEY = "PackageName";
- /** {@hide} */
- public static final String REQUEST_FEATURE_ID_KEY = "FeatureId";
-
- /**
- * scan configuration parameters to be sent to {@link #startBackgroundScan}
- */
- public static class ScanSettings implements Parcelable {
- /** Hidden network to be scanned for. */
- public static class HiddenNetwork {
- /** SSID of the network */
- @NonNull
- public final String ssid;
-
- /** Default constructor for HiddenNetwork. */
- public HiddenNetwork(@NonNull String ssid) {
- this.ssid = ssid;
- }
- }
-
- /** one of the WIFI_BAND values */
- public int band;
- /** list of channels; used when band is set to WIFI_BAND_UNSPECIFIED */
- public ChannelSpec[] channels;
- /**
- * List of hidden networks to scan for. Explicit probe requests are sent out for such
- * networks during scan. Only valid for single scan requests.
- */
- @NonNull
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public final List hiddenNetworks = new ArrayList<>();
- /**
- * period of background scan; in millisecond, 0 => single shot scan
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int periodInMs;
- /**
- * must have a valid REPORT_EVENT value
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int reportEvents;
- /**
- * defines number of bssids to cache from each scan
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int numBssidsPerScan;
- /**
- * defines number of scans to cache; use it with REPORT_EVENT_AFTER_BUFFER_FULL
- * to wake up at fixed interval
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int maxScansToCache;
- /**
- * if maxPeriodInMs is non zero or different than period, then this bucket is
- * a truncated binary exponential backoff bucket and the scan period will grow
- * exponentially as per formula: actual_period(N) = period * (2 ^ (N/stepCount))
- * to maxPeriodInMs
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int maxPeriodInMs;
- /**
- * for truncated binary exponential back off bucket, number of scans to perform
- * for a given period
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int stepCount;
- /**
- * Flag to indicate if the scan settings are targeted for PNO scan.
- * {@hide}
- */
- public boolean isPnoScan;
- /**
- * Indicate the type of scan to be performed by the wifi chip.
- *
- * On devices with multiple hardware radio chains (and hence different modes of scan),
- * this type serves as an indication to the hardware on what mode of scan to perform.
- * Only apps holding {@link android.Manifest.permission.NETWORK_STACK} permission can set
- * this value.
- *
- * Note: This serves as an intent and not as a stipulation, the wifi chip
- * might honor or ignore the indication based on the current radio conditions. Always
- * use the {@link ScanResult#radioChainInfos} to figure out the radio chain configuration
- * used to receive the corresponding scan result.
- *
- * One of {@link #SCAN_TYPE_LOW_LATENCY}, {@link #SCAN_TYPE_LOW_POWER},
- * {@link #SCAN_TYPE_HIGH_ACCURACY}.
- * Default value: {@link #SCAN_TYPE_LOW_LATENCY}.
- */
- @WifiAnnotations.ScanType
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public int type = SCAN_TYPE_LOW_LATENCY;
- /**
- * This scan request may ignore location settings while receiving scans. This should only
- * be used in emergency situations.
- * {@hide}
- */
- @SystemApi
- public boolean ignoreLocationSettings;
- /**
- * This scan request will be hidden from app-ops noting for location information. This
- * should only be used by FLP/NLP module on the device which is using the scan results to
- * compute results for behalf on their clients. FLP/NLP module using this flag should ensure
- * that they note in app-ops the eventual delivery of location information computed using
- * these results to their client .
- * {@hide}
- */
- @SystemApi
- public boolean hideFromAppOps;
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(band);
- dest.writeInt(periodInMs);
- dest.writeInt(reportEvents);
- dest.writeInt(numBssidsPerScan);
- dest.writeInt(maxScansToCache);
- dest.writeInt(maxPeriodInMs);
- dest.writeInt(stepCount);
- dest.writeInt(isPnoScan ? 1 : 0);
- dest.writeInt(type);
- dest.writeInt(ignoreLocationSettings ? 1 : 0);
- dest.writeInt(hideFromAppOps ? 1 : 0);
- if (channels != null) {
- dest.writeInt(channels.length);
- for (int i = 0; i < channels.length; i++) {
- dest.writeInt(channels[i].frequency);
- dest.writeInt(channels[i].dwellTimeMS);
- dest.writeInt(channels[i].passive ? 1 : 0);
- }
- } else {
- dest.writeInt(0);
- }
- dest.writeInt(hiddenNetworks.size());
- for (HiddenNetwork hiddenNetwork : hiddenNetworks) {
- dest.writeString(hiddenNetwork.ssid);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator CREATOR =
- new Creator() {
- public ScanSettings createFromParcel(Parcel in) {
- ScanSettings settings = new ScanSettings();
- settings.band = in.readInt();
- settings.periodInMs = in.readInt();
- settings.reportEvents = in.readInt();
- settings.numBssidsPerScan = in.readInt();
- settings.maxScansToCache = in.readInt();
- settings.maxPeriodInMs = in.readInt();
- settings.stepCount = in.readInt();
- settings.isPnoScan = in.readInt() == 1;
- settings.type = in.readInt();
- settings.ignoreLocationSettings = in.readInt() == 1;
- settings.hideFromAppOps = in.readInt() == 1;
- int num_channels = in.readInt();
- settings.channels = new ChannelSpec[num_channels];
- for (int i = 0; i < num_channels; i++) {
- int frequency = in.readInt();
- ChannelSpec spec = new ChannelSpec(frequency);
- spec.dwellTimeMS = in.readInt();
- spec.passive = in.readInt() == 1;
- settings.channels[i] = spec;
- }
- int numNetworks = in.readInt();
- settings.hiddenNetworks.clear();
- for (int i = 0; i < numNetworks; i++) {
- String ssid = in.readString();
- settings.hiddenNetworks.add(new HiddenNetwork(ssid));
- }
- return settings;
- }
-
- public ScanSettings[] newArray(int size) {
- return new ScanSettings[size];
- }
- };
- }
-
- /**
- * all the information garnered from a single scan
- */
- public static class ScanData implements Parcelable {
- /** scan identifier */
- private int mId;
- /** additional information about scan
- * 0 => no special issues encountered in the scan
- * non-zero => scan was truncated, so results may not be complete
- */
- private int mFlags;
- /**
- * Indicates the buckets that were scanned to generate these results.
- * This is not relevant to WifiScanner API users and is used internally.
- * {@hide}
- */
- private int mBucketsScanned;
- /**
- * Bands scanned. One of the WIFI_BAND values.
- * Will be {@link #WIFI_BAND_UNSPECIFIED} if the list of channels do not fully cover
- * any of the bands.
- * {@hide}
- */
- private int mBandScanned;
- /** all scan results discovered in this scan, sorted by timestamp in ascending order */
- private final List mResults;
-
- ScanData() {
- mResults = new ArrayList<>();
- }
-
- public ScanData(int id, int flags, ScanResult[] results) {
- mId = id;
- mFlags = flags;
- mResults = new ArrayList<>(Arrays.asList(results));
- }
-
- /** {@hide} */
- public ScanData(int id, int flags, int bucketsScanned, int bandScanned,
- ScanResult[] results) {
- this(id, flags, bucketsScanned, bandScanned, new ArrayList<>(Arrays.asList(results)));
- }
-
- /** {@hide} */
- public ScanData(int id, int flags, int bucketsScanned, int bandScanned,
- List results) {
- mId = id;
- mFlags = flags;
- mBucketsScanned = bucketsScanned;
- mBandScanned = bandScanned;
- mResults = results;
- }
-
- public ScanData(ScanData s) {
- mId = s.mId;
- mFlags = s.mFlags;
- mBucketsScanned = s.mBucketsScanned;
- mBandScanned = s.mBandScanned;
- mResults = new ArrayList<>();
- for (ScanResult scanResult : s.mResults) {
- mResults.add(new ScanResult(scanResult));
- }
- }
-
- public int getId() {
- return mId;
- }
-
- public int getFlags() {
- return mFlags;
- }
-
- /** {@hide} */
- public int getBucketsScanned() {
- return mBucketsScanned;
- }
-
- /** {@hide} */
- public int getBandScanned() {
- return mBandScanned;
- }
-
- public ScanResult[] getResults() {
- return mResults.toArray(new ScanResult[0]);
- }
-
- /** {@hide} */
- public void addResults(@NonNull ScanResult[] newResults) {
- for (ScanResult result : newResults) {
- mResults.add(new ScanResult(result));
- }
- }
-
- /** {@hide} */
- public void addResults(@NonNull ScanData s) {
- mBandScanned |= s.mBandScanned;
- mFlags |= s.mFlags;
- addResults(s.getResults());
- }
-
- /** {@hide} */
- public boolean isFullBandScanResults() {
- return (mBandScanned & WifiScanner.WIFI_BAND_24_GHZ) != 0
- && (mBandScanned & WifiScanner.WIFI_BAND_5_GHZ) != 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mId);
- dest.writeInt(mFlags);
- dest.writeInt(mBucketsScanned);
- dest.writeInt(mBandScanned);
- dest.writeParcelableList(mResults, 0);
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator CREATOR =
- new Creator() {
- public ScanData createFromParcel(Parcel in) {
- int id = in.readInt();
- int flags = in.readInt();
- int bucketsScanned = in.readInt();
- int bandScanned = in.readInt();
- List results = new ArrayList<>();
- in.readParcelableList(results, ScanResult.class.getClassLoader());
- return new ScanData(id, flags, bucketsScanned, bandScanned, results);
- }
-
- public ScanData[] newArray(int size) {
- return new ScanData[size];
- }
- };
- }
-
- public static class ParcelableScanData implements Parcelable {
-
- public ScanData mResults[];
-
- public ParcelableScanData(ScanData[] results) {
- mResults = results;
- }
-
- public ScanData[] getResults() {
- return mResults;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- if (mResults != null) {
- dest.writeInt(mResults.length);
- for (int i = 0; i < mResults.length; i++) {
- ScanData result = mResults[i];
- result.writeToParcel(dest, flags);
- }
- } else {
- dest.writeInt(0);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator CREATOR =
- new Creator() {
- public ParcelableScanData createFromParcel(Parcel in) {
- int n = in.readInt();
- ScanData results[] = new ScanData[n];
- for (int i = 0; i < n; i++) {
- results[i] = ScanData.CREATOR.createFromParcel(in);
- }
- return new ParcelableScanData(results);
- }
-
- public ParcelableScanData[] newArray(int size) {
- return new ParcelableScanData[size];
- }
- };
- }
-
- public static class ParcelableScanResults implements Parcelable {
-
- public ScanResult mResults[];
-
- public ParcelableScanResults(ScanResult[] results) {
- mResults = results;
- }
-
- public ScanResult[] getResults() {
- return mResults;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- if (mResults != null) {
- dest.writeInt(mResults.length);
- for (int i = 0; i < mResults.length; i++) {
- ScanResult result = mResults[i];
- result.writeToParcel(dest, flags);
- }
- } else {
- dest.writeInt(0);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator CREATOR =
- new Creator() {
- public ParcelableScanResults createFromParcel(Parcel in) {
- int n = in.readInt();
- ScanResult results[] = new ScanResult[n];
- for (int i = 0; i < n; i++) {
- results[i] = ScanResult.CREATOR.createFromParcel(in);
- }
- return new ParcelableScanResults(results);
- }
-
- public ParcelableScanResults[] newArray(int size) {
- return new ParcelableScanResults[size];
- }
- };
- }
-
- /** {@hide} */
- public static final String PNO_PARAMS_PNO_SETTINGS_KEY = "PnoSettings";
- /** {@hide} */
- public static final String PNO_PARAMS_SCAN_SETTINGS_KEY = "ScanSettings";
- /**
- * PNO scan configuration parameters to be sent to {@link #startPnoScan}.
- * Note: This structure needs to be in sync with |wifi_epno_params| struct in gscan HAL API.
- * {@hide}
- */
- public static class PnoSettings implements Parcelable {
- /**
- * Pno network to be added to the PNO scan filtering.
- * {@hide}
- */
- public static class PnoNetwork {
- /*
- * Pno flags bitmask to be set in {@link #PnoNetwork.flags}
- */
- /** Whether directed scan needs to be performed (for hidden SSIDs) */
- public static final byte FLAG_DIRECTED_SCAN = (1 << 0);
- /** Whether PNO event shall be triggered if the network is found on A band */
- public static final byte FLAG_A_BAND = (1 << 1);
- /** Whether PNO event shall be triggered if the network is found on G band */
- public static final byte FLAG_G_BAND = (1 << 2);
- /**
- * Whether strict matching is required
- * If required then the firmware must store the network's SSID and not just a hash
- */
- public static final byte FLAG_STRICT_MATCH = (1 << 3);
- /**
- * If this SSID should be considered the same network as the currently connected
- * one for scoring.
- */
- public static final byte FLAG_SAME_NETWORK = (1 << 4);
-
- /*
- * Code for matching the beacon AUTH IE - additional codes. Bitmask to be set in
- * {@link #PnoNetwork.authBitField}
- */
- /** Open Network */
- public static final byte AUTH_CODE_OPEN = (1 << 0);
- /** WPA_PSK or WPA2PSK */
- public static final byte AUTH_CODE_PSK = (1 << 1);
- /** any EAPOL */
- public static final byte AUTH_CODE_EAPOL = (1 << 2);
-
- /** SSID of the network */
- public String ssid;
- /** Bitmask of the FLAG_XXX */
- public byte flags = 0;
- /** Bitmask of the ATUH_XXX */
- public byte authBitField = 0;
- /** frequencies on which the particular network needs to be scanned for */
- public int[] frequencies = {};
-
- /**
- * default constructor for PnoNetwork
- */
- public PnoNetwork(String ssid) {
- this.ssid = ssid;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(ssid, flags, authBitField);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof PnoNetwork)) {
- return false;
- }
- PnoNetwork lhs = (PnoNetwork) obj;
- return TextUtils.equals(this.ssid, lhs.ssid)
- && this.flags == lhs.flags
- && this.authBitField == lhs.authBitField;
- }
- }
-
- /** Connected vs Disconnected PNO flag {@hide} */
- public boolean isConnected;
- /** Minimum 5GHz RSSI for a BSSID to be considered */
- public int min5GHzRssi;
- /** Minimum 2.4GHz RSSI for a BSSID to be considered */
- public int min24GHzRssi;
- /** Minimum 6GHz RSSI for a BSSID to be considered */
- public int min6GHzRssi;
- /** Pno Network filter list */
- public PnoNetwork[] networkList;
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(isConnected ? 1 : 0);
- dest.writeInt(min5GHzRssi);
- dest.writeInt(min24GHzRssi);
- dest.writeInt(min6GHzRssi);
- if (networkList != null) {
- dest.writeInt(networkList.length);
- for (int i = 0; i < networkList.length; i++) {
- dest.writeString(networkList[i].ssid);
- dest.writeByte(networkList[i].flags);
- dest.writeByte(networkList[i].authBitField);
- dest.writeIntArray(networkList[i].frequencies);
- }
- } else {
- dest.writeInt(0);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator CREATOR =
- new Creator() {
- public PnoSettings createFromParcel(Parcel in) {
- PnoSettings settings = new PnoSettings();
- settings.isConnected = in.readInt() == 1;
- settings.min5GHzRssi = in.readInt();
- settings.min24GHzRssi = in.readInt();
- settings.min6GHzRssi = in.readInt();
- int numNetworks = in.readInt();
- settings.networkList = new PnoNetwork[numNetworks];
- for (int i = 0; i < numNetworks; i++) {
- String ssid = in.readString();
- PnoNetwork network = new PnoNetwork(ssid);
- network.flags = in.readByte();
- network.authBitField = in.readByte();
- network.frequencies = in.createIntArray();
- settings.networkList[i] = network;
- }
- return settings;
- }
-
- public PnoSettings[] newArray(int size) {
- return new PnoSettings[size];
- }
- };
-
- }
-
- /**
- * interface to get scan events on; specify this on {@link #startBackgroundScan} or
- * {@link #startScan}
- */
- public interface ScanListener extends ActionListener {
- /**
- * Framework co-ordinates scans across multiple apps; so it may not give exactly the
- * same period requested. If period of a scan is changed; it is reported by this event.
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public void onPeriodChanged(int periodInMs);
- /**
- * reports results retrieved from background scan and single shot scans
- */
- public void onResults(ScanData[] results);
- /**
- * reports full scan result for each access point found in scan
- */
- public void onFullResult(ScanResult fullScanResult);
- }
-
- /**
- * interface to get PNO scan events on; specify this on {@link #startDisconnectedPnoScan} and
- * {@link #startConnectedPnoScan}.
- * {@hide}
- */
- public interface PnoScanListener extends ScanListener {
- /**
- * Invoked when one of the PNO networks are found in scan results.
- */
- void onPnoNetworkFound(ScanResult[] results);
- }
-
- /**
- * Enable/Disable wifi scanning.
- *
- * @param enable set to true to enable scanning, set to false to disable all types of scanning.
- *
- * @see WifiManager#ACTION_WIFI_SCAN_AVAILABILITY_CHANGED
- * {@hide}
- */
- @SystemApi
- @RequiresPermission(Manifest.permission.NETWORK_STACK)
- public void setScanningEnabled(boolean enable) {
- validateChannel();
- mAsyncChannel.sendMessage(enable ? CMD_ENABLE : CMD_DISABLE);
- }
-
- /**
- * Register a listener that will receive results from all single scans.
- * Either the {@link ScanListener#onSuccess()} or {@link ScanListener#onFailure(int, String)}
- * method will be called once when the listener is registered.
- * Afterwards (assuming onSuccess was called), all subsequent single scan results will be
- * delivered to the listener. It is possible that onFullResult will not be called for all
- * results of the first scan if the listener was registered during the scan.
- *
- * @param executor the Executor on which to run the callback.
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this request, and must also be specified to cancel the request.
- * Multiple requests should also not share this object.
- */
- @RequiresPermission(Manifest.permission.NETWORK_STACK)
- public void registerScanListener(@NonNull @CallbackExecutor Executor executor,
- @NonNull ScanListener listener) {
- Objects.requireNonNull(executor, "executor cannot be null");
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = addListener(listener, executor);
- if (key == INVALID_KEY) return;
- validateChannel();
- mAsyncChannel.sendMessage(CMD_REGISTER_SCAN_LISTENER, 0, key);
- }
-
- /**
- * Overload of {@link #registerScanListener(Executor, ScanListener)} that executes the callback
- * synchronously.
- * @hide
- */
- @RequiresPermission(Manifest.permission.NETWORK_STACK)
- public void registerScanListener(@NonNull ScanListener listener) {
- registerScanListener(new SynchronousExecutor(), listener);
- }
-
- /**
- * Deregister a listener for ongoing single scans
- * @param listener specifies which scan to cancel; must be same object as passed in {@link
- * #registerScanListener}
- */
- public void unregisterScanListener(@NonNull ScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = removeListener(listener);
- if (key == INVALID_KEY) return;
- validateChannel();
- mAsyncChannel.sendMessage(CMD_DEREGISTER_SCAN_LISTENER, 0, key);
- }
-
- /** start wifi scan in background
- * @param settings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startBackgroundScan(ScanSettings settings, ScanListener listener) {
- startBackgroundScan(settings, listener, null);
- }
-
- /** start wifi scan in background
- * @param settings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param workSource WorkSource to blame for power usage
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- * @deprecated Background scan support has always been hardware vendor dependent. This support
- * may not be present on newer devices. Use {@link #startScan(ScanSettings, ScanListener)}
- * instead for single scans.
- */
- @Deprecated
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startBackgroundScan(ScanSettings settings, ScanListener listener,
- WorkSource workSource) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = addListener(listener);
- if (key == INVALID_KEY) return;
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putParcelable(SCAN_PARAMS_SCAN_SETTINGS_KEY, settings);
- scanParams.putParcelable(SCAN_PARAMS_WORK_SOURCE_KEY, workSource);
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- mAsyncChannel.sendMessage(CMD_START_BACKGROUND_SCAN, 0, key, scanParams);
- }
-
- /**
- * stop an ongoing wifi scan
- * @param listener specifies which scan to cancel; must be same object as passed in {@link
- * #startBackgroundScan}
- * @deprecated Background scan support has always been hardware vendor dependent. This support
- * may not be present on newer devices. Use {@link #startScan(ScanSettings, ScanListener)}
- * instead for single scans.
- */
- @Deprecated
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void stopBackgroundScan(ScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = removeListener(listener);
- if (key == INVALID_KEY) return;
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- mAsyncChannel.sendMessage(CMD_STOP_BACKGROUND_SCAN, 0, key, scanParams);
- }
-
- /**
- * reports currently available scan results on appropriate listeners
- * @return true if all scan results were reported correctly
- * @deprecated Background scan support has always been hardware vendor dependent. This support
- * may not be present on newer devices. Use {@link #startScan(ScanSettings, ScanListener)}
- * instead for single scans.
- */
- @Deprecated
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public boolean getScanResults() {
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- Message reply =
- mAsyncChannel.sendMessageSynchronously(CMD_GET_SCAN_RESULTS, 0, 0, scanParams);
- return reply.what == CMD_OP_SUCCEEDED;
- }
-
- /**
- * starts a single scan and reports results asynchronously
- * @param settings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startScan(ScanSettings settings, ScanListener listener) {
- startScan(settings, listener, null);
- }
-
- /**
- * starts a single scan and reports results asynchronously
- * @param settings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- * @param workSource WorkSource to blame for power usage
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startScan(ScanSettings settings, ScanListener listener, WorkSource workSource) {
- startScan(settings, null, listener, workSource);
- }
-
- /**
- * starts a single scan and reports results asynchronously
- * @param settings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param executor the Executor on which to run the callback.
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- * @param workSource WorkSource to blame for power usage
- * @hide
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startScan(ScanSettings settings, @Nullable @CallbackExecutor Executor executor,
- ScanListener listener, WorkSource workSource) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = addListener(listener, executor);
- if (key == INVALID_KEY) return;
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putParcelable(SCAN_PARAMS_SCAN_SETTINGS_KEY, settings);
- scanParams.putParcelable(SCAN_PARAMS_WORK_SOURCE_KEY, workSource);
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- mAsyncChannel.sendMessage(CMD_START_SINGLE_SCAN, 0, key, scanParams);
- }
-
- /**
- * stops an ongoing single shot scan; only useful after {@link #startScan} if onResults()
- * hasn't been called on the listener, ignored otherwise
- * @param listener
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void stopScan(ScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = removeListener(listener);
- if (key == INVALID_KEY) return;
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- mAsyncChannel.sendMessage(CMD_STOP_SINGLE_SCAN, 0, key, scanParams);
- }
-
- /**
- * Retrieve the most recent scan results from a single scan request.
- */
- @NonNull
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public List getSingleScanResults() {
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- Message reply = mAsyncChannel.sendMessageSynchronously(CMD_GET_SINGLE_SCAN_RESULTS, 0, 0,
- scanParams);
- if (reply.what == WifiScanner.CMD_OP_SUCCEEDED) {
- return Arrays.asList(((ParcelableScanResults) reply.obj).getResults());
- }
- OperationResult result = (OperationResult) reply.obj;
- Log.e(TAG, "Error retrieving SingleScan results reason: " + result.reason
- + " description: " + result.description);
- return new ArrayList<>();
- }
-
- private void startPnoScan(ScanSettings scanSettings, PnoSettings pnoSettings, int key) {
- // Bundle up both the settings and send it across.
- Bundle pnoParams = new Bundle();
- // Set the PNO scan flag.
- scanSettings.isPnoScan = true;
- pnoParams.putParcelable(PNO_PARAMS_SCAN_SETTINGS_KEY, scanSettings);
- pnoParams.putParcelable(PNO_PARAMS_PNO_SETTINGS_KEY, pnoSettings);
- mAsyncChannel.sendMessage(CMD_START_PNO_SCAN, 0, key, pnoParams);
- }
- /**
- * Start wifi connected PNO scan
- * @param scanSettings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param pnoSettings specifies various parameters for PNO; for more information look at
- * {@link PnoSettings}
- * @param executor the Executor on which to run the callback.
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- * {@hide}
- */
- public void startConnectedPnoScan(ScanSettings scanSettings, PnoSettings pnoSettings,
- @NonNull @CallbackExecutor Executor executor, PnoScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- Objects.requireNonNull(pnoSettings, "pnoSettings cannot be null");
- int key = addListener(listener, executor);
- if (key == INVALID_KEY) return;
- validateChannel();
- pnoSettings.isConnected = true;
- startPnoScan(scanSettings, pnoSettings, key);
- }
- /**
- * Start wifi disconnected PNO scan
- * @param scanSettings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param pnoSettings specifies various parameters for PNO; for more information look at
- * {@link PnoSettings}
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- * {@hide}
- */
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public void startDisconnectedPnoScan(ScanSettings scanSettings, PnoSettings pnoSettings,
- @NonNull @CallbackExecutor Executor executor, PnoScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- Objects.requireNonNull(pnoSettings, "pnoSettings cannot be null");
- int key = addListener(listener, executor);
- if (key == INVALID_KEY) return;
- validateChannel();
- pnoSettings.isConnected = false;
- startPnoScan(scanSettings, pnoSettings, key);
- }
- /**
- * Stop an ongoing wifi PNO scan
- * @param listener specifies which scan to cancel; must be same object as passed in {@link
- * #startPnoScan}
- * {@hide}
- */
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public void stopPnoScan(ScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = removeListener(listener);
- if (key == INVALID_KEY) return;
- validateChannel();
- mAsyncChannel.sendMessage(CMD_STOP_PNO_SCAN, 0, key);
- }
-
- /** specifies information about an access point of interest */
- @Deprecated
- public static class BssidInfo {
- /** bssid of the access point; in XX:XX:XX:XX:XX:XX format */
- public String bssid;
- /** low signal strength threshold; more information at {@link ScanResult#level} */
- public int low; /* minimum RSSI */
- /** high signal threshold; more information at {@link ScanResult#level} */
- public int high; /* maximum RSSI */
- /** channel frequency (in KHz) where you may find this BSSID */
- public int frequencyHint;
- }
-
- /** @hide */
- @SystemApi
- @Deprecated
- public static class WifiChangeSettings implements Parcelable {
- public int rssiSampleSize; /* sample size for RSSI averaging */
- public int lostApSampleSize; /* samples to confirm AP's loss */
- public int unchangedSampleSize; /* samples to confirm no change */
- public int minApsBreachingThreshold; /* change threshold to trigger event */
- public int periodInMs; /* scan period in millisecond */
- public BssidInfo[] bssidInfos;
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator CREATOR =
- new Creator() {
- public WifiChangeSettings createFromParcel(Parcel in) {
- return new WifiChangeSettings();
- }
-
- public WifiChangeSettings[] newArray(int size) {
- return new WifiChangeSettings[size];
- }
- };
-
- }
-
- /** configure WifiChange detection
- * @param rssiSampleSize number of samples used for RSSI averaging
- * @param lostApSampleSize number of samples to confirm an access point's loss
- * @param unchangedSampleSize number of samples to confirm there are no changes
- * @param minApsBreachingThreshold minimum number of access points that need to be
- * out of range to detect WifiChange
- * @param periodInMs indicates period of scan to find changes
- * @param bssidInfos access points to watch
- */
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void configureWifiChange(
- int rssiSampleSize, /* sample size for RSSI averaging */
- int lostApSampleSize, /* samples to confirm AP's loss */
- int unchangedSampleSize, /* samples to confirm no change */
- int minApsBreachingThreshold, /* change threshold to trigger event */
- int periodInMs, /* period of scan */
- BssidInfo[] bssidInfos /* signal thresholds to cross */
- )
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * interface to get wifi change events on; use this on {@link #startTrackingWifiChange}
- */
- @Deprecated
- public interface WifiChangeListener extends ActionListener {
- /** indicates that changes were detected in wifi environment
- * @param results indicate the access points that exhibited change
- */
- public void onChanging(ScanResult[] results); /* changes are found */
- /** indicates that no wifi changes are being detected for a while
- * @param results indicate the access points that are bing monitored for change
- */
- public void onQuiescence(ScanResult[] results); /* changes settled down */
- }
-
- /**
- * track changes in wifi environment
- * @param listener object to report events on; this object must be unique and must also be
- * provided on {@link #stopTrackingWifiChange}
- */
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void startTrackingWifiChange(WifiChangeListener listener) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * stop tracking changes in wifi environment
- * @param listener object that was provided to report events on {@link
- * #stopTrackingWifiChange}
- */
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void stopTrackingWifiChange(WifiChangeListener listener) {
- throw new UnsupportedOperationException();
- }
-
- /** @hide */
- @SystemApi
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void configureWifiChange(WifiChangeSettings settings) {
- throw new UnsupportedOperationException();
- }
-
- /** interface to receive hotlist events on; use this on {@link #setHotlist} */
- @Deprecated
- public static interface BssidListener extends ActionListener {
- /** indicates that access points were found by on going scans
- * @param results list of scan results, one for each access point visible currently
- */
- public void onFound(ScanResult[] results);
- /** indicates that access points were missed by on going scans
- * @param results list of scan results, for each access point that is not visible anymore
- */
- public void onLost(ScanResult[] results);
- }
-
- /** @hide */
- @SystemApi
- @Deprecated
- public static class HotlistSettings implements Parcelable {
- public BssidInfo[] bssidInfos;
- public int apLostThreshold;
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator CREATOR =
- new Creator() {
- public HotlistSettings createFromParcel(Parcel in) {
- HotlistSettings settings = new HotlistSettings();
- return settings;
- }
-
- public HotlistSettings[] newArray(int size) {
- return new HotlistSettings[size];
- }
- };
- }
-
- /**
- * set interesting access points to find
- * @param bssidInfos access points of interest
- * @param apLostThreshold number of scans needed to indicate that AP is lost
- * @param listener object provided to report events on; this object must be unique and must
- * also be provided on {@link #stopTrackingBssids}
- */
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void startTrackingBssids(BssidInfo[] bssidInfos,
- int apLostThreshold, BssidListener listener) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * remove tracking of interesting access points
- * @param listener same object provided in {@link #startTrackingBssids}
- */
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void stopTrackingBssids(BssidListener listener) {
- throw new UnsupportedOperationException();
- }
-
-
- /* private members and methods */
-
- private static final String TAG = "WifiScanner";
- private static final boolean DBG = false;
-
- /* commands for Wifi Service */
- private static final int BASE = Protocol.BASE_WIFI_SCANNER;
-
- /** @hide */
- public static final int CMD_START_BACKGROUND_SCAN = BASE + 2;
- /** @hide */
- public static final int CMD_STOP_BACKGROUND_SCAN = BASE + 3;
- /** @hide */
- public static final int CMD_GET_SCAN_RESULTS = BASE + 4;
- /** @hide */
- public static final int CMD_SCAN_RESULT = BASE + 5;
- /** @hide */
- public static final int CMD_OP_SUCCEEDED = BASE + 17;
- /** @hide */
- public static final int CMD_OP_FAILED = BASE + 18;
- /** @hide */
- public static final int CMD_FULL_SCAN_RESULT = BASE + 20;
- /** @hide */
- public static final int CMD_START_SINGLE_SCAN = BASE + 21;
- /** @hide */
- public static final int CMD_STOP_SINGLE_SCAN = BASE + 22;
- /** @hide */
- public static final int CMD_SINGLE_SCAN_COMPLETED = BASE + 23;
- /** @hide */
- public static final int CMD_START_PNO_SCAN = BASE + 24;
- /** @hide */
- public static final int CMD_STOP_PNO_SCAN = BASE + 25;
- /** @hide */
- public static final int CMD_PNO_NETWORK_FOUND = BASE + 26;
- /** @hide */
- public static final int CMD_REGISTER_SCAN_LISTENER = BASE + 27;
- /** @hide */
- public static final int CMD_DEREGISTER_SCAN_LISTENER = BASE + 28;
- /** @hide */
- public static final int CMD_GET_SINGLE_SCAN_RESULTS = BASE + 29;
- /** @hide */
- public static final int CMD_ENABLE = BASE + 30;
- /** @hide */
- public static final int CMD_DISABLE = BASE + 31;
-
- private Context mContext;
- private IWifiScanner mService;
-
- private static final int INVALID_KEY = 0;
- private int mListenerKey = 1;
-
- private final SparseArray mListenerMap = new SparseArray();
- private final SparseArray mExecutorMap = new SparseArray<>();
- private final Object mListenerMapLock = new Object();
-
- private AsyncChannel mAsyncChannel;
- private final Handler mInternalHandler;
-
- /**
- * Create a new WifiScanner instance.
- * Applications will almost always want to use
- * {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve
- * the standard {@link android.content.Context#WIFI_SERVICE Context.WIFI_SERVICE}.
- *
- * @param context the application context
- * @param service the Binder interface for {@link Context#WIFI_SCANNING_SERVICE}
- * @param looper the Looper used to deliver callbacks
- *
- * @hide
- */
- public WifiScanner(@NonNull Context context, @NonNull IWifiScanner service,
- @NonNull Looper looper) {
- mContext = context;
- mService = service;
-
- Messenger messenger = null;
- try {
- messenger = mService.getMessenger();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
-
- if (messenger == null) {
- throw new IllegalStateException("getMessenger() returned null! This is invalid.");
- }
-
- mAsyncChannel = new AsyncChannel();
-
- mInternalHandler = new ServiceHandler(looper);
- mAsyncChannel.connectSync(mContext, mInternalHandler, messenger);
- // We cannot use fullyConnectSync because it sends the FULL_CONNECTION message
- // synchronously, which causes WifiScanningService to receive the wrong replyTo value.
- mAsyncChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
- }
-
- private void validateChannel() {
- if (mAsyncChannel == null) throw new IllegalStateException(
- "No permission to access and change wifi or a bad initialization");
- }
-
- private int addListener(ActionListener listener) {
- return addListener(listener, null);
- }
-
- // Add a listener into listener map. If the listener already exists, return INVALID_KEY and
- // send an error message to internal handler; Otherwise add the listener to the listener map and
- // return the key of the listener.
- private int addListener(ActionListener listener, Executor executor) {
- synchronized (mListenerMapLock) {
- boolean keyExists = (getListenerKey(listener) != INVALID_KEY);
- // Note we need to put the listener into listener map even if it's a duplicate as the
- // internal handler will need the key to find the listener. In case of duplicates,
- // removing duplicate key logic will be handled in internal handler.
- int key = putListener(listener);
- if (keyExists) {
- if (DBG) Log.d(TAG, "listener key already exists");
- OperationResult operationResult = new OperationResult(REASON_DUPLICATE_REQEUST,
- "Outstanding request with same key not stopped yet");
- Message message = Message.obtain(mInternalHandler, CMD_OP_FAILED, 0, key,
- operationResult);
- message.sendToTarget();
- return INVALID_KEY;
- } else {
- mExecutorMap.put(key, executor);
- return key;
- }
- }
- }
-
- private int putListener(Object listener) {
- if (listener == null) return INVALID_KEY;
- int key;
- synchronized (mListenerMapLock) {
- do {
- key = mListenerKey++;
- } while (key == INVALID_KEY);
- mListenerMap.put(key, listener);
- }
- return key;
- }
-
- private static class ListenerWithExecutor {
- @Nullable final Object mListener;
- @Nullable final Executor mExecutor;
-
- ListenerWithExecutor(@Nullable Object listener, @Nullable Executor executor) {
- mListener = listener;
- mExecutor = executor;
- }
- }
-
- private ListenerWithExecutor getListenerWithExecutor(int key) {
- if (key == INVALID_KEY) return new ListenerWithExecutor(null, null);
- synchronized (mListenerMapLock) {
- Object listener = mListenerMap.get(key);
- Executor executor = mExecutorMap.get(key);
- return new ListenerWithExecutor(listener, executor);
- }
- }
-
- private int getListenerKey(Object listener) {
- if (listener == null) return INVALID_KEY;
- synchronized (mListenerMapLock) {
- int index = mListenerMap.indexOfValue(listener);
- if (index == -1) {
- return INVALID_KEY;
- } else {
- return mListenerMap.keyAt(index);
- }
- }
- }
-
- private Object removeListener(int key) {
- if (key == INVALID_KEY) return null;
- synchronized (mListenerMapLock) {
- Object listener = mListenerMap.get(key);
- mListenerMap.remove(key);
- mExecutorMap.remove(key);
- return listener;
- }
- }
-
- private int removeListener(Object listener) {
- int key = getListenerKey(listener);
- if (key == INVALID_KEY) {
- Log.e(TAG, "listener cannot be found");
- return key;
- }
- synchronized (mListenerMapLock) {
- mListenerMap.remove(key);
- mExecutorMap.remove(key);
- return key;
- }
- }
-
- /** @hide */
- public static class OperationResult implements Parcelable {
- public int reason;
- public String description;
-
- public OperationResult(int reason, String description) {
- this.reason = reason;
- this.description = description;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(reason);
- dest.writeString(description);
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator CREATOR =
- new Creator() {
- public OperationResult createFromParcel(Parcel in) {
- int reason = in.readInt();
- String description = in.readString();
- return new OperationResult(reason, description);
- }
-
- public OperationResult[] newArray(int size) {
- return new OperationResult[size];
- }
- };
- }
-
- private class ServiceHandler extends Handler {
- ServiceHandler(Looper looper) {
- super(looper);
- }
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED:
- return;
- case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
- Log.e(TAG, "Channel connection lost");
- // This will cause all further async API calls on the WifiManager
- // to fail and throw an exception
- mAsyncChannel = null;
- getLooper().quit();
- return;
- }
-
- ListenerWithExecutor listenerWithExecutor = getListenerWithExecutor(msg.arg2);
- Object listener = listenerWithExecutor.mListener;
-
- if (listener == null) {
- if (DBG) Log.d(TAG, "invalid listener key = " + msg.arg2);
- return;
- } else {
- if (DBG) Log.d(TAG, "listener key = " + msg.arg2);
- }
-
- Executor executor = listenerWithExecutor.mExecutor;
- if (executor == null) {
- executor = new SynchronousExecutor();
- }
-
- switch (msg.what) {
- /* ActionListeners grouped together */
- case CMD_OP_SUCCEEDED: {
- ActionListener actionListener = (ActionListener) listener;
- Binder.clearCallingIdentity();
- executor.execute(actionListener::onSuccess);
- } break;
- case CMD_OP_FAILED: {
- OperationResult result = (OperationResult) msg.obj;
- ActionListener actionListener = (ActionListener) listener;
- removeListener(msg.arg2);
- Binder.clearCallingIdentity();
- executor.execute(() ->
- actionListener.onFailure(result.reason, result.description));
- } break;
- case CMD_SCAN_RESULT: {
- ScanListener scanListener = (ScanListener) listener;
- ParcelableScanData parcelableScanData = (ParcelableScanData) msg.obj;
- Binder.clearCallingIdentity();
- executor.execute(() -> scanListener.onResults(parcelableScanData.getResults()));
- } break;
- case CMD_FULL_SCAN_RESULT: {
- ScanResult result = (ScanResult) msg.obj;
- ScanListener scanListener = ((ScanListener) listener);
- Binder.clearCallingIdentity();
- executor.execute(() -> scanListener.onFullResult(result));
- } break;
- case CMD_SINGLE_SCAN_COMPLETED: {
- if (DBG) Log.d(TAG, "removing listener for single scan");
- removeListener(msg.arg2);
- } break;
- case CMD_PNO_NETWORK_FOUND: {
- PnoScanListener pnoScanListener = (PnoScanListener) listener;
- ParcelableScanResults parcelableScanResults = (ParcelableScanResults) msg.obj;
- Binder.clearCallingIdentity();
- executor.execute(() ->
- pnoScanListener.onPnoNetworkFound(parcelableScanResults.getResults()));
- } break;
- default: {
- if (DBG) Log.d(TAG, "Ignoring message " + msg.what);
- } break;
- }
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiSsid.java b/wifi/java/android/net/wifi/WifiSsid.java
deleted file mode 100644
index 704ae81f71aab..0000000000000
--- a/wifi/java/android/net/wifi/WifiSsid.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * Copyright (C) 2012 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 android.net.wifi;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.io.ByteArrayOutputStream;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CoderResult;
-import java.nio.charset.CodingErrorAction;
-import java.util.Arrays;
-import java.util.Locale;
-
-/**
- * Stores SSID octets and handles conversion.
- *
- * For Ascii encoded string, any octet < 32 or > 127 is encoded as
- * a "\x" followed by the hex representation of the octet.
- * Exception chars are ", \, \e, \n, \r, \t which are escaped by a \
- * See src/utils/common.c for the implementation in the supplicant.
- *
- * @hide
- */
-public final class WifiSsid implements Parcelable {
- private static final String TAG = "WifiSsid";
-
- @UnsupportedAppUsage
- public final ByteArrayOutputStream octets = new ByteArrayOutputStream(32);
-
- private static final int HEX_RADIX = 16;
-
- @UnsupportedAppUsage
- public static final String NONE = WifiManager.UNKNOWN_SSID;
-
- private WifiSsid() {
- }
-
- /**
- * Create a WifiSsid from a raw byte array. If the byte array is null, return an empty WifiSsid
- * object.
- */
- @NonNull
- public static WifiSsid createFromByteArray(@Nullable byte[] ssid) {
- WifiSsid wifiSsid = new WifiSsid();
- if (ssid != null) {
- wifiSsid.octets.write(ssid, 0 /* the start offset */, ssid.length);
- }
- return wifiSsid;
- }
-
- @UnsupportedAppUsage
- public static WifiSsid createFromAsciiEncoded(String asciiEncoded) {
- WifiSsid a = new WifiSsid();
- a.convertToBytes(asciiEncoded);
- return a;
- }
-
- public static WifiSsid createFromHex(String hexStr) {
- WifiSsid a = new WifiSsid();
- if (hexStr == null) return a;
-
- if (hexStr.startsWith("0x") || hexStr.startsWith("0X")) {
- hexStr = hexStr.substring(2);
- }
-
- for (int i = 0; i < hexStr.length()-1; i += 2) {
- int val;
- try {
- val = Integer.parseInt(hexStr.substring(i, i + 2), HEX_RADIX);
- } catch(NumberFormatException e) {
- val = 0;
- }
- a.octets.write(val);
- }
- return a;
- }
-
- /* This function is equivalent to printf_decode() at src/utils/common.c in
- * the supplicant */
- private void convertToBytes(String asciiEncoded) {
- int i = 0;
- int val = 0;
- while (i< asciiEncoded.length()) {
- char c = asciiEncoded.charAt(i);
- switch (c) {
- case '\\':
- i++;
- switch(asciiEncoded.charAt(i)) {
- case '\\':
- octets.write('\\');
- i++;
- break;
- case '"':
- octets.write('"');
- i++;
- break;
- case 'n':
- octets.write('\n');
- i++;
- break;
- case 'r':
- octets.write('\r');
- i++;
- break;
- case 't':
- octets.write('\t');
- i++;
- break;
- case 'e':
- octets.write(27); //escape char
- i++;
- break;
- case 'x':
- i++;
- try {
- val = Integer.parseInt(asciiEncoded.substring(i, i + 2), HEX_RADIX);
- } catch (NumberFormatException e) {
- val = -1;
- } catch (StringIndexOutOfBoundsException e) {
- val = -1;
- }
- if (val < 0) {
- val = Character.digit(asciiEncoded.charAt(i), HEX_RADIX);
- if (val < 0) break;
- octets.write(val);
- i++;
- } else {
- octets.write(val);
- i += 2;
- }
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- val = asciiEncoded.charAt(i) - '0';
- i++;
- if (asciiEncoded.charAt(i) >= '0' && asciiEncoded.charAt(i) <= '7') {
- val = val * 8 + asciiEncoded.charAt(i) - '0';
- i++;
- }
- if (asciiEncoded.charAt(i) >= '0' && asciiEncoded.charAt(i) <= '7') {
- val = val * 8 + asciiEncoded.charAt(i) - '0';
- i++;
- }
- octets.write(val);
- break;
- default:
- break;
- }
- break;
- default:
- octets.write(c);
- i++;
- break;
- }
- }
- }
-
- /**
- * Converts this SSID to an unquoted UTF-8 String representation.
- * @return the SSID string, or {@link WifiManager#UNKNOWN_SSID} if there was an error.
- */
- @Override
- public String toString() {
- byte[] ssidBytes = octets.toByteArray();
- // Supplicant returns \x00\x00\x00\x00\x00\x00\x00\x00 hex string
- // for a hidden access point. Make sure we maintain the previous
- // behavior of returning empty string for this case.
- if (octets.size() <= 0 || isArrayAllZeroes(ssidBytes)) return "";
- // TODO: Handle conversion to other charsets upon failure
- Charset charset = Charset.forName("UTF-8");
- CharsetDecoder decoder = charset.newDecoder()
- .onMalformedInput(CodingErrorAction.REPLACE)
- .onUnmappableCharacter(CodingErrorAction.REPLACE);
- CharBuffer out = CharBuffer.allocate(32);
-
- CoderResult result = decoder.decode(ByteBuffer.wrap(ssidBytes), out, true);
- out.flip();
- if (result.isError()) {
- return WifiManager.UNKNOWN_SSID;
- }
- return out.toString();
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof WifiSsid)) {
- return false;
- }
- WifiSsid that = (WifiSsid) thatObject;
- return Arrays.equals(octets.toByteArray(), that.octets.toByteArray());
- }
-
- @Override
- public int hashCode() {
- return Arrays.hashCode(octets.toByteArray());
- }
-
- private boolean isArrayAllZeroes(byte[] ssidBytes) {
- for (int i = 0; i< ssidBytes.length; i++) {
- if (ssidBytes[i] != 0) return false;
- }
- return true;
- }
-
- /** @hide */
- public boolean isHidden() {
- return isArrayAllZeroes(octets.toByteArray());
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public byte[] getOctets() {
- return octets.toByteArray();
- }
-
- /** @hide */
- public String getHexString() {
- String out = "0x";
- byte[] ssidbytes = getOctets();
- for (int i = 0; i < octets.size(); i++) {
- out += String.format(Locale.US, "%02x", ssidbytes[i]);
- }
- return (octets.size() > 0) ? out : null;
- }
-
- /** Implement the Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface */
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeInt(octets.size());
- dest.writeByteArray(octets.toByteArray());
- }
-
- /** Implement the Parcelable interface */
- @UnsupportedAppUsage
- public static final @NonNull Creator CREATOR =
- new Creator() {
- @Override
- public WifiSsid createFromParcel(Parcel in) {
- WifiSsid ssid = new WifiSsid();
- int length = in.readInt();
- byte[] b = new byte[length];
- in.readByteArray(b);
- ssid.octets.write(b, 0, length);
- return ssid;
- }
-
- @Override
- public WifiSsid[] newArray(int size) {
- return new WifiSsid[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java b/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
deleted file mode 100644
index 8f3635fd2f04e..0000000000000
--- a/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
+++ /dev/null
@@ -1,351 +0,0 @@
-/*
- * 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 android.net.wifi;
-
-import android.annotation.IntDef;
-import android.annotation.SystemApi;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import android.telephony.Annotation.NetworkType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-/**
- * This class makes a subset of
- * com.android.server.wifi.nano.WifiMetricsProto.WifiUsabilityStatsEntry parcelable.
- *
- * @hide
- */
-@SystemApi
-public final class WifiUsabilityStatsEntry implements Parcelable {
- /** {@hide} */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"PROBE_STATUS_"}, value = {
- PROBE_STATUS_UNKNOWN,
- PROBE_STATUS_NO_PROBE,
- PROBE_STATUS_SUCCESS,
- PROBE_STATUS_FAILURE})
- public @interface ProbeStatus {}
-
- /** Link probe status is unknown */
- public static final int PROBE_STATUS_UNKNOWN = 0;
- /** Link probe is not triggered */
- public static final int PROBE_STATUS_NO_PROBE = 1;
- /** Link probe is triggered and the result is success */
- public static final int PROBE_STATUS_SUCCESS = 2;
- /** Link probe is triggered and the result is failure */
- public static final int PROBE_STATUS_FAILURE = 3;
-
- /** Absolute milliseconds from device boot when these stats were sampled */
- private final long mTimeStampMillis;
- /** The RSSI (in dBm) at the sample time */
- private final int mRssi;
- /** Link speed at the sample time in Mbps */
- private final int mLinkSpeedMbps;
- /** The total number of tx success counted from the last radio chip reset */
- private final long mTotalTxSuccess;
- /** The total number of MPDU data packet retries counted from the last radio chip reset */
- private final long mTotalTxRetries;
- /** The total number of tx bad counted from the last radio chip reset */
- private final long mTotalTxBad;
- /** The total number of rx success counted from the last radio chip reset */
- private final long mTotalRxSuccess;
- /** The total time the wifi radio is on in ms counted from the last radio chip reset */
- private final long mTotalRadioOnTimeMillis;
- /** The total time the wifi radio is doing tx in ms counted from the last radio chip reset */
- private final long mTotalRadioTxTimeMillis;
- /** The total time the wifi radio is doing rx in ms counted from the last radio chip reset */
- private final long mTotalRadioRxTimeMillis;
- /** The total time spent on all types of scans in ms counted from the last radio chip reset */
- private final long mTotalScanTimeMillis;
- /** The total time spent on nan scans in ms counted from the last radio chip reset */
- private final long mTotalNanScanTimeMillis;
- /** The total time spent on background scans in ms counted from the last radio chip reset */
- private final long mTotalBackgroundScanTimeMillis;
- /** The total time spent on roam scans in ms counted from the last radio chip reset */
- private final long mTotalRoamScanTimeMillis;
- /** The total time spent on pno scans in ms counted from the last radio chip reset */
- private final long mTotalPnoScanTimeMillis;
- /** The total time spent on hotspot2.0 scans and GAS exchange in ms counted from the last radio
- * chip reset */
- private final long mTotalHotspot2ScanTimeMillis;
- /** The total time CCA is on busy status on the current frequency in ms counted from the last
- * radio chip reset */
- private final long mTotalCcaBusyFreqTimeMillis;
- /** The total radio on time on the current frequency from the last radio chip reset */
- private final long mTotalRadioOnFreqTimeMillis;
- /** The total number of beacons received from the last radio chip reset */
- private final long mTotalBeaconRx;
- /** The status of link probe since last stats update */
- @ProbeStatus private final int mProbeStatusSinceLastUpdate;
- /** The elapsed time of the most recent link probe since last stats update */
- private final int mProbeElapsedTimeSinceLastUpdateMillis;
- /** The MCS rate of the most recent link probe since last stats update */
- private final int mProbeMcsRateSinceLastUpdate;
- /** Rx link speed at the sample time in Mbps */
- private final int mRxLinkSpeedMbps;
- private final @NetworkType int mCellularDataNetworkType;
- private final int mCellularSignalStrengthDbm;
- private final int mCellularSignalStrengthDb;
- private final boolean mIsSameRegisteredCell;
-
- /** Constructor function {@hide} */
- public WifiUsabilityStatsEntry(long timeStampMillis, int rssi, int linkSpeedMbps,
- long totalTxSuccess, long totalTxRetries, long totalTxBad, long totalRxSuccess,
- long totalRadioOnTimeMillis, long totalRadioTxTimeMillis, long totalRadioRxTimeMillis,
- long totalScanTimeMillis, long totalNanScanTimeMillis,
- long totalBackgroundScanTimeMillis,
- long totalRoamScanTimeMillis, long totalPnoScanTimeMillis,
- long totalHotspot2ScanTimeMillis,
- long totalCcaBusyFreqTimeMillis, long totalRadioOnFreqTimeMillis, long totalBeaconRx,
- @ProbeStatus int probeStatusSinceLastUpdate, int probeElapsedTimeSinceLastUpdateMillis,
- int probeMcsRateSinceLastUpdate, int rxLinkSpeedMbps,
- @NetworkType int cellularDataNetworkType,
- int cellularSignalStrengthDbm, int cellularSignalStrengthDb,
- boolean isSameRegisteredCell) {
- mTimeStampMillis = timeStampMillis;
- mRssi = rssi;
- mLinkSpeedMbps = linkSpeedMbps;
- mTotalTxSuccess = totalTxSuccess;
- mTotalTxRetries = totalTxRetries;
- mTotalTxBad = totalTxBad;
- mTotalRxSuccess = totalRxSuccess;
- mTotalRadioOnTimeMillis = totalRadioOnTimeMillis;
- mTotalRadioTxTimeMillis = totalRadioTxTimeMillis;
- mTotalRadioRxTimeMillis = totalRadioRxTimeMillis;
- mTotalScanTimeMillis = totalScanTimeMillis;
- mTotalNanScanTimeMillis = totalNanScanTimeMillis;
- mTotalBackgroundScanTimeMillis = totalBackgroundScanTimeMillis;
- mTotalRoamScanTimeMillis = totalRoamScanTimeMillis;
- mTotalPnoScanTimeMillis = totalPnoScanTimeMillis;
- mTotalHotspot2ScanTimeMillis = totalHotspot2ScanTimeMillis;
- mTotalCcaBusyFreqTimeMillis = totalCcaBusyFreqTimeMillis;
- mTotalRadioOnFreqTimeMillis = totalRadioOnFreqTimeMillis;
- mTotalBeaconRx = totalBeaconRx;
- mProbeStatusSinceLastUpdate = probeStatusSinceLastUpdate;
- mProbeElapsedTimeSinceLastUpdateMillis = probeElapsedTimeSinceLastUpdateMillis;
- mProbeMcsRateSinceLastUpdate = probeMcsRateSinceLastUpdate;
- mRxLinkSpeedMbps = rxLinkSpeedMbps;
- mCellularDataNetworkType = cellularDataNetworkType;
- mCellularSignalStrengthDbm = cellularSignalStrengthDbm;
- mCellularSignalStrengthDb = cellularSignalStrengthDb;
- mIsSameRegisteredCell = isSameRegisteredCell;
- }
-
- /** Implement the Parcelable interface */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeLong(mTimeStampMillis);
- dest.writeInt(mRssi);
- dest.writeInt(mLinkSpeedMbps);
- dest.writeLong(mTotalTxSuccess);
- dest.writeLong(mTotalTxRetries);
- dest.writeLong(mTotalTxBad);
- dest.writeLong(mTotalRxSuccess);
- dest.writeLong(mTotalRadioOnTimeMillis);
- dest.writeLong(mTotalRadioTxTimeMillis);
- dest.writeLong(mTotalRadioRxTimeMillis);
- dest.writeLong(mTotalScanTimeMillis);
- dest.writeLong(mTotalNanScanTimeMillis);
- dest.writeLong(mTotalBackgroundScanTimeMillis);
- dest.writeLong(mTotalRoamScanTimeMillis);
- dest.writeLong(mTotalPnoScanTimeMillis);
- dest.writeLong(mTotalHotspot2ScanTimeMillis);
- dest.writeLong(mTotalCcaBusyFreqTimeMillis);
- dest.writeLong(mTotalRadioOnFreqTimeMillis);
- dest.writeLong(mTotalBeaconRx);
- dest.writeInt(mProbeStatusSinceLastUpdate);
- dest.writeInt(mProbeElapsedTimeSinceLastUpdateMillis);
- dest.writeInt(mProbeMcsRateSinceLastUpdate);
- dest.writeInt(mRxLinkSpeedMbps);
- dest.writeInt(mCellularDataNetworkType);
- dest.writeInt(mCellularSignalStrengthDbm);
- dest.writeInt(mCellularSignalStrengthDb);
- dest.writeBoolean(mIsSameRegisteredCell);
- }
-
- /** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator