FileDocCategorySizeDatePackage
WifiManager.javaAPI DocAndroid 5.1 API91235Thu Mar 12 22:22:44 GMT 2015android.net.wifi

WifiManager

public class WifiManager extends Object
This class provides the primary API for managing all aspects of Wi-Fi connectivity. Get an instance of this class by calling {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.WIFI_SERVICE)}. 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}.

Fields Summary
private static final String
TAG
public static final int
ERROR_AUTHENTICATING
The error code if there was a problem authenticating.
public static final String
WIFI_SCAN_AVAILABLE
Broadcast intent action indicating whether Wi-Fi scanning is allowed currently
public static final String
EXTRA_SCAN_AVAILABLE
Extra int indicating scan availability, WIFI_STATE_ENABLED and WIFI_STATE_DISABLED
public static final String
WIFI_STATE_CHANGED_ACTION
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.
public static final String
EXTRA_WIFI_STATE
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)}.
public static final String
EXTRA_PREVIOUS_WIFI_STATE
The previous Wi-Fi state.
public static final int
WIFI_STATE_DISABLING
Wi-Fi is currently being disabled. The state will change to {@link #WIFI_STATE_DISABLED} if it finishes successfully.
public static final int
WIFI_STATE_DISABLED
Wi-Fi is disabled.
public static final int
WIFI_STATE_ENABLING
Wi-Fi is currently being enabled. The state will change to {@link #WIFI_STATE_ENABLED} if it finishes successfully.
public static final int
WIFI_STATE_ENABLED
Wi-Fi is enabled.
public static final int
WIFI_STATE_UNKNOWN
Wi-Fi is in an unknown state. This state will occur when an error happens while enabling or disabling.
public static final String
WIFI_AP_STATE_CHANGED_ACTION
Broadcast intent action indicating that Wi-Fi AP has been enabled, disabled, enabling, disabling, or failed.
public static final String
EXTRA_WIFI_AP_STATE
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)}.
public static final String
EXTRA_PREVIOUS_WIFI_AP_STATE
The previous Wi-Fi state.
public static final int
WIFI_AP_STATE_DISABLING
Wi-Fi AP is currently being disabled. The state will change to {@link #WIFI_AP_STATE_DISABLED} if it finishes successfully.
public static final int
WIFI_AP_STATE_DISABLED
Wi-Fi AP is disabled.
public static final int
WIFI_AP_STATE_ENABLING
Wi-Fi AP is currently being enabled. The state will change to {@link #WIFI_AP_STATE_ENABLED} if it finishes successfully.
public static final int
WIFI_AP_STATE_ENABLED
Wi-Fi AP is enabled.
public static final int
WIFI_AP_STATE_FAILED
Wi-Fi AP is in a failed state. This state will occur when an error occurs during enabling or disabling
public static final String
SUPPLICANT_CONNECTION_CHANGE_ACTION
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.
public static final String
EXTRA_SUPPLICANT_CONNECTED
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)}.
public static final String
NETWORK_STATE_CHANGED_ACTION
Broadcast intent action indicating that the state of Wi-Fi connectivity has changed. One extra provides the new state in the form of a {@link android.net.NetworkInfo} object. If the new state is CONNECTED, additional extras may provide the BSSID and WifiInfo of the access point. as a {@code String}.
public static final String
EXTRA_NETWORK_INFO
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_BSSID
The lookup key for a String giving the BSSID of the access point to which we are connected. Only present when the new state is CONNECTED. Retrieve with {@link android.content.Intent#getStringExtra(String)}.
public static final String
EXTRA_WIFI_INFO
The lookup key for a {@link android.net.wifi.WifiInfo} object giving the information about the access point to which we are connected. Only present when the new state is CONNECTED. Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
public static final String
SUPPLICANT_STATE_CHANGED_ACTION
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.
public static final String
EXTRA_NEW_STATE
The lookup key for a {@link SupplicantState} describing the new state Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
public static final String
EXTRA_SUPPLICANT_ERROR
The lookup key for a {@link SupplicantState} describing the supplicant error code if any Retrieve with {@link android.content.Intent#getIntExtra(String, int)}.
public static final String
CONFIGURED_NETWORKS_CHANGED_ACTION
Broadcast intent action indicating that the configured networks changed. This can be as a result of adding/updating/deleting a network. If {@link #EXTRA_MULTIPLE_NETWORKS_CHANGED} is set to true the new configuration can be retreived with the {@link #EXTRA_WIFI_CONFIGURATION} extra. If multiple Wi-Fi configurations changed, {@link #EXTRA_WIFI_CONFIGURATION} will not be present.
public static final String
EXTRA_WIFI_CONFIGURATION
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.
public static final String
EXTRA_MULTIPLE_NETWORKS_CHANGED
Multiple network configurations have changed.
public static final String
EXTRA_CHANGE_REASON
The lookup key for an integer indicating the reason a Wi-Fi network configuration has changed. Only present if {@link #EXTRA_MULTIPLE_NETWORKS_CHANGED} is {@code false}
public static final int
CHANGE_REASON_ADDED
The configuration is new and was added.
public static final int
CHANGE_REASON_REMOVED
The configuration was removed and is no longer present in the system's list of configured networks.
public static final int
CHANGE_REASON_CONFIG_CHANGE
The configuration has changed as a result of explicit action or because the system took an automated action such as disabling a malfunctioning configuration.
public static final String
SCAN_RESULTS_AVAILABLE_ACTION
An access point scan has completed, and results are available from the supplicant. Call {@link #getScanResults()} to obtain the results.
public static final String
BATCHED_SCAN_RESULTS_AVAILABLE_ACTION
A batch of access point scans has been completed and the results areavailable. Call {@link #getBatchedScanResults()} to obtain the results.
public static final String
RSSI_CHANGED_ACTION
The RSSI (signal strength) has changed.
public static final String
EXTRA_NEW_RSSI
The lookup key for an {@code int} giving the new RSSI in dBm.
public static final String
LINK_CONFIGURATION_CHANGED_ACTION
Broadcast intent action indicating that the link configuration changed on wifi.
public static final String
EXTRA_LINK_PROPERTIES
The lookup key for a {@link android.net.LinkProperties} object associated with the Wi-Fi network. Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
public static final String
EXTRA_NETWORK_CAPABILITIES
The lookup key for a {@link android.net.NetworkCapabilities} object associated with the Wi-Fi network. Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
public static final String
NETWORK_IDS_CHANGED_ACTION
The network IDs of the configured networks could have changed.
public static final String
ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE
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.

public static final String
ACTION_PICK_WIFI_NETWORK
Activity Action: Pick a Wi-Fi network to connect to.

Input: Nothing.

Output: Nothing.

public static final int
WIFI_MODE_FULL
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.
public static final int
WIFI_MODE_SCAN_ONLY
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.
public static final int
WIFI_MODE_FULL_HIGH_PERF
In this Wi-Fi lock mode, Wi-Fi will be kept active as in mode {@link #WIFI_MODE_FULL} but it operates at high performance with minimum packet loss and low packet latency even when the device screen is off. This mode will consume more power and hence should be used only when there is a need for such an active connection.

An example use case is when a voice connection needs to be kept active even after the device screen goes off. Holding the regular {@link #WIFI_MODE_FULL} lock will keep the wifi connection active, but the connection can be lossy. Holding a {@link #WIFI_MODE_FULL_HIGH_PERF} lock for the duration of the voice call will improve the call quality.

When there is no support from the hardware, this lock mode will have the same behavior as {@link #WIFI_MODE_FULL}

private static final int
MIN_RSSI
Anything worse than or equal to this will show 0 bars.
private static final int
MAX_RSSI
Anything better than or equal to this will show the max bars.
public static final int
RSSI_LEVELS
Number of RSSI levels used in the framework to initiate {@link #RSSI_CHANGED_ACTION} broadcast
public static final int
WIFI_FREQUENCY_BAND_AUTO
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.
public static final int
WIFI_FREQUENCY_BAND_5GHZ
Operation on 5 GHz alone
public static final int
WIFI_FREQUENCY_BAND_2GHZ
Operation on 2.4 GHz alone
public static final int
DATA_ACTIVITY_NOTIFICATION
List of asyncronous notifications
public static final int
DATA_ACTIVITY_NONE
public static final int
DATA_ACTIVITY_IN
public static final int
DATA_ACTIVITY_OUT
public static final int
DATA_ACTIVITY_INOUT
public static final boolean
DEFAULT_POOR_NETWORK_AVOIDANCE_ENABLED
private static final int
MAX_ACTIVE_LOCKS
private int
mActiveLockCount
private android.content.Context
mContext
IWifiManager
mService
private static final int
INVALID_KEY
private static int
sListenerKey
private static final android.util.SparseArray
sListenerMap
private static final Object
sListenerMapLock
private static com.android.internal.util.AsyncChannel
sAsyncChannel
private static CountDownLatch
sConnected
private static final Object
sThreadRefLock
private static int
sThreadRefCount
private static android.os.HandlerThread
sHandlerThread
public static final int
WIFI_FEATURE_INFRA
public static final int
WIFI_FEATURE_INFRA_5G
public static final int
WIFI_FEATURE_PASSPOINT
public static final int
WIFI_FEATURE_P2P
public static final int
WIFI_FEATURE_MOBILE_HOTSPOT
public static final int
WIFI_FEATURE_SCANNER
public static final int
WIFI_FEATURE_NAN
public static final int
WIFI_FEATURE_D2D_RTT
public static final int
WIFI_FEATURE_D2AP_RTT
public static final int
WIFI_FEATURE_BATCH_SCAN
public static final int
WIFI_FEATURE_PNO
public static final int
WIFI_FEATURE_ADDITIONAL_STA
public static final int
WIFI_FEATURE_TDLS
public static final int
WIFI_FEATURE_TDLS_OFFCHANNEL
public static final int
WIFI_FEATURE_EPR
private static final int
BASE
public static final int
CONNECT_NETWORK
public static final int
CONNECT_NETWORK_FAILED
public static final int
CONNECT_NETWORK_SUCCEEDED
public static final int
FORGET_NETWORK
public static final int
FORGET_NETWORK_FAILED
public static final int
FORGET_NETWORK_SUCCEEDED
public static final int
SAVE_NETWORK
public static final int
SAVE_NETWORK_FAILED
public static final int
SAVE_NETWORK_SUCCEEDED
public static final int
START_WPS
public static final int
START_WPS_SUCCEEDED
public static final int
WPS_FAILED
public static final int
WPS_COMPLETED
public static final int
CANCEL_WPS
public static final int
CANCEL_WPS_FAILED
public static final int
CANCEL_WPS_SUCCEDED
public static final int
DISABLE_NETWORK
public static final int
DISABLE_NETWORK_FAILED
public static final int
DISABLE_NETWORK_SUCCEEDED
public static final int
RSSI_PKTCNT_FETCH
public static final int
RSSI_PKTCNT_FETCH_SUCCEEDED
public static final int
RSSI_PKTCNT_FETCH_FAILED
public static final int
ERROR
Passed with {@link ActionListener#onFailure}. Indicates that the operation failed due to an internal error.
public static final int
IN_PROGRESS
Passed with {@link ActionListener#onFailure}. Indicates that the operation is already in progress
public static final int
BUSY
Passed with {@link ActionListener#onFailure}. Indicates that the operation failed because the framework is busy and unable to service the request
public static final int
WPS_OVERLAP_ERROR
WPS overlap detected
public static final int
WPS_WEP_PROHIBITED
WEP on WPS is prohibited
public static final int
WPS_TKIP_ONLY_PROHIBITED
TKIP only prohibited
public static final int
WPS_AUTH_FAILURE
Authentication failure on WPS
public static final int
WPS_TIMED_OUT
WPS timed out
public static final int
INVALID_ARGS
Passed with {@link ActionListener#onFailure}. Indicates that the operation failed due to invalid inputs
public static final int
NOT_AUTHORIZED
Passed with {@link ActionListener#onFailure}. Indicates that the operation failed due to user permissions.
Constructors Summary
public WifiManager(android.content.Context context, IWifiManager service)
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
hide
- hide this because it takes in a parameter of type IWifiManager, which is a system private class.


                                                            
         
        mContext = context;
        mService = service;
        init();
    
Methods Summary
public intaddNetwork(WifiConfiguration config)
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.
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.

        if (config == null) {
            return -1;
        }
        config.networkId = -1;
        return addOrUpdateNetwork(config);
    
private intaddOrUpdateNetwork(WifiConfiguration 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.

        try {
            return mService.addOrUpdateNetwork(config);
        } catch (RemoteException e) {
            return -1;
        }
    
public booleanaddToBlacklist(java.lang.String bssid)
Add a bssid to the supplicant blacklist This API is used by WifiWatchdogService

return
{@code true} if the operation succeeds else {@code false}
hide

        try {
            mService.addToBlacklist(bssid);
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public static intcalculateSignalLevel(int rssi, int numLevels)
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).

        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);
        }
    
public voidcancelWps(android.net.wifi.WifiManager$WpsCallback listener)
Cancel any ongoing Wi-fi Protected Setup

param
listener for callbacks on success or failure. Can be null.
throws
IllegalStateException if the WifiManager instance needs to be initialized again

        validateChannel();
        sAsyncChannel.sendMessage(CANCEL_WPS, 0, putListener(listener));
    
public booleanclearBlacklist()
Clear the supplicant blacklist This API is used by WifiWatchdogService

return
{@code true} if the operation succeeds else {@code false}
hide

        try {
            mService.clearBlacklist();
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public static intcompareSignalLevel(int rssiA, int rssiB)
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.

        return rssiA - rssiB;
    
public voidconnect(WifiConfiguration config, android.net.wifi.WifiManager$ActionListener listener)
Connect to a network with the given configuration. The network also gets added to the supplicant configuration. For a new network, this function is used instead of a sequence of addNetwork(), enableNetwork(), saveConfiguration() 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

        if (config == null) throw new IllegalArgumentException("config cannot be null");
        validateChannel();
        // Use INVALID_NETWORK_ID for arg1 when passing a config object
        // arg1 is used to pass network id when the network already exists
        sAsyncChannel.sendMessage(CONNECT_NETWORK, WifiConfiguration.INVALID_NETWORK_ID,
                putListener(listener), config);
    
public voidconnect(int networkId, android.net.wifi.WifiManager$ActionListener listener)
Connect to a network with the given networkId. This function is used instead of a enableNetwork(), saveConfiguration() and reconnect()

param
networkId the network id identifiying the network in the supplicant configuration list
param
listener for callbacks on success or failure. Can be null.
throws
IllegalStateException if the WifiManager instance needs to be initialized again
hide

        if (networkId < 0) throw new IllegalArgumentException("Network id cannot be negative");
        validateChannel();
        sAsyncChannel.sendMessage(CONNECT_NETWORK, networkId, putListener(listener));
    
public android.net.wifi.WifiManager$MulticastLockcreateMulticastLock(java.lang.String 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

        return new MulticastLock(tag);
    
public android.net.wifi.WifiManager$WifiLockcreateWifiLock(int lockType, java.lang.String tag)
Creates a new WifiLock.

param
lockType the type of lock to create. See {@link #WIFI_MODE_FULL}, {@link #WIFI_MODE_FULL_HIGH_PERF} and {@link #WIFI_MODE_SCAN_ONLY} 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

        return new WifiLock(lockType, tag);
    
public android.net.wifi.WifiManager$WifiLockcreateWifiLock(java.lang.String 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

        return new WifiLock(WIFI_MODE_FULL, tag);
    
public voiddisable(int netId, android.net.wifi.WifiManager$ActionListener listener)
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
hide

        if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
        validateChannel();
        sAsyncChannel.sendMessage(DISABLE_NETWORK, netId, putListener(listener));
    
public voiddisableEphemeralNetwork(java.lang.String SSID)
Disable ephemeral Network

param
SSID, in the format of WifiConfiguration's SSID.
hide

        if (SSID == null) throw new IllegalArgumentException("SSID cannot be null");
        try {
            mService.disableEphemeralNetwork(SSID);
        } catch (RemoteException e) {
        }
    
public booleandisableNetwork(int netId)
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.

param
netId the ID of the network as returned by {@link #addNetwork}.
return
{@code true} if the operation succeeded

        try {
            return mService.disableNetwork(netId);
        } catch (RemoteException e) {
            return false;
        }
    
public booleandisconnect()
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

        try {
            mService.disconnect();
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public voidenableAggressiveHandover(int enabled)
Set wifi Aggressive Handover. Called from developer settings.

hide

        try {
            mService.enableAggressiveHandover(enabled);
        } catch (RemoteException e) {

        }
    
public booleanenableNetwork(int netId, boolean disableOthers)
Allow a previously configured network to be associated with. If disableOthers is true, then all other configured networks are disabled, and an attempt to connect to the selected network is initiated. This may result in the asynchronous delivery of state change events.

param
netId the ID of the network in the list of configured networks
param
disableOthers if true, disable all other networks. The way to select a particular network to connect to is specify {@code true} for this parameter.
return
{@code true} if the operation succeeded

        try {
            return mService.enableNetwork(netId, disableOthers);
        } catch (RemoteException e) {
            return false;
        }
    
public voidenableVerboseLogging(int verbose)
Set wifi verbose log. Called from developer settings.

hide

        try {
            mService.enableVerboseLogging(verbose);
        } catch (Exception e) {
            //ignore any failure here
            Log.e(TAG, "enableVerboseLogging " + e.toString());
        }
    
protected voidfinalize()

        try {
            synchronized (sThreadRefLock) {
                if (--sThreadRefCount == 0 && sAsyncChannel != null) {
                    sAsyncChannel.disconnect();
                }
            }
        } finally {
            super.finalize();
        }
    
public voidforget(int netId, android.net.wifi.WifiManager$ActionListener listener)
Delete the network in the supplicant config. This function is used instead of a sequence of removeNetwork() and saveConfiguration().

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

        if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
        validateChannel();
        sAsyncChannel.sendMessage(FORGET_NETWORK, netId, putListener(listener));
    
public intgetAggressiveHandover()
Get the WiFi Handover aggressiveness.This is used by settings to decide what to show within the picker.

hide

        try {
            return mService.getAggressiveHandover();
        } catch (RemoteException e) {
            return 0;
        }
    
public intgetAllowScansWithTraffic()
Get setting for allowing Scans when traffic is ongoing.

hide

        try {
            return mService.getAllowScansWithTraffic();
        } catch (RemoteException e) {
            return 0;
        }
    
public java.util.ListgetBatchedScanResults()
Retrieve the latest batched scan result. This should be called immediately after {@link BATCHED_SCAN_RESULTS_AVAILABLE_ACTION} is received.

hide

        try {
            return mService.getBatchedScanResults(mContext.getOpPackageName());
        } catch (RemoteException e) {
            return null;
        }
    
public java.util.ListgetChannelList()
Get a list of available channels for customized scan.

see
{@link WifiChannel}
return
the channel list, or null if not available
hide

        try {
            return mService.getChannelList();
        } catch (RemoteException e) {
            return null;
        }
    
public java.lang.StringgetConfigFile()
Returns the file in which IP and proxy configuration data is stored

hide

        try {
            return mService.getConfigFile();
        } catch (RemoteException e) {
            return null;
        }
    
public java.util.ListgetConfiguredNetworks()
Return a list of all the networks configured in the supplicant. Not all fields of WifiConfiguration are returned. Only the following fields are filled in:
  • networkId
  • SSID
  • BSSID
  • priority
  • allowedProtocols
  • allowedKeyManagement
  • allowedAuthAlgorithms
  • allowedPairwiseCiphers
  • allowedGroupCiphers

return
a list of network configurations in the form of a list of {@link WifiConfiguration} objects. Upon failure to fetch or when when Wi-Fi is turned off, it can be null.

        try {
            return mService.getConfiguredNetworks();
        } catch (RemoteException e) {
            return null;
        }
    
public WifiInfogetConnectionInfo()
Return dynamic information about the current Wi-Fi connection, if any is active.

return
the Wi-Fi information, contained in {@link WifiInfo}.

        try {
            return mService.getConnectionInfo();
        } catch (RemoteException e) {
            return null;
        }
    
public WifiConnectionStatisticsgetConnectionStatistics()

hide

        try {
            return mService.getConnectionStatistics();
        } catch (RemoteException e) {
            return null;
        }
    
public WifiActivityEnergyInfogetControllerActivityEnergyInfo(int updateType)
Return the record of {@link WifiActivityEnergyInfo} object that has the activity and energy info. This can be used to ascertain what the controller has been up to, since the last sample.

param
updateType Type of info, cached vs refreshed.
return
a record with {@link WifiActivityEnergyInfo} or null if report is unavailable or unsupported
hide

        if (mService == null) return null;
        try {
            WifiActivityEnergyInfo record;
            if (!isEnhancedPowerReportingSupported()) {
                return null;
            }
            synchronized(this) {
                record = mService.reportActivityInfo();
                if (record.isValid()) {
                    return record;
                } else {
                    return null;
                }
            }
        } catch (RemoteException e) {
            Log.e(TAG, "getControllerActivityEnergyInfo: " + e);
        }
        return null;
    
public android.net.DhcpInfogetDhcpInfo()
Return the DHCP-assigned addresses from the last successful DHCP request, if any.

return
the DHCP information

        try {
            return mService.getDhcpInfo();
        } catch (RemoteException e) {
            return null;
        }
    
public intgetFrequencyBand()
Get the operational frequency band.

return
One of {@link #WIFI_FREQUENCY_BAND_AUTO}, {@link #WIFI_FREQUENCY_BAND_5GHZ}, {@link #WIFI_FREQUENCY_BAND_2GHZ} or {@code -1} on failure.
hide

        try {
            return mService.getFrequencyBand();
        } catch (RemoteException e) {
            return -1;
        }
    
public java.util.ListgetPrivilegedConfiguredNetworks()

hide

        try {
            return mService.getPrivilegedConfiguredNetworks();
        } catch (RemoteException e) {
            return null;
        }
    
public java.util.ListgetScanResults()
Return the results of the latest access point scan.

return
the list of access points found in the most recent scan.

        try {
            return mService.getScanResults(mContext.getOpPackageName());
        } catch (RemoteException e) {
            return null;
        }
    
private intgetSupportedFeatures()

  // Enhanced power reporting

       
        try {
            return mService.getSupportedFeatures();
        } catch (RemoteException e) {
            return 0;
        }
    
public voidgetTxPacketCount(android.net.wifi.WifiManager$TxPacketCountListener listener)
Return TX packet counter, for CTS test of WiFi watchdog.

param
listener is the interface to receive result
hide
for CTS test only

        validateChannel();
        sAsyncChannel.sendMessage(RSSI_PKTCNT_FETCH, 0, putListener(listener));
    
public intgetVerboseLoggingLevel()
Get the WiFi verbose logging level.This is used by settings to decide what to show within the picker.

hide

        try {
            return mService.getVerboseLoggingLevel();
        } catch (RemoteException e) {
            return 0;
        }
    
public WifiConfigurationgetWifiApConfiguration()
Gets the Wi-Fi AP Configuration.

return
AP details in WifiConfiguration
hide
Dont open yet

        try {
            return mService.getWifiApConfiguration();
        } catch (RemoteException e) {
            return null;
        }
    
public intgetWifiApState()
Gets the Wi-Fi 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
Dont open yet

        try {
            return mService.getWifiApEnabledState();
        } catch (RemoteException e) {
            return WIFI_AP_STATE_FAILED;
        }
    
public android.os.MessengergetWifiServiceMessenger()
Get a reference to WifiService handler. This is used by a client to establish an AsyncChannel communication with WifiService

return
Messenger pointing to the WifiService handler
hide

        try {
            return mService.getWifiServiceMessenger();
        } catch (RemoteException e) {
            return null;
        } catch (SecurityException e) {
            return null;
        }
    
public intgetWifiState()
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()

        try {
            return mService.getWifiEnabledState();
        } catch (RemoteException e) {
            return WIFI_STATE_UNKNOWN;
        }
    
public java.lang.StringgetWpsNfcConfigurationToken(int netId)
Creates a configuration token describing the network referenced by {@code netId} of MIME type application/vnd.wfa.wsc. Can be used to configure WiFi networks via NFC.

return
hex-string encoded configuration token
hide

        try {
            return mService.getWpsNfcConfigurationToken(netId);
        } catch (RemoteException e) {
            return null;
        }
    
private voidinit()

        synchronized (sThreadRefLock) {
            if (++sThreadRefCount == 1) {
                Messenger messenger = getWifiServiceMessenger();
                if (messenger == null) {
                    sAsyncChannel = null;
                    return;
                }

                sHandlerThread = new HandlerThread("WifiManager");
                sAsyncChannel = new AsyncChannel();
                sConnected = new CountDownLatch(1);

                sHandlerThread.start();
                Handler handler = new ServiceHandler(sHandlerThread.getLooper());
                sAsyncChannel.connect(mContext, handler, messenger);
                try {
                    sConnected.await();
                } catch (InterruptedException e) {
                    Log.e(TAG, "interrupted wait at init");
                }
            }
        }
    
public booleaninitializeMulticastFiltering()
Initialize the multicast filtering to 'on'

hide
no intent to publish

        try {
            mService.initializeMulticastFiltering();
            return true;
        } catch (RemoteException e) {
             return false;
        }
    
public booleanis5GHzBandSupported()

return
true if this adapter supports 5 GHz band

        return isFeatureSupported(WIFI_FEATURE_INFRA_5G);
    
public booleanisAdditionalStaSupported()

return
true if this adapter supports multiple simultaneous connections
hide

        return isFeatureSupported(WIFI_FEATURE_ADDITIONAL_STA);
    
public booleanisBatchedScanSupported()
Check if the Batched Scan feature is supported.

return
false if not supported.
hide

        try {
            return mService.isBatchedScanSupported();
        } catch (RemoteException e) { return false; }
    
public booleanisDeviceToApRttSupported()

return
true if this adapter supports Device-to-AP RTT

        return isFeatureSupported(WIFI_FEATURE_D2AP_RTT);
    
public booleanisDeviceToDeviceRttSupported()

return
true if this adapter supports Device-to-device RTT
hide

        return isFeatureSupported(WIFI_FEATURE_D2D_RTT);
    
public booleanisDualBandSupported()
Check if the chipset supports dual frequency band (2.4 GHz and 5 GHz)

return
{@code true} if supported, {@code false} otherwise.
hide

        try {
            return mService.isDualBandSupported();
        } catch (RemoteException e) {
            return false;
        }
    
public booleanisEnhancedPowerReportingSupported()

return
true if this adapter supports advanced power/performance counters

        return isFeatureSupported(WIFI_FEATURE_EPR);
    
private booleanisFeatureSupported(int feature)

        return (getSupportedFeatures() & feature) == feature;
    
public booleanisMulticastEnabled()
Check multicast filter status.

return
true if multicast packets are allowed.
hide
pending API council approval

        try {
            return mService.isMulticastEnabled();
        } catch (RemoteException e) {
            return false;
        }
    
public booleanisNanSupported()

return
true if this adapter supports Neighbour Awareness Network APIs
hide

        return isFeatureSupported(WIFI_FEATURE_NAN);
    
public booleanisOffChannelTdlsSupported()

return
true if this adapter supports Off Channel Tunnel Directed Link Setup
hide

        return isFeatureSupported(WIFI_FEATURE_TDLS_OFFCHANNEL);
    
public booleanisP2pSupported()

return
true if this adapter supports WifiP2pManager (Wi-Fi Direct)

        return isFeatureSupported(WIFI_FEATURE_P2P);
    
public booleanisPasspointSupported()

return
true if this adapter supports passpoint
hide

        return isFeatureSupported(WIFI_FEATURE_PASSPOINT);
    
public booleanisPortableHotspotSupported()

return
true if this adapter supports portable Wi-Fi hotspot
hide

        return isFeatureSupported(WIFI_FEATURE_MOBILE_HOTSPOT);
    
public booleanisPreferredNetworkOffloadSupported()

return
true if this adapter supports offloaded connectivity scan

        return isFeatureSupported(WIFI_FEATURE_PNO);
    
public booleanisScanAlwaysAvailable()
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}.

        try {
            return mService.isScanAlwaysAvailable();
        } catch (RemoteException e) {
            return false;
        }
    
public booleanisTdlsSupported()

return
true if this adapter supports Tunnel Directed Link Setup

        return isFeatureSupported(WIFI_FEATURE_TDLS);
    
public booleanisWifiApEnabled()
Return whether Wi-Fi AP is enabled or disabled.

return
{@code true} if Wi-Fi AP is enabled
see
#getWifiApState()
hide
Dont open yet

        return getWifiApState() == WIFI_AP_STATE_ENABLED;
    
public booleanisWifiEnabled()
Return whether Wi-Fi is enabled or disabled.

return
{@code true} if Wi-Fi is enabled
see
#getWifiState()

        return getWifiState() == WIFI_STATE_ENABLED;
    
public booleanisWifiScannerSupported()

return
true if this adapter supports WifiScanner APIs
hide

        return isFeatureSupported(WIFI_FEATURE_SCANNER);
    
public booleanpingSupplicant()
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.

        if (mService == null)
            return false;
        try {
            return mService.pingSupplicant();
        } catch (RemoteException e) {
            return false;
        }
    
public voidpollBatchedScan()
Force a re-reading of batched scan results. This will attempt to read more information from the chip, but will do so at the expense of previous data. Rate limited to the current scan frequency. pollBatchedScan will always wait 1 period from the start of the batch before trying to read from the chip, so if your #scans/batch == 1 this will have no effect. If you had already waited 1 period before calling, this should have immediate (though async) effect. If you call before that 1 period is up this will set up a timer and fetch results when the 1 period is up. Servicing a pollBatchedScan request (immediate or after timed delay) starts a new batch, so if you were doing 10 scans/batch and called in the 4th scan, you would get data in the 4th and then again 10 scans later.

hide

        try {
            mService.pollBatchedScan();
        } catch (RemoteException e) { }
    
private static intputListener(java.lang.Object listener)

        if (listener == null) return INVALID_KEY;
        int key;
        synchronized (sListenerMapLock) {
            do {
                key = sListenerKey++;
            } while (key == INVALID_KEY);
            sListenerMap.put(key, listener);
        }
        return key;
    
public booleanreassociate()
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

        try {
            mService.reassociate();
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public booleanreconnect()
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

        try {
            mService.reconnect();
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
private static java.lang.ObjectremoveListener(int key)

        if (key == INVALID_KEY) return null;
        synchronized (sListenerMapLock) {
            Object listener = sListenerMap.get(key);
            sListenerMap.remove(key);
            return listener;
        }
    
public booleanremoveNetwork(int netId)
Remove the specified network from the list of configured networks. This may result in the asynchronous delivery of state change events.

param
netId the integer that identifies the network configuration to the supplicant
return
{@code true} if the operation succeeded

        try {
            return mService.removeNetwork(netId);
        } catch (RemoteException e) {
            return false;
        }
    
public booleanrequestBatchedScan(BatchedScanSettings requested)
Request a batched scan for access points. To end your requested batched scan, call stopBatchedScan with the same Settings. If there are mulitple requests for batched scans, the more demanding settings will take precidence.

param
requested {@link BatchedScanSettings} the scan settings requested.
return
false on known error
hide

        try {
            return mService.requestBatchedScan(requested, new Binder(), null);
        } catch (RemoteException e) { return false; }
    
public booleanrequestBatchedScan(BatchedScanSettings requested, android.os.WorkSource workSource)

hide

        try {
            return mService.requestBatchedScan(requested, new Binder(), workSource);
        } catch (RemoteException e) { return false; }
    
public voidsave(WifiConfiguration config, android.net.wifi.WifiManager$ActionListener listener)
Save the given network in the supplicant config. If the network already exists, the configuration is updated. A new network is enabled by default. For a new network, this function is used instead of a sequence of addNetwork(), enableNetwork() and saveConfiguration(). For an existing network, it accomplishes the task of updateNetwork() and saveConfiguration()

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

        if (config == null) throw new IllegalArgumentException("config cannot be null");
        validateChannel();
        sAsyncChannel.sendMessage(SAVE_NETWORK, 0, putListener(listener), config);
    
public booleansaveConfiguration()
Tell the supplicant 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 true} if the operation succeeded

        try {
            return mService.saveConfiguration();
        } catch (RemoteException e) {
            return false;
        }
    
public voidsetAllowScansWithTraffic(int enabled)
Set setting for allowing Scans when traffic is ongoing.

hide

        try {
            mService.setAllowScansWithTraffic(enabled);
        } catch (RemoteException e) {

        }
    
public voidsetCountryCode(java.lang.String country, boolean persist)
Set the country code.

param
countryCode country code in ISO 3166 format.
param
persist {@code true} if this needs to be remembered
hide

        try {
            mService.setCountryCode(country, persist);
        } catch (RemoteException e) { }
    
public voidsetFrequencyBand(int band, boolean persist)
Set the operational frequency band.

param
band One of {@link #WIFI_FREQUENCY_BAND_AUTO}, {@link #WIFI_FREQUENCY_BAND_5GHZ}, {@link #WIFI_FREQUENCY_BAND_2GHZ},
param
persist {@code true} if this needs to be remembered
hide

        try {
            mService.setFrequencyBand(band, persist);
        } catch (RemoteException e) { }
    
public voidsetTdlsEnabled(java.net.InetAddress remoteIPAddress, boolean enable)
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

        try {
            mService.enableTdls(remoteIPAddress.getHostAddress(), enable);
        } catch (RemoteException e) {
            // Just ignore the exception
        }
    
public voidsetTdlsEnabledWithMacAddress(java.lang.String remoteMacAddress, boolean enable)
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

        try {
            mService.enableTdlsWithMacAddress(remoteMacAddress, enable);
        } catch (RemoteException e) {
            // Just ignore the exception
        }
    
public booleansetWifiApConfiguration(WifiConfiguration wifiConfig)
Sets the Wi-Fi AP Configuration.

return
{@code true} if the operation succeeded, {@code false} otherwise
hide
Dont open yet

        try {
            mService.setWifiApConfiguration(wifiConfig);
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public booleansetWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled)
Start AccessPoint mode with the specified configuration. If the radio is already running in AP mode, update the new configuration Note that starting in access point mode disables station mode operation

param
wifiConfig SSID, security and channel details as part of WifiConfiguration
return
{@code true} if the operation succeeds, {@code false} otherwise
hide
Dont open up yet

        try {
            mService.setWifiApEnabled(wifiConfig, enabled);
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public booleansetWifiEnabled(boolean enabled)
Enable or disable Wi-Fi.

param
enabled {@code true} to enable, {@code false} to disable.
return
{@code true} if the operation succeeds (or if the existing state is the same as the requested state).

        try {
            return mService.setWifiEnabled(enabled);
        } catch (RemoteException e) {
            return false;
        }
    
public booleanstartCustomizedScan(android.net.wifi.ScanSettings requested)
Request a scan for access points in specified channel list. Each channel is specified by its frequency in MHz, e.g. "5500" (do NOT include "DFS" even though it is). The availability of the results is made known later in the same way as {@link #startScan}. Note: 1. Customized scan is for non-connection purposes, i.e. it won't trigger a wifi connection even though it finds some known networks. 2. Customized scan result may include access points that is not specified in the channel list. An app will need to do frequency filtering if it wants to get pure results for the channel list it specified.

hide

        try {
            mService.startScan(requested, null);
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public booleanstartCustomizedScan(android.net.wifi.ScanSettings requested, android.os.WorkSource workSource)

hide

        try {
            mService.startScan(requested, workSource);
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public booleanstartLocationRestrictedScan(android.os.WorkSource workSource)
startLocationRestrictedScan() Trigger a scan which will not make use of DFS channels and is thus not suitable for establishing wifi connection.

hide

        try {
            mService.startLocationRestrictedScan(workSource);
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public booleanstartScan()
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.

return
{@code true} if the operation succeeded, i.e., the scan was initiated

        try {
            mService.startScan(null, null);
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public booleanstartScan(android.os.WorkSource workSource)

hide

        try {
            mService.startScan(null, workSource);
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public booleanstartWifi()
Start the driver and connect to network. This function will over-ride WifiLock and device idle status. For example, even if the device is idle or there is only a scan-only lock held, a start wifi would mean that wifi connection is kept active until a stopWifi() is sent. This API is used by WifiStateTracker

return
{@code true} if the operation succeeds else {@code false}
hide

        try {
            mService.startWifi();
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public voidstartWps(WpsInfo config, android.net.wifi.WifiManager$WpsCallback listener)
Start Wi-fi Protected Setup

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

        if (config == null) throw new IllegalArgumentException("config cannot be null");
        validateChannel();
        sAsyncChannel.sendMessage(START_WPS, 0, putListener(listener), config);
    
public voidstopBatchedScan(BatchedScanSettings requested)
End a requested batch scan for this applicaiton. Note that batched scan may still occur if other apps are using them.

param
requested {@link BatchedScanSettings} the scan settings you previously requested and now wish to stop. A value of null here will stop all scans requested by the calling App.
hide

        try {
            mService.stopBatchedScan(requested);
        } catch (RemoteException e) {}
    
public booleanstopWifi()
Disconnect from a network (if any) and stop the driver. This function will over-ride WifiLock and device idle status. Wi-Fi stays inactive until a startWifi() is issued. This API is used by WifiStateTracker

return
{@code true} if the operation succeeds else {@code false}
hide

        try {
            mService.stopWifi();
            return true;
        } catch (RemoteException e) {
            return false;
        }
    
public intupdateNetwork(WifiConfiguration 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.
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.

        if (config == null || config.networkId < 0) {
            return -1;
        }
        return addOrUpdateNetwork(config);
    
private voidvalidateChannel()

        if (sAsyncChannel == null) throw new IllegalStateException(
                "No permission to access and change wifi or a bad initialization");