Home | History | Annotate | Download | only in wifi
      1 /*
      2  * Copyright (C) 2008 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.net.wifi;
     18 
     19 import android.annotation.SdkConstant;
     20 import android.annotation.SdkConstant.SdkConstantType;
     21 import android.annotation.SystemApi;
     22 import android.content.Context;
     23 import android.net.ConnectivityManager;
     24 import android.net.DhcpInfo;
     25 import android.net.Network;
     26 import android.net.NetworkCapabilities;
     27 import android.net.NetworkRequest;
     28 import android.os.Binder;
     29 import android.os.Build;
     30 import android.os.Handler;
     31 import android.os.IBinder;
     32 import android.os.Looper;
     33 import android.os.Message;
     34 import android.os.Messenger;
     35 import android.os.RemoteException;
     36 import android.os.WorkSource;
     37 import android.util.Log;
     38 import android.util.SparseArray;
     39 
     40 import com.android.internal.util.AsyncChannel;
     41 import com.android.internal.util.Protocol;
     42 import com.android.server.net.NetworkPinner;
     43 
     44 import java.net.InetAddress;
     45 import java.util.List;
     46 import java.util.concurrent.CountDownLatch;
     47 
     48 /**
     49  * This class provides the primary API for managing all aspects of Wi-Fi
     50  * connectivity. Get an instance of this class by calling
     51  * {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.WIFI_SERVICE)}.
     52  * On releases before NYC, it should only be obtained from an application context, and not from
     53  * any other derived context to avoid memory leaks within the calling process.
     54 
     55  * It deals with several categories of items:
     56  * <ul>
     57  * <li>The list of configured networks. The list can be viewed and updated,
     58  * and attributes of individual entries can be modified.</li>
     59  * <li>The currently active Wi-Fi network, if any. Connectivity can be
     60  * established or torn down, and dynamic information about the state of
     61  * the network can be queried.</li>
     62  * <li>Results of access point scans, containing enough information to
     63  * make decisions about what access point to connect to.</li>
     64  * <li>It defines the names of various Intent actions that are broadcast
     65  * upon any sort of change in Wi-Fi state.
     66  * </ul>
     67  * This is the API to use when performing Wi-Fi specific operations. To
     68  * perform operations that pertain to network connectivity at an abstract
     69  * level, use {@link android.net.ConnectivityManager}.
     70  */
     71 public class WifiManager {
     72 
     73     private static final String TAG = "WifiManager";
     74     // Supplicant error codes:
     75     /**
     76      * The error code if there was a problem authenticating.
     77      */
     78     public static final int ERROR_AUTHENTICATING = 1;
     79 
     80     /**
     81      * Broadcast intent action indicating whether Wi-Fi scanning is allowed currently
     82      * @hide
     83      */
     84     public static final String WIFI_SCAN_AVAILABLE = "wifi_scan_available";
     85 
     86     /**
     87      * Extra int indicating scan availability, WIFI_STATE_ENABLED and WIFI_STATE_DISABLED
     88      * @hide
     89      */
     90     public static final String EXTRA_SCAN_AVAILABLE = "scan_enabled";
     91 
     92     /**
     93      * Broadcast intent action indicating that the credential of a Wi-Fi network
     94      * has been changed. One extra provides the ssid of the network. Another
     95      * extra provides the event type, whether the credential is saved or forgot.
     96      * @hide
     97      */
     98     @SystemApi
     99     public static final String WIFI_CREDENTIAL_CHANGED_ACTION =
    100             "android.net.wifi.WIFI_CREDENTIAL_CHANGED";
    101     /** @hide */
    102     @SystemApi
    103     public static final String EXTRA_WIFI_CREDENTIAL_EVENT_TYPE = "et";
    104     /** @hide */
    105     @SystemApi
    106     public static final String EXTRA_WIFI_CREDENTIAL_SSID = "ssid";
    107     /** @hide */
    108     @SystemApi
    109     public static final int WIFI_CREDENTIAL_SAVED = 0;
    110     /** @hide */
    111     @SystemApi
    112     public static final int WIFI_CREDENTIAL_FORGOT = 1;
    113 
    114     /**
    115      * Broadcast intent action indicating that the a Passpoint release 2 icon has been received.
    116      * @hide
    117      */
    118     public static final String PASSPOINT_ICON_RECEIVED_ACTION =
    119             "android.net.wifi.PASSPOINT_ICON_RECEIVED";
    120     /** @hide */
    121     public static final String EXTRA_PASSPOINT_ICON_BSSID = "bssid";
    122     /** @hide */
    123     public static final String EXTRA_PASSPOINT_ICON_FILE = "file";
    124     /** @hide */
    125     public static final String EXTRA_PASSPOINT_ICON_DATA = "icon";
    126 
    127     /**
    128      * Broadcast intent action indicating that the a Passpoint release
    129      * 2 WNM frame has been received.
    130      * @hide
    131      */
    132     public static final String PASSPOINT_WNM_FRAME_RECEIVED_ACTION =
    133             "android.net.wifi.PASSPOINT_WNM_FRAME_RECEIVED";
    134     /**
    135      * Originating BSS
    136      * @hide */
    137     public static final String EXTRA_PASSPOINT_WNM_BSSID = "bssid";
    138     /**
    139      * SOAP-XML or OMA-DM
    140      * @hide */
    141     public static final String EXTRA_PASSPOINT_WNM_METHOD = "method";
    142     /**
    143      * Type of Passpoint match
    144      * @hide */
    145     public static final String EXTRA_PASSPOINT_WNM_PPOINT_MATCH = "match";
    146     /**
    147      * String
    148      * @hide */
    149     public static final String EXTRA_PASSPOINT_WNM_URL = "url";
    150     /**
    151      * Boolean true=ess, false=bss
    152      * @hide */
    153     public static final String EXTRA_PASSPOINT_WNM_ESS = "ess";
    154     /**
    155      * Delay in seconds
    156      * @hide */
    157     public static final String EXTRA_PASSPOINT_WNM_DELAY = "delay";
    158 
    159     /**
    160      * Broadcast intent action indicating that Wi-Fi has been enabled, disabled,
    161      * enabling, disabling, or unknown. One extra provides this state as an int.
    162      * Another extra provides the previous state, if available.
    163      *
    164      * @see #EXTRA_WIFI_STATE
    165      * @see #EXTRA_PREVIOUS_WIFI_STATE
    166      */
    167     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
    168     public static final String WIFI_STATE_CHANGED_ACTION =
    169         "android.net.wifi.WIFI_STATE_CHANGED";
    170     /**
    171      * The lookup key for an int that indicates whether Wi-Fi is enabled,
    172      * disabled, enabling, disabling, or unknown.  Retrieve it with
    173      * {@link android.content.Intent#getIntExtra(String,int)}.
    174      *
    175      * @see #WIFI_STATE_DISABLED
    176      * @see #WIFI_STATE_DISABLING
    177      * @see #WIFI_STATE_ENABLED
    178      * @see #WIFI_STATE_ENABLING
    179      * @see #WIFI_STATE_UNKNOWN
    180      */
    181     public static final String EXTRA_WIFI_STATE = "wifi_state";
    182     /**
    183      * The previous Wi-Fi state.
    184      *
    185      * @see #EXTRA_WIFI_STATE
    186      */
    187     public static final String EXTRA_PREVIOUS_WIFI_STATE = "previous_wifi_state";
    188 
    189     /**
    190      * Wi-Fi is currently being disabled. The state will change to {@link #WIFI_STATE_DISABLED} if
    191      * it finishes successfully.
    192      *
    193      * @see #WIFI_STATE_CHANGED_ACTION
    194      * @see #getWifiState()
    195      */
    196     public static final int WIFI_STATE_DISABLING = 0;
    197     /**
    198      * Wi-Fi is disabled.
    199      *
    200      * @see #WIFI_STATE_CHANGED_ACTION
    201      * @see #getWifiState()
    202      */
    203     public static final int WIFI_STATE_DISABLED = 1;
    204     /**
    205      * Wi-Fi is currently being enabled. The state will change to {@link #WIFI_STATE_ENABLED} if
    206      * it finishes successfully.
    207      *
    208      * @see #WIFI_STATE_CHANGED_ACTION
    209      * @see #getWifiState()
    210      */
    211     public static final int WIFI_STATE_ENABLING = 2;
    212     /**
    213      * Wi-Fi is enabled.
    214      *
    215      * @see #WIFI_STATE_CHANGED_ACTION
    216      * @see #getWifiState()
    217      */
    218     public static final int WIFI_STATE_ENABLED = 3;
    219     /**
    220      * Wi-Fi is in an unknown state. This state will occur when an error happens while enabling
    221      * or disabling.
    222      *
    223      * @see #WIFI_STATE_CHANGED_ACTION
    224      * @see #getWifiState()
    225      */
    226     public static final int WIFI_STATE_UNKNOWN = 4;
    227 
    228     /**
    229      * Broadcast intent action indicating that Wi-Fi AP has been enabled, disabled,
    230      * enabling, disabling, or failed.
    231      *
    232      * @hide
    233      */
    234     @SystemApi
    235     public static final String WIFI_AP_STATE_CHANGED_ACTION =
    236         "android.net.wifi.WIFI_AP_STATE_CHANGED";
    237 
    238     /**
    239      * The lookup key for an int that indicates whether Wi-Fi AP is enabled,
    240      * disabled, enabling, disabling, or failed.  Retrieve it with
    241      * {@link android.content.Intent#getIntExtra(String,int)}.
    242      *
    243      * @see #WIFI_AP_STATE_DISABLED
    244      * @see #WIFI_AP_STATE_DISABLING
    245      * @see #WIFI_AP_STATE_ENABLED
    246      * @see #WIFI_AP_STATE_ENABLING
    247      * @see #WIFI_AP_STATE_FAILED
    248      *
    249      * @hide
    250      */
    251     @SystemApi
    252     public static final String EXTRA_WIFI_AP_STATE = "wifi_state";
    253 
    254     /**
    255      * The look up key for an int that indicates why softAP started failed
    256      * currently support general and no_channel
    257      * @see #SAP_START_FAILURE_GENERAL
    258      * @see #SAP_START_FAILURE_NO_CHANNEL
    259      *
    260      * @hide
    261      */
    262     public static final String EXTRA_WIFI_AP_FAILURE_REASON = "wifi_ap_error_code";
    263     /**
    264      * The previous Wi-Fi state.
    265      *
    266      * @see #EXTRA_WIFI_AP_STATE
    267      *
    268      * @hide
    269      */
    270     @SystemApi
    271     public static final String EXTRA_PREVIOUS_WIFI_AP_STATE = "previous_wifi_state";
    272     /**
    273      * Wi-Fi AP is currently being disabled. The state will change to
    274      * {@link #WIFI_AP_STATE_DISABLED} if it finishes successfully.
    275      *
    276      * @see #WIFI_AP_STATE_CHANGED_ACTION
    277      * @see #getWifiApState()
    278      *
    279      * @hide
    280      */
    281     @SystemApi
    282     public static final int WIFI_AP_STATE_DISABLING = 10;
    283     /**
    284      * Wi-Fi AP is disabled.
    285      *
    286      * @see #WIFI_AP_STATE_CHANGED_ACTION
    287      * @see #getWifiState()
    288      *
    289      * @hide
    290      */
    291     @SystemApi
    292     public static final int WIFI_AP_STATE_DISABLED = 11;
    293     /**
    294      * Wi-Fi AP is currently being enabled. The state will change to
    295      * {@link #WIFI_AP_STATE_ENABLED} if it finishes successfully.
    296      *
    297      * @see #WIFI_AP_STATE_CHANGED_ACTION
    298      * @see #getWifiApState()
    299      *
    300      * @hide
    301      */
    302     @SystemApi
    303     public static final int WIFI_AP_STATE_ENABLING = 12;
    304     /**
    305      * Wi-Fi AP is enabled.
    306      *
    307      * @see #WIFI_AP_STATE_CHANGED_ACTION
    308      * @see #getWifiApState()
    309      *
    310      * @hide
    311      */
    312     @SystemApi
    313     public static final int WIFI_AP_STATE_ENABLED = 13;
    314     /**
    315      * Wi-Fi AP is in a failed state. This state will occur when an error occurs during
    316      * enabling or disabling
    317      *
    318      * @see #WIFI_AP_STATE_CHANGED_ACTION
    319      * @see #getWifiApState()
    320      *
    321      * @hide
    322      */
    323     @SystemApi
    324     public static final int WIFI_AP_STATE_FAILED = 14;
    325 
    326     /**
    327      *  If WIFI AP start failed, this reason code means there is no legal channel exists on
    328      *  user selected band by regulatory
    329      *
    330      *  @hide
    331      */
    332     public static final int SAP_START_FAILURE_GENERAL= 0;
    333 
    334     /**
    335      *  All other reason for AP start failed besides SAP_START_FAILURE_GENERAL
    336      *
    337      *  @hide
    338      */
    339     public static final int SAP_START_FAILURE_NO_CHANNEL = 1;
    340     /**
    341      * Broadcast intent action indicating that a connection to the supplicant has
    342      * been established (and it is now possible
    343      * to perform Wi-Fi operations) or the connection to the supplicant has been
    344      * lost. One extra provides the connection state as a boolean, where {@code true}
    345      * means CONNECTED.
    346      * @see #EXTRA_SUPPLICANT_CONNECTED
    347      */
    348     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
    349     public static final String SUPPLICANT_CONNECTION_CHANGE_ACTION =
    350         "android.net.wifi.supplicant.CONNECTION_CHANGE";
    351     /**
    352      * The lookup key for a boolean that indicates whether a connection to
    353      * the supplicant daemon has been gained or lost. {@code true} means
    354      * a connection now exists.
    355      * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
    356      */
    357     public static final String EXTRA_SUPPLICANT_CONNECTED = "connected";
    358     /**
    359      * Broadcast intent action indicating that the state of Wi-Fi connectivity
    360      * has changed. One extra provides the new state
    361      * in the form of a {@link android.net.NetworkInfo} object. If the new
    362      * state is CONNECTED, additional extras may provide the BSSID and WifiInfo of
    363      * the access point.
    364      * as a {@code String}.
    365      * @see #EXTRA_NETWORK_INFO
    366      * @see #EXTRA_BSSID
    367      * @see #EXTRA_WIFI_INFO
    368      */
    369     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
    370     public static final String NETWORK_STATE_CHANGED_ACTION = "android.net.wifi.STATE_CHANGE";
    371     /**
    372      * The lookup key for a {@link android.net.NetworkInfo} object associated with the
    373      * Wi-Fi network. Retrieve with
    374      * {@link android.content.Intent#getParcelableExtra(String)}.
    375      */
    376     public static final String EXTRA_NETWORK_INFO = "networkInfo";
    377     /**
    378      * The lookup key for a String giving the BSSID of the access point to which
    379      * we are connected. Only present when the new state is CONNECTED.
    380      * Retrieve with
    381      * {@link android.content.Intent#getStringExtra(String)}.
    382      */
    383     public static final String EXTRA_BSSID = "bssid";
    384     /**
    385      * The lookup key for a {@link android.net.wifi.WifiInfo} object giving the
    386      * information about the access point to which we are connected. Only present
    387      * when the new state is CONNECTED.  Retrieve with
    388      * {@link android.content.Intent#getParcelableExtra(String)}.
    389      */
    390     public static final String EXTRA_WIFI_INFO = "wifiInfo";
    391     /**
    392      * Broadcast intent action indicating that the state of establishing a connection to
    393      * an access point has changed.One extra provides the new
    394      * {@link SupplicantState}. Note that the supplicant state is Wi-Fi specific, and
    395      * is not generally the most useful thing to look at if you are just interested in
    396      * the overall state of connectivity.
    397      * @see #EXTRA_NEW_STATE
    398      * @see #EXTRA_SUPPLICANT_ERROR
    399      */
    400     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
    401     public static final String SUPPLICANT_STATE_CHANGED_ACTION =
    402         "android.net.wifi.supplicant.STATE_CHANGE";
    403     /**
    404      * The lookup key for a {@link SupplicantState} describing the new state
    405      * Retrieve with
    406      * {@link android.content.Intent#getParcelableExtra(String)}.
    407      */
    408     public static final String EXTRA_NEW_STATE = "newState";
    409 
    410     /**
    411      * The lookup key for a {@link SupplicantState} describing the supplicant
    412      * error code if any
    413      * Retrieve with
    414      * {@link android.content.Intent#getIntExtra(String, int)}.
    415      * @see #ERROR_AUTHENTICATING
    416      */
    417     public static final String EXTRA_SUPPLICANT_ERROR = "supplicantError";
    418 
    419     /**
    420      * Broadcast intent action indicating that the configured networks changed.
    421      * This can be as a result of adding/updating/deleting a network. If
    422      * {@link #EXTRA_MULTIPLE_NETWORKS_CHANGED} is set to true the new configuration
    423      * can be retreived with the {@link #EXTRA_WIFI_CONFIGURATION} extra. If multiple
    424      * Wi-Fi configurations changed, {@link #EXTRA_WIFI_CONFIGURATION} will not be present.
    425      * @hide
    426      */
    427     @SystemApi
    428     public static final String CONFIGURED_NETWORKS_CHANGED_ACTION =
    429         "android.net.wifi.CONFIGURED_NETWORKS_CHANGE";
    430     /**
    431      * The lookup key for a (@link android.net.wifi.WifiConfiguration} object representing
    432      * the changed Wi-Fi configuration when the {@link #CONFIGURED_NETWORKS_CHANGED_ACTION}
    433      * broadcast is sent.
    434      * @hide
    435      */
    436     @SystemApi
    437     public static final String EXTRA_WIFI_CONFIGURATION = "wifiConfiguration";
    438     /**
    439      * Multiple network configurations have changed.
    440      * @see #CONFIGURED_NETWORKS_CHANGED_ACTION
    441      *
    442      * @hide
    443      */
    444     @SystemApi
    445     public static final String EXTRA_MULTIPLE_NETWORKS_CHANGED = "multipleChanges";
    446     /**
    447      * The lookup key for an integer indicating the reason a Wi-Fi network configuration
    448      * has changed. Only present if {@link #EXTRA_MULTIPLE_NETWORKS_CHANGED} is {@code false}
    449      * @see #CONFIGURED_NETWORKS_CHANGED_ACTION
    450      * @hide
    451      */
    452     @SystemApi
    453     public static final String EXTRA_CHANGE_REASON = "changeReason";
    454     /**
    455      * The configuration is new and was added.
    456      * @hide
    457      */
    458     @SystemApi
    459     public static final int CHANGE_REASON_ADDED = 0;
    460     /**
    461      * The configuration was removed and is no longer present in the system's list of
    462      * configured networks.
    463      * @hide
    464      */
    465     @SystemApi
    466     public static final int CHANGE_REASON_REMOVED = 1;
    467     /**
    468      * The configuration has changed as a result of explicit action or because the system
    469      * took an automated action such as disabling a malfunctioning configuration.
    470      * @hide
    471      */
    472     @SystemApi
    473     public static final int CHANGE_REASON_CONFIG_CHANGE = 2;
    474     /**
    475      * An access point scan has completed, and results are available from the supplicant.
    476      * Call {@link #getScanResults()} to obtain the results. {@link #EXTRA_RESULTS_UPDATED}
    477      * indicates if the scan was completed successfully.
    478      */
    479     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
    480     public static final String SCAN_RESULTS_AVAILABLE_ACTION = "android.net.wifi.SCAN_RESULTS";
    481 
    482     /**
    483      * Lookup key for a {@code boolean} representing the result of previous {@link #startScan}
    484      * operation, reported with {@link #SCAN_RESULTS_AVAILABLE_ACTION}.
    485      * @return true scan was successful, results are updated
    486      * @return false scan was not successful, results haven't been updated since previous scan
    487      */
    488     public static final String EXTRA_RESULTS_UPDATED = "resultsUpdated";
    489 
    490     /**
    491      * A batch of access point scans has been completed and the results areavailable.
    492      * Call {@link #getBatchedScanResults()} to obtain the results.
    493      * @deprecated This API is nolonger supported.
    494      * Use {@link android.net.wifi.WifiScanner} API
    495      * @hide
    496      */
    497     @Deprecated
    498     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
    499     public static final String BATCHED_SCAN_RESULTS_AVAILABLE_ACTION =
    500             "android.net.wifi.BATCHED_RESULTS";
    501     /**
    502      * The RSSI (signal strength) has changed.
    503      * @see #EXTRA_NEW_RSSI
    504      */
    505     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
    506     public static final String RSSI_CHANGED_ACTION = "android.net.wifi.RSSI_CHANGED";
    507     /**
    508      * The lookup key for an {@code int} giving the new RSSI in dBm.
    509      */
    510     public static final String EXTRA_NEW_RSSI = "newRssi";
    511 
    512     /**
    513      * Broadcast intent action indicating that the link configuration
    514      * changed on wifi.
    515      * @hide
    516      */
    517     public static final String LINK_CONFIGURATION_CHANGED_ACTION =
    518         "android.net.wifi.LINK_CONFIGURATION_CHANGED";
    519 
    520     /**
    521      * The lookup key for a {@link android.net.LinkProperties} object associated with the
    522      * Wi-Fi network. Retrieve with
    523      * {@link android.content.Intent#getParcelableExtra(String)}.
    524      * @hide
    525      */
    526     public static final String EXTRA_LINK_PROPERTIES = "linkProperties";
    527 
    528     /**
    529      * The lookup key for a {@link android.net.NetworkCapabilities} object associated with the
    530      * Wi-Fi network. Retrieve with
    531      * {@link android.content.Intent#getParcelableExtra(String)}.
    532      * @hide
    533      */
    534     public static final String EXTRA_NETWORK_CAPABILITIES = "networkCapabilities";
    535 
    536     /**
    537      * The network IDs of the configured networks could have changed.
    538      */
    539     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
    540     public static final String NETWORK_IDS_CHANGED_ACTION = "android.net.wifi.NETWORK_IDS_CHANGED";
    541 
    542     /**
    543      * Activity Action: Show a system activity that allows the user to enable
    544      * scans to be available even with Wi-Fi turned off.
    545      *
    546      * <p>Notification of the result of this activity is posted using the
    547      * {@link android.app.Activity#onActivityResult} callback. The
    548      * <code>resultCode</code>
    549      * will be {@link android.app.Activity#RESULT_OK} if scan always mode has
    550      * been turned on or {@link android.app.Activity#RESULT_CANCELED} if the user
    551      * has rejected the request or an error has occurred.
    552      */
    553     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
    554     public static final String ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE =
    555             "android.net.wifi.action.REQUEST_SCAN_ALWAYS_AVAILABLE";
    556 
    557     /**
    558      * Activity Action: Pick a Wi-Fi network to connect to.
    559      * <p>Input: Nothing.
    560      * <p>Output: Nothing.
    561      */
    562     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
    563     public static final String ACTION_PICK_WIFI_NETWORK = "android.net.wifi.PICK_WIFI_NETWORK";
    564 
    565     /**
    566      * Internally used Wi-Fi lock mode representing the case were no locks are held.
    567      * @hide
    568      */
    569     public static final int WIFI_MODE_NO_LOCKS_HELD = 0;
    570 
    571     /**
    572      * In this Wi-Fi lock mode, Wi-Fi will be kept active,
    573      * and will behave normally, i.e., it will attempt to automatically
    574      * establish a connection to a remembered access point that is
    575      * within range, and will do periodic scans if there are remembered
    576      * access points but none are in range.
    577      */
    578     public static final int WIFI_MODE_FULL = 1;
    579     /**
    580      * In this Wi-Fi lock mode, Wi-Fi will be kept active,
    581      * but the only operation that will be supported is initiation of
    582      * scans, and the subsequent reporting of scan results. No attempts
    583      * will be made to automatically connect to remembered access points,
    584      * nor will periodic scans be automatically performed looking for
    585      * remembered access points. Scans must be explicitly requested by
    586      * an application in this mode.
    587      */
    588     public static final int WIFI_MODE_SCAN_ONLY = 2;
    589     /**
    590      * In this Wi-Fi lock mode, Wi-Fi will be kept active as in mode
    591      * {@link #WIFI_MODE_FULL} but it operates at high performance
    592      * with minimum packet loss and low packet latency even when
    593      * the device screen is off. This mode will consume more power
    594      * and hence should be used only when there is a need for such
    595      * an active connection.
    596      * <p>
    597      * An example use case is when a voice connection needs to be
    598      * kept active even after the device screen goes off. Holding the
    599      * regular {@link #WIFI_MODE_FULL} lock will keep the wifi
    600      * connection active, but the connection can be lossy.
    601      * Holding a {@link #WIFI_MODE_FULL_HIGH_PERF} lock for the
    602      * duration of the voice call will improve the call quality.
    603      * <p>
    604      * When there is no support from the hardware, this lock mode
    605      * will have the same behavior as {@link #WIFI_MODE_FULL}
    606      */
    607     public static final int WIFI_MODE_FULL_HIGH_PERF = 3;
    608 
    609     /** Anything worse than or equal to this will show 0 bars. */
    610     private static final int MIN_RSSI = -100;
    611 
    612     /** Anything better than or equal to this will show the max bars. */
    613     private static final int MAX_RSSI = -55;
    614 
    615     /**
    616      * Number of RSSI levels used in the framework to initiate
    617      * {@link #RSSI_CHANGED_ACTION} broadcast
    618      * @hide
    619      */
    620     public static final int RSSI_LEVELS = 5;
    621 
    622     /**
    623      * Auto settings in the driver. The driver could choose to operate on both
    624      * 2.4 GHz and 5 GHz or make a dynamic decision on selecting the band.
    625      * @hide
    626      */
    627     public static final int WIFI_FREQUENCY_BAND_AUTO = 0;
    628 
    629     /**
    630      * Operation on 5 GHz alone
    631      * @hide
    632      */
    633     public static final int WIFI_FREQUENCY_BAND_5GHZ = 1;
    634 
    635     /**
    636      * Operation on 2.4 GHz alone
    637      * @hide
    638      */
    639     public static final int WIFI_FREQUENCY_BAND_2GHZ = 2;
    640 
    641     /** List of asyncronous notifications
    642      * @hide
    643      */
    644     public static final int DATA_ACTIVITY_NOTIFICATION = 1;
    645 
    646     //Lowest bit indicates data reception and the second lowest
    647     //bit indicates data transmitted
    648     /** @hide */
    649     public static final int DATA_ACTIVITY_NONE         = 0x00;
    650     /** @hide */
    651     public static final int DATA_ACTIVITY_IN           = 0x01;
    652     /** @hide */
    653     public static final int DATA_ACTIVITY_OUT          = 0x02;
    654     /** @hide */
    655     public static final int DATA_ACTIVITY_INOUT        = 0x03;
    656 
    657     /** @hide */
    658     public static final boolean DEFAULT_POOR_NETWORK_AVOIDANCE_ENABLED = false;
    659 
    660     /* Maximum number of active locks we allow.
    661      * This limit was added to prevent apps from creating a ridiculous number
    662      * of locks and crashing the system by overflowing the global ref table.
    663      */
    664     private static final int MAX_ACTIVE_LOCKS = 50;
    665 
    666     /* Number of currently active WifiLocks and MulticastLocks */
    667     private int mActiveLockCount;
    668 
    669     private Context mContext;
    670     IWifiManager mService;
    671     private final int mTargetSdkVersion;
    672 
    673     private static final int INVALID_KEY = 0;
    674     private int mListenerKey = 1;
    675     private final SparseArray mListenerMap = new SparseArray();
    676     private final Object mListenerMapLock = new Object();
    677 
    678     private AsyncChannel mAsyncChannel;
    679     private CountDownLatch mConnected;
    680     private Looper mLooper;
    681 
    682     /**
    683      * Create a new WifiManager instance.
    684      * Applications will almost always want to use
    685      * {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve
    686      * the standard {@link android.content.Context#WIFI_SERVICE Context.WIFI_SERVICE}.
    687      * @param context the application context
    688      * @param service the Binder interface
    689      * @hide - hide this because it takes in a parameter of type IWifiManager, which
    690      * is a system private class.
    691      */
    692     public WifiManager(Context context, IWifiManager service, Looper looper) {
    693         mContext = context;
    694         mService = service;
    695         mLooper = looper;
    696         mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
    697     }
    698 
    699     /**
    700      * Return a list of all the networks configured in the supplicant.
    701      * Not all fields of WifiConfiguration are returned. Only the following
    702      * fields are filled in:
    703      * <ul>
    704      * <li>networkId</li>
    705      * <li>SSID</li>
    706      * <li>BSSID</li>
    707      * <li>priority</li>
    708      * <li>allowedProtocols</li>
    709      * <li>allowedKeyManagement</li>
    710      * <li>allowedAuthAlgorithms</li>
    711      * <li>allowedPairwiseCiphers</li>
    712      * <li>allowedGroupCiphers</li>
    713      * </ul>
    714      * @return a list of network configurations in the form of a list
    715      * of {@link WifiConfiguration} objects. Upon failure to fetch or
    716      * when Wi-Fi is turned off, it can be null.
    717      */
    718     public List<WifiConfiguration> getConfiguredNetworks() {
    719         try {
    720             return mService.getConfiguredNetworks();
    721         } catch (RemoteException e) {
    722             throw e.rethrowFromSystemServer();
    723         }
    724     }
    725 
    726     /** @hide */
    727     @SystemApi
    728     public List<WifiConfiguration> getPrivilegedConfiguredNetworks() {
    729         try {
    730             return mService.getPrivilegedConfiguredNetworks();
    731         } catch (RemoteException e) {
    732             throw e.rethrowFromSystemServer();
    733         }
    734     }
    735 
    736     /** @hide */
    737     @SystemApi
    738     public WifiConnectionStatistics getConnectionStatistics() {
    739         try {
    740             return mService.getConnectionStatistics();
    741         } catch (RemoteException e) {
    742             throw e.rethrowFromSystemServer();
    743         }
    744     }
    745 
    746     /**
    747      * Returns a WifiConfiguration matching this ScanResult
    748      * @param scanResult scanResult that represents the BSSID
    749      * @return {@link WifiConfiguration} that matches this BSSID or null
    750      * @hide
    751      */
    752     public WifiConfiguration getMatchingWifiConfig(ScanResult scanResult) {
    753         try {
    754             return mService.getMatchingWifiConfig(scanResult);
    755         } catch (RemoteException e) {
    756             throw e.rethrowFromSystemServer();
    757         }
    758     }
    759 
    760     /**
    761      * Add a new network description to the set of configured networks.
    762      * The {@code networkId} field of the supplied configuration object
    763      * is ignored.
    764      * <p/>
    765      * The new network will be marked DISABLED by default. To enable it,
    766      * called {@link #enableNetwork}.
    767      *
    768      * @param config the set of variables that describe the configuration,
    769      *            contained in a {@link WifiConfiguration} object.
    770      * @return the ID of the newly created network description. This is used in
    771      *         other operations to specified the network to be acted upon.
    772      *         Returns {@code -1} on failure.
    773      */
    774     public int addNetwork(WifiConfiguration config) {
    775         if (config == null) {
    776             return -1;
    777         }
    778         config.networkId = -1;
    779         return addOrUpdateNetwork(config);
    780     }
    781 
    782     /**
    783      * Update the network description of an existing configured network.
    784      *
    785      * @param config the set of variables that describe the configuration,
    786      *            contained in a {@link WifiConfiguration} object. It may
    787      *            be sparse, so that only the items that are being changed
    788      *            are non-<code>null</code>. The {@code networkId} field
    789      *            must be set to the ID of the existing network being updated.
    790      * @return Returns the {@code networkId} of the supplied
    791      *         {@code WifiConfiguration} on success.
    792      *         <br/>
    793      *         Returns {@code -1} on failure, including when the {@code networkId}
    794      *         field of the {@code WifiConfiguration} does not refer to an
    795      *         existing network.
    796      */
    797     public int updateNetwork(WifiConfiguration config) {
    798         if (config == null || config.networkId < 0) {
    799             return -1;
    800         }
    801         return addOrUpdateNetwork(config);
    802     }
    803 
    804     /**
    805      * Internal method for doing the RPC that creates a new network description
    806      * or updates an existing one.
    807      *
    808      * @param config The possibly sparse object containing the variables that
    809      *         are to set or updated in the network description.
    810      * @return the ID of the network on success, {@code -1} on failure.
    811      */
    812     private int addOrUpdateNetwork(WifiConfiguration config) {
    813         try {
    814             return mService.addOrUpdateNetwork(config);
    815         } catch (RemoteException e) {
    816             throw e.rethrowFromSystemServer();
    817         }
    818     }
    819 
    820     /**
    821      * Add a Hotspot 2.0 release 2 Management Object
    822      * @param mo The MO in XML form
    823      * @return -1 for failure
    824      * @hide
    825      */
    826     public int addPasspointManagementObject(String mo) {
    827         try {
    828             return mService.addPasspointManagementObject(mo);
    829         } catch (RemoteException e) {
    830             throw e.rethrowFromSystemServer();
    831         }
    832     }
    833 
    834     /**
    835      * Modify a Hotspot 2.0 release 2 Management Object
    836      * @param fqdn The FQDN of the service provider
    837      * @param mos A List of MO definitions to be updated
    838      * @return the number of nodes updated, or -1 for failure
    839      * @hide
    840      */
    841     public int modifyPasspointManagementObject(String fqdn,
    842                                                List<PasspointManagementObjectDefinition> mos) {
    843         try {
    844             return mService.modifyPasspointManagementObject(fqdn, mos);
    845         } catch (RemoteException e) {
    846             throw e.rethrowFromSystemServer();
    847         }
    848     }
    849 
    850     /**
    851      * Query for a Hotspot 2.0 release 2 OSU icon
    852      * @param bssid The BSSID of the AP
    853      * @param fileName Icon file name
    854      * @hide
    855      */
    856     public void queryPasspointIcon(long bssid, String fileName) {
    857         try {
    858             mService.queryPasspointIcon(bssid, fileName);
    859         } catch (RemoteException e) {
    860             throw e.rethrowFromSystemServer();
    861         }
    862     }
    863 
    864     /**
    865      * Match the currently associated network against the SP matching the given FQDN
    866      * @param fqdn FQDN of the SP
    867      * @return ordinal [HomeProvider, RoamingProvider, Incomplete, None, Declined]
    868      * @hide
    869      */
    870     public int matchProviderWithCurrentNetwork(String fqdn) {
    871         try {
    872             return mService.matchProviderWithCurrentNetwork(fqdn);
    873         } catch (RemoteException e) {
    874             throw e.rethrowFromSystemServer();
    875         }
    876     }
    877 
    878     /**
    879      * Deauthenticate and set the re-authentication hold off time for the current network
    880      * @param holdoff hold off time in milliseconds
    881      * @param ess set if the hold off pertains to an ESS rather than a BSS
    882      * @hide
    883      */
    884     public void deauthenticateNetwork(long holdoff, boolean ess) {
    885         try {
    886             mService.deauthenticateNetwork(holdoff, ess);
    887         } catch (RemoteException e) {
    888             throw e.rethrowFromSystemServer();
    889         }
    890     }
    891 
    892     /**
    893      * Remove the specified network from the list of configured networks.
    894      * This may result in the asynchronous delivery of state change
    895      * events.
    896      * @param netId the integer that identifies the network configuration
    897      * to the supplicant
    898      * @return {@code true} if the operation succeeded
    899      */
    900     public boolean removeNetwork(int netId) {
    901         try {
    902             return mService.removeNetwork(netId);
    903         } catch (RemoteException e) {
    904             throw e.rethrowFromSystemServer();
    905         }
    906     }
    907 
    908     /**
    909      * Allow a previously configured network to be associated with. If
    910      * <code>disableOthers</code> is true, then all other configured
    911      * networks are disabled, and an attempt to connect to the selected
    912      * network is initiated. This may result in the asynchronous delivery
    913      * of state change events.
    914      * <p>
    915      * <b>Note:</b> If an application's target SDK version is
    916      * {@link android.os.Build.VERSION_CODES#LOLLIPOP} or newer, network
    917      * communication may not use Wi-Fi even if Wi-Fi is connected; traffic may
    918      * instead be sent through another network, such as cellular data,
    919      * Bluetooth tethering, or Ethernet. For example, traffic will never use a
    920      * Wi-Fi network that does not provide Internet access (e.g. a wireless
    921      * printer), if another network that does offer Internet access (e.g.
    922      * cellular data) is available. Applications that need to ensure that their
    923      * network traffic uses Wi-Fi should use APIs such as
    924      * {@link Network#bindSocket(java.net.Socket)},
    925      * {@link Network#openConnection(java.net.URL)}, or
    926      * {@link ConnectivityManager#bindProcessToNetwork} to do so.
    927      *
    928      * @param netId the ID of the network in the list of configured networks
    929      * @param disableOthers if true, disable all other networks. The way to
    930      * select a particular network to connect to is specify {@code true}
    931      * for this parameter.
    932      * @return {@code true} if the operation succeeded
    933      */
    934     public boolean enableNetwork(int netId, boolean disableOthers) {
    935         final boolean pin = disableOthers && mTargetSdkVersion < Build.VERSION_CODES.LOLLIPOP;
    936         if (pin) {
    937             NetworkRequest request = new NetworkRequest.Builder()
    938                     .clearCapabilities()
    939                     .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    940                     .build();
    941             NetworkPinner.pin(mContext, request);
    942         }
    943 
    944         boolean success;
    945         try {
    946             success = mService.enableNetwork(netId, disableOthers);
    947         } catch (RemoteException e) {
    948             throw e.rethrowFromSystemServer();
    949         }
    950 
    951         if (pin && !success) {
    952             NetworkPinner.unpin();
    953         }
    954 
    955         return success;
    956     }
    957 
    958     /**
    959      * Disable a configured network. The specified network will not be
    960      * a candidate for associating. This may result in the asynchronous
    961      * delivery of state change events.
    962      * @param netId the ID of the network as returned by {@link #addNetwork}.
    963      * @return {@code true} if the operation succeeded
    964      */
    965     public boolean disableNetwork(int netId) {
    966         try {
    967             return mService.disableNetwork(netId);
    968         } catch (RemoteException e) {
    969             throw e.rethrowFromSystemServer();
    970         }
    971     }
    972 
    973     /**
    974      * Disassociate from the currently active access point. This may result
    975      * in the asynchronous delivery of state change events.
    976      * @return {@code true} if the operation succeeded
    977      */
    978     public boolean disconnect() {
    979         try {
    980             mService.disconnect();
    981             return true;
    982         } catch (RemoteException e) {
    983             throw e.rethrowFromSystemServer();
    984         }
    985     }
    986 
    987     /**
    988      * Reconnect to the currently active access point, if we are currently
    989      * disconnected. This may result in the asynchronous delivery of state
    990      * change events.
    991      * @return {@code true} if the operation succeeded
    992      */
    993     public boolean reconnect() {
    994         try {
    995             mService.reconnect();
    996             return true;
    997         } catch (RemoteException e) {
    998             throw e.rethrowFromSystemServer();
    999         }
   1000     }
   1001 
   1002     /**
   1003      * Reconnect to the currently active access point, even if we are already
   1004      * connected. This may result in the asynchronous delivery of state
   1005      * change events.
   1006      * @return {@code true} if the operation succeeded
   1007      */
   1008     public boolean reassociate() {
   1009         try {
   1010             mService.reassociate();
   1011             return true;
   1012         } catch (RemoteException e) {
   1013             throw e.rethrowFromSystemServer();
   1014         }
   1015     }
   1016 
   1017     /**
   1018      * Check that the supplicant daemon is responding to requests.
   1019      * @return {@code true} if we were able to communicate with the supplicant and
   1020      * it returned the expected response to the PING message.
   1021      */
   1022     public boolean pingSupplicant() {
   1023         if (mService == null)
   1024             return false;
   1025         try {
   1026             return mService.pingSupplicant();
   1027         } catch (RemoteException e) {
   1028             throw e.rethrowFromSystemServer();
   1029         }
   1030     }
   1031 
   1032     /* Keep this list in sync with wifi_hal.h */
   1033     /** @hide */
   1034     public static final int WIFI_FEATURE_INFRA            = 0x0001;  // Basic infrastructure mode
   1035     /** @hide */
   1036     public static final int WIFI_FEATURE_INFRA_5G         = 0x0002;  // Support for 5 GHz Band
   1037     /** @hide */
   1038     public static final int WIFI_FEATURE_PASSPOINT        = 0x0004;  // Support for GAS/ANQP
   1039     /** @hide */
   1040     public static final int WIFI_FEATURE_P2P              = 0x0008;  // Wifi-Direct
   1041     /** @hide */
   1042     public static final int WIFI_FEATURE_MOBILE_HOTSPOT   = 0x0010;  // Soft AP
   1043     /** @hide */
   1044     public static final int WIFI_FEATURE_SCANNER          = 0x0020;  // WifiScanner APIs
   1045     /** @hide */
   1046     public static final int WIFI_FEATURE_NAN              = 0x0040;  // Neighbor Awareness Networking
   1047     /** @hide */
   1048     public static final int WIFI_FEATURE_D2D_RTT          = 0x0080;  // Device-to-device RTT
   1049     /** @hide */
   1050     public static final int WIFI_FEATURE_D2AP_RTT         = 0x0100;  // Device-to-AP RTT
   1051     /** @hide */
   1052     public static final int WIFI_FEATURE_BATCH_SCAN       = 0x0200;  // Batched Scan (deprecated)
   1053     /** @hide */
   1054     public static final int WIFI_FEATURE_PNO              = 0x0400;  // Preferred network offload
   1055     /** @hide */
   1056     public static final int WIFI_FEATURE_ADDITIONAL_STA   = 0x0800;  // Support for two STAs
   1057     /** @hide */
   1058     public static final int WIFI_FEATURE_TDLS             = 0x1000;  // Tunnel directed link setup
   1059     /** @hide */
   1060     public static final int WIFI_FEATURE_TDLS_OFFCHANNEL  = 0x2000;  // Support for TDLS off channel
   1061     /** @hide */
   1062     public static final int WIFI_FEATURE_EPR              = 0x4000;  // Enhanced power reporting
   1063     /** @hide */
   1064     public static final int WIFI_FEATURE_AP_STA            = 0x8000;  // Support for AP STA Concurrency
   1065     /** @hide */
   1066     public static final int WIFI_FEATURE_LINK_LAYER_STATS  = 0x10000; // Link layer stats collection
   1067     /** @hide */
   1068     public static final int WIFI_FEATURE_LOGGER            = 0x20000; // WiFi Logger
   1069     /** @hide */
   1070     public static final int WIFI_FEATURE_HAL_EPNO          = 0x40000; // WiFi PNO enhanced
   1071 
   1072     private int getSupportedFeatures() {
   1073         try {
   1074             return mService.getSupportedFeatures();
   1075         } catch (RemoteException e) {
   1076             throw e.rethrowFromSystemServer();
   1077         }
   1078     }
   1079 
   1080     private boolean isFeatureSupported(int feature) {
   1081         return (getSupportedFeatures() & feature) == feature;
   1082     }
   1083     /**
   1084      * @return true if this adapter supports 5 GHz band
   1085      */
   1086     public boolean is5GHzBandSupported() {
   1087         return isFeatureSupported(WIFI_FEATURE_INFRA_5G);
   1088     }
   1089 
   1090     /**
   1091      * @return true if this adapter supports passpoint
   1092      * @hide
   1093      */
   1094     public boolean isPasspointSupported() {
   1095         return isFeatureSupported(WIFI_FEATURE_PASSPOINT);
   1096     }
   1097 
   1098     /**
   1099      * @return true if this adapter supports WifiP2pManager (Wi-Fi Direct)
   1100      */
   1101     public boolean isP2pSupported() {
   1102         return isFeatureSupported(WIFI_FEATURE_P2P);
   1103     }
   1104 
   1105     /**
   1106      * @return true if this adapter supports portable Wi-Fi hotspot
   1107      * @hide
   1108      */
   1109     @SystemApi
   1110     public boolean isPortableHotspotSupported() {
   1111         return isFeatureSupported(WIFI_FEATURE_MOBILE_HOTSPOT);
   1112     }
   1113 
   1114     /**
   1115      * @return true if this adapter supports WifiScanner APIs
   1116      * @hide
   1117      */
   1118     @SystemApi
   1119     public boolean isWifiScannerSupported() {
   1120         return isFeatureSupported(WIFI_FEATURE_SCANNER);
   1121     }
   1122 
   1123     /**
   1124      * @return true if this adapter supports Neighbour Awareness Network APIs
   1125      * @hide PROPOSED_NAN_API
   1126      */
   1127     public boolean isNanSupported() {
   1128         return isFeatureSupported(WIFI_FEATURE_NAN);
   1129     }
   1130 
   1131     /**
   1132      * @return true if this adapter supports Device-to-device RTT
   1133      * @hide
   1134      */
   1135     @SystemApi
   1136     public boolean isDeviceToDeviceRttSupported() {
   1137         return isFeatureSupported(WIFI_FEATURE_D2D_RTT);
   1138     }
   1139 
   1140     /**
   1141      * @return true if this adapter supports Device-to-AP RTT
   1142      */
   1143     @SystemApi
   1144     public boolean isDeviceToApRttSupported() {
   1145         return isFeatureSupported(WIFI_FEATURE_D2AP_RTT);
   1146     }
   1147 
   1148     /**
   1149      * @return true if this adapter supports offloaded connectivity scan
   1150      */
   1151     public boolean isPreferredNetworkOffloadSupported() {
   1152         return isFeatureSupported(WIFI_FEATURE_PNO);
   1153     }
   1154 
   1155     /**
   1156      * @return true if this adapter supports multiple simultaneous connections
   1157      * @hide
   1158      */
   1159     public boolean isAdditionalStaSupported() {
   1160         return isFeatureSupported(WIFI_FEATURE_ADDITIONAL_STA);
   1161     }
   1162 
   1163     /**
   1164      * @return true if this adapter supports Tunnel Directed Link Setup
   1165      */
   1166     public boolean isTdlsSupported() {
   1167         return isFeatureSupported(WIFI_FEATURE_TDLS);
   1168     }
   1169 
   1170     /**
   1171      * @return true if this adapter supports Off Channel Tunnel Directed Link Setup
   1172      * @hide
   1173      */
   1174     public boolean isOffChannelTdlsSupported() {
   1175         return isFeatureSupported(WIFI_FEATURE_TDLS_OFFCHANNEL);
   1176     }
   1177 
   1178     /**
   1179      * @return true if this adapter supports advanced power/performance counters
   1180      */
   1181     public boolean isEnhancedPowerReportingSupported() {
   1182         return isFeatureSupported(WIFI_FEATURE_LINK_LAYER_STATS);
   1183     }
   1184 
   1185     /**
   1186      * Return the record of {@link WifiActivityEnergyInfo} object that
   1187      * has the activity and energy info. This can be used to ascertain what
   1188      * the controller has been up to, since the last sample.
   1189      * @param updateType Type of info, cached vs refreshed.
   1190      *
   1191      * @return a record with {@link WifiActivityEnergyInfo} or null if
   1192      * report is unavailable or unsupported
   1193      * @hide
   1194      */
   1195     public WifiActivityEnergyInfo getControllerActivityEnergyInfo(int updateType) {
   1196         if (mService == null) return null;
   1197         try {
   1198             synchronized(this) {
   1199                 return mService.reportActivityInfo();
   1200             }
   1201         } catch (RemoteException e) {
   1202             throw e.rethrowFromSystemServer();
   1203         }
   1204     }
   1205 
   1206     /**
   1207      * Request a scan for access points. Returns immediately. The availability
   1208      * of the results is made known later by means of an asynchronous event sent
   1209      * on completion of the scan.
   1210      * @return {@code true} if the operation succeeded, i.e., the scan was initiated
   1211      */
   1212     public boolean startScan() {
   1213         try {
   1214             mService.startScan(null, null);
   1215             return true;
   1216         } catch (RemoteException e) {
   1217             throw e.rethrowFromSystemServer();
   1218         }
   1219     }
   1220 
   1221     /** @hide */
   1222     @SystemApi
   1223     public boolean startScan(WorkSource workSource) {
   1224         try {
   1225             mService.startScan(null, workSource);
   1226             return true;
   1227         } catch (RemoteException e) {
   1228             throw e.rethrowFromSystemServer();
   1229         }
   1230     }
   1231 
   1232     /**
   1233      * startLocationRestrictedScan()
   1234      * Trigger a scan which will not make use of DFS channels and is thus not suitable for
   1235      * establishing wifi connection.
   1236      * @deprecated This API is nolonger supported.
   1237      * Use {@link android.net.wifi.WifiScanner} API
   1238      * @hide
   1239      */
   1240     @Deprecated
   1241     @SystemApi
   1242     public boolean startLocationRestrictedScan(WorkSource workSource) {
   1243         return false;
   1244     }
   1245 
   1246     /**
   1247      * Check if the Batched Scan feature is supported.
   1248      *
   1249      * @return false if not supported.
   1250      * @deprecated This API is nolonger supported.
   1251      * Use {@link android.net.wifi.WifiScanner} API
   1252      * @hide
   1253      */
   1254     @Deprecated
   1255     @SystemApi
   1256     public boolean isBatchedScanSupported() {
   1257         return false;
   1258     }
   1259 
   1260     /**
   1261      * Retrieve the latest batched scan result.  This should be called immediately after
   1262      * {@link BATCHED_SCAN_RESULTS_AVAILABLE_ACTION} is received.
   1263      * @deprecated This API is nolonger supported.
   1264      * Use {@link android.net.wifi.WifiScanner} API
   1265      * @hide
   1266      */
   1267     @Deprecated
   1268     @SystemApi
   1269     public List<BatchedScanResult> getBatchedScanResults() {
   1270         return null;
   1271     }
   1272 
   1273     /**
   1274      * Creates a configuration token describing the network referenced by {@code netId}
   1275      * of MIME type application/vnd.wfa.wsc. Can be used to configure WiFi networks via NFC.
   1276      *
   1277      * @return hex-string encoded configuration token
   1278      * @hide
   1279      */
   1280     public String getWpsNfcConfigurationToken(int netId) {
   1281         try {
   1282             return mService.getWpsNfcConfigurationToken(netId);
   1283         } catch (RemoteException e) {
   1284             throw e.rethrowFromSystemServer();
   1285         }
   1286     }
   1287 
   1288     /**
   1289      * Return dynamic information about the current Wi-Fi connection, if any is active.
   1290      * @return the Wi-Fi information, contained in {@link WifiInfo}.
   1291      */
   1292     public WifiInfo getConnectionInfo() {
   1293         try {
   1294             return mService.getConnectionInfo();
   1295         } catch (RemoteException e) {
   1296             throw e.rethrowFromSystemServer();
   1297         }
   1298     }
   1299 
   1300     /**
   1301      * Return the results of the latest access point scan.
   1302      * @return the list of access points found in the most recent scan. An app must hold
   1303      * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION ACCESS_COARSE_LOCATION} or
   1304      * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission
   1305      * in order to get valid results.  If there is a remote exception (e.g., either a communication
   1306      * problem with the system service or an exception within the framework) an empty list will be
   1307      * returned.
   1308      */
   1309     public List<ScanResult> getScanResults() {
   1310         try {
   1311             return mService.getScanResults(mContext.getOpPackageName());
   1312         } catch (RemoteException e) {
   1313             throw e.rethrowFromSystemServer();
   1314         }
   1315     }
   1316 
   1317     /**
   1318      * Check if scanning is always available.
   1319      *
   1320      * If this return {@code true}, apps can issue {@link #startScan} and fetch scan results
   1321      * even when Wi-Fi is turned off.
   1322      *
   1323      * To change this setting, see {@link #ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE}.
   1324      */
   1325     public boolean isScanAlwaysAvailable() {
   1326         try {
   1327             return mService.isScanAlwaysAvailable();
   1328         } catch (RemoteException e) {
   1329             throw e.rethrowFromSystemServer();
   1330         }
   1331     }
   1332 
   1333     /**
   1334      * Tell the supplicant to persist the current list of configured networks.
   1335      * <p>
   1336      * Note: It is possible for this method to change the network IDs of
   1337      * existing networks. You should assume the network IDs can be different
   1338      * after calling this method.
   1339      *
   1340      * @return {@code true} if the operation succeeded
   1341      */
   1342     public boolean saveConfiguration() {
   1343         try {
   1344             return mService.saveConfiguration();
   1345         } catch (RemoteException e) {
   1346             throw e.rethrowFromSystemServer();
   1347         }
   1348     }
   1349 
   1350     /**
   1351      * Set the country code.
   1352      * @param countryCode country code in ISO 3166 format.
   1353      * @param persist {@code true} if this needs to be remembered
   1354      *
   1355      * @hide
   1356      */
   1357     public void setCountryCode(String country, boolean persist) {
   1358         try {
   1359             mService.setCountryCode(country, persist);
   1360         } catch (RemoteException e) {
   1361             throw e.rethrowFromSystemServer();
   1362         }
   1363     }
   1364 
   1365     /**
   1366     * get the country code.
   1367     * @return the country code in ISO 3166 format.
   1368     *
   1369     * @hide
   1370     */
   1371     public String getCountryCode() {
   1372        try {
   1373            String country = mService.getCountryCode();
   1374            return country;
   1375        } catch (RemoteException e) {
   1376            throw e.rethrowFromSystemServer();
   1377        }
   1378     }
   1379 
   1380     /**
   1381      * Set the operational frequency band.
   1382      * @param band  One of
   1383      *     {@link #WIFI_FREQUENCY_BAND_AUTO},
   1384      *     {@link #WIFI_FREQUENCY_BAND_5GHZ},
   1385      *     {@link #WIFI_FREQUENCY_BAND_2GHZ},
   1386      * @param persist {@code true} if this needs to be remembered
   1387      * @hide
   1388      */
   1389     public void setFrequencyBand(int band, boolean persist) {
   1390         try {
   1391             mService.setFrequencyBand(band, persist);
   1392         } catch (RemoteException e) {
   1393             throw e.rethrowFromSystemServer();
   1394         }
   1395     }
   1396 
   1397     /**
   1398      * Get the operational frequency band.
   1399      * @return One of
   1400      *     {@link #WIFI_FREQUENCY_BAND_AUTO},
   1401      *     {@link #WIFI_FREQUENCY_BAND_5GHZ},
   1402      *     {@link #WIFI_FREQUENCY_BAND_2GHZ} or
   1403      *     {@code -1} on failure.
   1404      * @hide
   1405      */
   1406     public int getFrequencyBand() {
   1407         try {
   1408             return mService.getFrequencyBand();
   1409         } catch (RemoteException e) {
   1410             throw e.rethrowFromSystemServer();
   1411         }
   1412     }
   1413 
   1414     /**
   1415      * Check if the chipset supports dual frequency band (2.4 GHz and 5 GHz)
   1416      * @return {@code true} if supported, {@code false} otherwise.
   1417      * @hide
   1418      */
   1419     public boolean isDualBandSupported() {
   1420         try {
   1421             return mService.isDualBandSupported();
   1422         } catch (RemoteException e) {
   1423             throw e.rethrowFromSystemServer();
   1424         }
   1425     }
   1426 
   1427     /**
   1428      * Return the DHCP-assigned addresses from the last successful DHCP request,
   1429      * if any.
   1430      * @return the DHCP information
   1431      */
   1432     public DhcpInfo getDhcpInfo() {
   1433         try {
   1434             return mService.getDhcpInfo();
   1435         } catch (RemoteException e) {
   1436             throw e.rethrowFromSystemServer();
   1437         }
   1438     }
   1439 
   1440     /**
   1441      * Enable or disable Wi-Fi.
   1442      * @param enabled {@code true} to enable, {@code false} to disable.
   1443      * @return {@code true} if the operation succeeds (or if the existing state
   1444      *         is the same as the requested state).
   1445      */
   1446     public boolean setWifiEnabled(boolean enabled) {
   1447         try {
   1448             return mService.setWifiEnabled(enabled);
   1449         } catch (RemoteException e) {
   1450             throw e.rethrowFromSystemServer();
   1451         }
   1452     }
   1453 
   1454     /**
   1455      * Gets the Wi-Fi enabled state.
   1456      * @return One of {@link #WIFI_STATE_DISABLED},
   1457      *         {@link #WIFI_STATE_DISABLING}, {@link #WIFI_STATE_ENABLED},
   1458      *         {@link #WIFI_STATE_ENABLING}, {@link #WIFI_STATE_UNKNOWN}
   1459      * @see #isWifiEnabled()
   1460      */
   1461     public int getWifiState() {
   1462         try {
   1463             return mService.getWifiEnabledState();
   1464         } catch (RemoteException e) {
   1465             throw e.rethrowFromSystemServer();
   1466         }
   1467     }
   1468 
   1469     /**
   1470      * Return whether Wi-Fi is enabled or disabled.
   1471      * @return {@code true} if Wi-Fi is enabled
   1472      * @see #getWifiState()
   1473      */
   1474     public boolean isWifiEnabled() {
   1475         return getWifiState() == WIFI_STATE_ENABLED;
   1476     }
   1477 
   1478     /**
   1479      * Return TX packet counter, for CTS test of WiFi watchdog.
   1480      * @param listener is the interface to receive result
   1481      *
   1482      * @hide for CTS test only
   1483      */
   1484     public void getTxPacketCount(TxPacketCountListener listener) {
   1485         getChannel().sendMessage(RSSI_PKTCNT_FETCH, 0, putListener(listener));
   1486     }
   1487 
   1488     /**
   1489      * Calculates the level of the signal. This should be used any time a signal
   1490      * is being shown.
   1491      *
   1492      * @param rssi The power of the signal measured in RSSI.
   1493      * @param numLevels The number of levels to consider in the calculated
   1494      *            level.
   1495      * @return A level of the signal, given in the range of 0 to numLevels-1
   1496      *         (both inclusive).
   1497      */
   1498     public static int calculateSignalLevel(int rssi, int numLevels) {
   1499         if (rssi <= MIN_RSSI) {
   1500             return 0;
   1501         } else if (rssi >= MAX_RSSI) {
   1502             return numLevels - 1;
   1503         } else {
   1504             float inputRange = (MAX_RSSI - MIN_RSSI);
   1505             float outputRange = (numLevels - 1);
   1506             return (int)((float)(rssi - MIN_RSSI) * outputRange / inputRange);
   1507         }
   1508     }
   1509 
   1510     /**
   1511      * Compares two signal strengths.
   1512      *
   1513      * @param rssiA The power of the first signal measured in RSSI.
   1514      * @param rssiB The power of the second signal measured in RSSI.
   1515      * @return Returns <0 if the first signal is weaker than the second signal,
   1516      *         0 if the two signals have the same strength, and >0 if the first
   1517      *         signal is stronger than the second signal.
   1518      */
   1519     public static int compareSignalLevel(int rssiA, int rssiB) {
   1520         return rssiA - rssiB;
   1521     }
   1522 
   1523     /**
   1524      * Start AccessPoint mode with the specified
   1525      * configuration. If the radio is already running in
   1526      * AP mode, update the new configuration
   1527      * Note that starting in access point mode disables station
   1528      * mode operation
   1529      * @param wifiConfig SSID, security and channel details as
   1530      *        part of WifiConfiguration
   1531      * @return {@code true} if the operation succeeds, {@code false} otherwise
   1532      *
   1533      * @hide
   1534      */
   1535     @SystemApi
   1536     public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
   1537         try {
   1538             mService.setWifiApEnabled(wifiConfig, enabled);
   1539             return true;
   1540         } catch (RemoteException e) {
   1541             throw e.rethrowFromSystemServer();
   1542         }
   1543     }
   1544 
   1545     /**
   1546      * Gets the Wi-Fi enabled state.
   1547      * @return One of {@link #WIFI_AP_STATE_DISABLED},
   1548      *         {@link #WIFI_AP_STATE_DISABLING}, {@link #WIFI_AP_STATE_ENABLED},
   1549      *         {@link #WIFI_AP_STATE_ENABLING}, {@link #WIFI_AP_STATE_FAILED}
   1550      * @see #isWifiApEnabled()
   1551      *
   1552      * @hide
   1553      */
   1554     @SystemApi
   1555     public int getWifiApState() {
   1556         try {
   1557             return mService.getWifiApEnabledState();
   1558         } catch (RemoteException e) {
   1559             throw e.rethrowFromSystemServer();
   1560         }
   1561     }
   1562 
   1563     /**
   1564      * Return whether Wi-Fi AP is enabled or disabled.
   1565      * @return {@code true} if Wi-Fi AP is enabled
   1566      * @see #getWifiApState()
   1567      *
   1568      * @hide
   1569      */
   1570     @SystemApi
   1571     public boolean isWifiApEnabled() {
   1572         return getWifiApState() == WIFI_AP_STATE_ENABLED;
   1573     }
   1574 
   1575     /**
   1576      * Gets the Wi-Fi AP Configuration.
   1577      * @return AP details in WifiConfiguration
   1578      *
   1579      * @hide
   1580      */
   1581     @SystemApi
   1582     public WifiConfiguration getWifiApConfiguration() {
   1583         try {
   1584             return mService.getWifiApConfiguration();
   1585         } catch (RemoteException e) {
   1586             throw e.rethrowFromSystemServer();
   1587         }
   1588     }
   1589 
   1590     /**
   1591      * Builds a WifiConfiguration from Hotspot 2.0 MIME file.
   1592      * @return AP details in WifiConfiguration
   1593      *
   1594      * @hide Dont open yet
   1595      */
   1596     public WifiConfiguration buildWifiConfig(String uriString, String mimeType, byte[] data) {
   1597         try {
   1598             return mService.buildWifiConfig(uriString, mimeType, data);
   1599         } catch (RemoteException e) {
   1600             throw e.rethrowFromSystemServer();
   1601         }
   1602     }
   1603 
   1604     /**
   1605      * Sets the Wi-Fi AP Configuration.
   1606      * @return {@code true} if the operation succeeded, {@code false} otherwise
   1607      *
   1608      * @hide
   1609      */
   1610     @SystemApi
   1611     public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
   1612         try {
   1613             mService.setWifiApConfiguration(wifiConfig);
   1614             return true;
   1615         } catch (RemoteException e) {
   1616             throw e.rethrowFromSystemServer();
   1617         }
   1618     }
   1619 
   1620     /**
   1621      * Add a bssid to the supplicant blacklist
   1622      *
   1623      * This API is used by WifiWatchdogService
   1624      *
   1625      * @return {@code true} if the operation succeeds else {@code false}
   1626      * @hide
   1627      */
   1628     public boolean addToBlacklist(String bssid) {
   1629         try {
   1630             mService.addToBlacklist(bssid);
   1631             return true;
   1632         } catch (RemoteException e) {
   1633             throw e.rethrowFromSystemServer();
   1634         }
   1635     }
   1636 
   1637     /**
   1638      * Clear the supplicant blacklist
   1639      *
   1640      * This API is used by WifiWatchdogService
   1641      *
   1642      * @return {@code true} if the operation succeeds else {@code false}
   1643      * @hide
   1644      */
   1645     public boolean clearBlacklist() {
   1646         try {
   1647             mService.clearBlacklist();
   1648             return true;
   1649         } catch (RemoteException e) {
   1650             throw e.rethrowFromSystemServer();
   1651         }
   1652     }
   1653 
   1654 
   1655     /**
   1656      * Enable/Disable TDLS on a specific local route.
   1657      *
   1658      * <p>
   1659      * TDLS enables two wireless endpoints to talk to each other directly
   1660      * without going through the access point that is managing the local
   1661      * network. It saves bandwidth and improves quality of the link.
   1662      * </p>
   1663      * <p>
   1664      * This API enables/disables the option of using TDLS. If enabled, the
   1665      * underlying hardware is free to use TDLS or a hop through the access
   1666      * point. If disabled, existing TDLS session is torn down and
   1667      * hardware is restricted to use access point for transferring wireless
   1668      * packets. Default value for all routes is 'disabled', meaning restricted
   1669      * to use access point for transferring packets.
   1670      * </p>
   1671      *
   1672      * @param remoteIPAddress IP address of the endpoint to setup TDLS with
   1673      * @param enable true = setup and false = tear down TDLS
   1674      */
   1675     public void setTdlsEnabled(InetAddress remoteIPAddress, boolean enable) {
   1676         try {
   1677             mService.enableTdls(remoteIPAddress.getHostAddress(), enable);
   1678         } catch (RemoteException e) {
   1679             throw e.rethrowFromSystemServer();
   1680         }
   1681     }
   1682 
   1683     /**
   1684      * Similar to {@link #setTdlsEnabled(InetAddress, boolean) }, except
   1685      * this version allows you to specify remote endpoint with a MAC address.
   1686      * @param remoteMacAddress MAC address of the remote endpoint such as 00:00:0c:9f:f2:ab
   1687      * @param enable true = setup and false = tear down TDLS
   1688      */
   1689     public void setTdlsEnabledWithMacAddress(String remoteMacAddress, boolean enable) {
   1690         try {
   1691             mService.enableTdlsWithMacAddress(remoteMacAddress, enable);
   1692         } catch (RemoteException e) {
   1693             throw e.rethrowFromSystemServer();
   1694         }
   1695     }
   1696 
   1697     /* TODO: deprecate synchronous API and open up the following API */
   1698 
   1699     private static final int BASE = Protocol.BASE_WIFI_MANAGER;
   1700 
   1701     /* Commands to WifiService */
   1702     /** @hide */
   1703     public static final int CONNECT_NETWORK                 = BASE + 1;
   1704     /** @hide */
   1705     public static final int CONNECT_NETWORK_FAILED          = BASE + 2;
   1706     /** @hide */
   1707     public static final int CONNECT_NETWORK_SUCCEEDED       = BASE + 3;
   1708 
   1709     /** @hide */
   1710     public static final int FORGET_NETWORK                  = BASE + 4;
   1711     /** @hide */
   1712     public static final int FORGET_NETWORK_FAILED           = BASE + 5;
   1713     /** @hide */
   1714     public static final int FORGET_NETWORK_SUCCEEDED        = BASE + 6;
   1715 
   1716     /** @hide */
   1717     public static final int SAVE_NETWORK                    = BASE + 7;
   1718     /** @hide */
   1719     public static final int SAVE_NETWORK_FAILED             = BASE + 8;
   1720     /** @hide */
   1721     public static final int SAVE_NETWORK_SUCCEEDED          = BASE + 9;
   1722 
   1723     /** @hide */
   1724     public static final int START_WPS                       = BASE + 10;
   1725     /** @hide */
   1726     public static final int START_WPS_SUCCEEDED             = BASE + 11;
   1727     /** @hide */
   1728     public static final int WPS_FAILED                      = BASE + 12;
   1729     /** @hide */
   1730     public static final int WPS_COMPLETED                   = BASE + 13;
   1731 
   1732     /** @hide */
   1733     public static final int CANCEL_WPS                      = BASE + 14;
   1734     /** @hide */
   1735     public static final int CANCEL_WPS_FAILED               = BASE + 15;
   1736     /** @hide */
   1737     public static final int CANCEL_WPS_SUCCEDED             = BASE + 16;
   1738 
   1739     /** @hide */
   1740     public static final int DISABLE_NETWORK                 = BASE + 17;
   1741     /** @hide */
   1742     public static final int DISABLE_NETWORK_FAILED          = BASE + 18;
   1743     /** @hide */
   1744     public static final int DISABLE_NETWORK_SUCCEEDED       = BASE + 19;
   1745 
   1746     /** @hide */
   1747     public static final int RSSI_PKTCNT_FETCH               = BASE + 20;
   1748     /** @hide */
   1749     public static final int RSSI_PKTCNT_FETCH_SUCCEEDED     = BASE + 21;
   1750     /** @hide */
   1751     public static final int RSSI_PKTCNT_FETCH_FAILED        = BASE + 22;
   1752 
   1753     /**
   1754      * Passed with {@link ActionListener#onFailure}.
   1755      * Indicates that the operation failed due to an internal error.
   1756      * @hide
   1757      */
   1758     public static final int ERROR                       = 0;
   1759 
   1760     /**
   1761      * Passed with {@link ActionListener#onFailure}.
   1762      * Indicates that the operation is already in progress
   1763      * @hide
   1764      */
   1765     public static final int IN_PROGRESS                 = 1;
   1766 
   1767     /**
   1768      * Passed with {@link ActionListener#onFailure}.
   1769      * Indicates that the operation failed because the framework is busy and
   1770      * unable to service the request
   1771      * @hide
   1772      */
   1773     public static final int BUSY                        = 2;
   1774 
   1775     /* WPS specific errors */
   1776     /** WPS overlap detected */
   1777     public static final int WPS_OVERLAP_ERROR           = 3;
   1778     /** WEP on WPS is prohibited */
   1779     public static final int WPS_WEP_PROHIBITED          = 4;
   1780     /** TKIP only prohibited */
   1781     public static final int WPS_TKIP_ONLY_PROHIBITED    = 5;
   1782     /** Authentication failure on WPS */
   1783     public static final int WPS_AUTH_FAILURE            = 6;
   1784     /** WPS timed out */
   1785     public static final int WPS_TIMED_OUT               = 7;
   1786 
   1787     /**
   1788      * Passed with {@link ActionListener#onFailure}.
   1789      * Indicates that the operation failed due to invalid inputs
   1790      * @hide
   1791      */
   1792     public static final int INVALID_ARGS                = 8;
   1793 
   1794     /**
   1795      * Passed with {@link ActionListener#onFailure}.
   1796      * Indicates that the operation failed due to user permissions.
   1797      * @hide
   1798      */
   1799     public static final int NOT_AUTHORIZED              = 9;
   1800 
   1801     /**
   1802      * Interface for callback invocation on an application action
   1803      * @hide
   1804      */
   1805     public interface ActionListener {
   1806         /** The operation succeeded */
   1807         public void onSuccess();
   1808         /**
   1809          * The operation failed
   1810          * @param reason The reason for failure could be one of
   1811          * {@link #ERROR}, {@link #IN_PROGRESS} or {@link #BUSY}
   1812          */
   1813         public void onFailure(int reason);
   1814     }
   1815 
   1816     /** Interface for callback invocation on a start WPS action */
   1817     public static abstract class WpsCallback {
   1818         /** WPS start succeeded */
   1819         public abstract void onStarted(String pin);
   1820 
   1821         /** WPS operation completed succesfully */
   1822         public abstract void onSucceeded();
   1823 
   1824         /**
   1825          * WPS operation failed
   1826          * @param reason The reason for failure could be one of
   1827          * {@link #WPS_TKIP_ONLY_PROHIBITED}, {@link #WPS_OVERLAP_ERROR},
   1828          * {@link #WPS_WEP_PROHIBITED}, {@link #WPS_TIMED_OUT} or {@link #WPS_AUTH_FAILURE}
   1829          * and some generic errors.
   1830          */
   1831         public abstract void onFailed(int reason);
   1832     }
   1833 
   1834     /** Interface for callback invocation on a TX packet count poll action {@hide} */
   1835     public interface TxPacketCountListener {
   1836         /**
   1837          * The operation succeeded
   1838          * @param count TX packet counter
   1839          */
   1840         public void onSuccess(int count);
   1841         /**
   1842          * The operation failed
   1843          * @param reason The reason for failure could be one of
   1844          * {@link #ERROR}, {@link #IN_PROGRESS} or {@link #BUSY}
   1845          */
   1846         public void onFailure(int reason);
   1847     }
   1848 
   1849     // Ensure that multiple ServiceHandler threads do not interleave message dispatch.
   1850     private static final Object sServiceHandlerDispatchLock = new Object();
   1851 
   1852     private class ServiceHandler extends Handler {
   1853         ServiceHandler(Looper looper) {
   1854             super(looper);
   1855         }
   1856 
   1857         @Override
   1858         public void handleMessage(Message message) {
   1859             synchronized (sServiceHandlerDispatchLock) {
   1860                 dispatchMessageToListeners(message);
   1861             }
   1862         }
   1863 
   1864         private void dispatchMessageToListeners(Message message) {
   1865             Object listener = removeListener(message.arg2);
   1866             switch (message.what) {
   1867                 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
   1868                     if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
   1869                         mAsyncChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
   1870                     } else {
   1871                         Log.e(TAG, "Failed to set up channel connection");
   1872                         // This will cause all further async API calls on the WifiManager
   1873                         // to fail and throw an exception
   1874                         mAsyncChannel = null;
   1875                     }
   1876                     mConnected.countDown();
   1877                     break;
   1878                 case AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED:
   1879                     // Ignore
   1880                     break;
   1881                 case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
   1882                     Log.e(TAG, "Channel connection lost");
   1883                     // This will cause all further async API calls on the WifiManager
   1884                     // to fail and throw an exception
   1885                     mAsyncChannel = null;
   1886                     getLooper().quit();
   1887                     break;
   1888                     /* ActionListeners grouped together */
   1889                 case WifiManager.CONNECT_NETWORK_FAILED:
   1890                 case WifiManager.FORGET_NETWORK_FAILED:
   1891                 case WifiManager.SAVE_NETWORK_FAILED:
   1892                 case WifiManager.DISABLE_NETWORK_FAILED:
   1893                     if (listener != null) {
   1894                         ((ActionListener) listener).onFailure(message.arg1);
   1895                     }
   1896                     break;
   1897                     /* ActionListeners grouped together */
   1898                 case WifiManager.CONNECT_NETWORK_SUCCEEDED:
   1899                 case WifiManager.FORGET_NETWORK_SUCCEEDED:
   1900                 case WifiManager.SAVE_NETWORK_SUCCEEDED:
   1901                 case WifiManager.DISABLE_NETWORK_SUCCEEDED:
   1902                     if (listener != null) {
   1903                         ((ActionListener) listener).onSuccess();
   1904                     }
   1905                     break;
   1906                 case WifiManager.START_WPS_SUCCEEDED:
   1907                     if (listener != null) {
   1908                         WpsResult result = (WpsResult) message.obj;
   1909                         ((WpsCallback) listener).onStarted(result.pin);
   1910                         //Listener needs to stay until completion or failure
   1911                         synchronized (mListenerMapLock) {
   1912                             mListenerMap.put(message.arg2, listener);
   1913                         }
   1914                     }
   1915                     break;
   1916                 case WifiManager.WPS_COMPLETED:
   1917                     if (listener != null) {
   1918                         ((WpsCallback) listener).onSucceeded();
   1919                     }
   1920                     break;
   1921                 case WifiManager.WPS_FAILED:
   1922                     if (listener != null) {
   1923                         ((WpsCallback) listener).onFailed(message.arg1);
   1924                     }
   1925                     break;
   1926                 case WifiManager.CANCEL_WPS_SUCCEDED:
   1927                     if (listener != null) {
   1928                         ((WpsCallback) listener).onSucceeded();
   1929                     }
   1930                     break;
   1931                 case WifiManager.CANCEL_WPS_FAILED:
   1932                     if (listener != null) {
   1933                         ((WpsCallback) listener).onFailed(message.arg1);
   1934                     }
   1935                     break;
   1936                 case WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED:
   1937                     if (listener != null) {
   1938                         RssiPacketCountInfo info = (RssiPacketCountInfo) message.obj;
   1939                         if (info != null)
   1940                             ((TxPacketCountListener) listener).onSuccess(info.txgood + info.txbad);
   1941                         else
   1942                             ((TxPacketCountListener) listener).onFailure(ERROR);
   1943                     }
   1944                     break;
   1945                 case WifiManager.RSSI_PKTCNT_FETCH_FAILED:
   1946                     if (listener != null) {
   1947                         ((TxPacketCountListener) listener).onFailure(message.arg1);
   1948                     }
   1949                     break;
   1950                 default:
   1951                     //ignore
   1952                     break;
   1953             }
   1954         }
   1955     }
   1956 
   1957     private int putListener(Object listener) {
   1958         if (listener == null) return INVALID_KEY;
   1959         int key;
   1960         synchronized (mListenerMapLock) {
   1961             do {
   1962                 key = mListenerKey++;
   1963             } while (key == INVALID_KEY);
   1964             mListenerMap.put(key, listener);
   1965         }
   1966         return key;
   1967     }
   1968 
   1969     private Object removeListener(int key) {
   1970         if (key == INVALID_KEY) return null;
   1971         synchronized (mListenerMapLock) {
   1972             Object listener = mListenerMap.get(key);
   1973             mListenerMap.remove(key);
   1974             return listener;
   1975         }
   1976     }
   1977 
   1978     private synchronized AsyncChannel getChannel() {
   1979         if (mAsyncChannel == null) {
   1980             Messenger messenger = getWifiServiceMessenger();
   1981             if (messenger == null) {
   1982                 throw new IllegalStateException(
   1983                         "getWifiServiceMessenger() returned null!  This is invalid.");
   1984             }
   1985 
   1986             mAsyncChannel = new AsyncChannel();
   1987             mConnected = new CountDownLatch(1);
   1988 
   1989             Handler handler = new ServiceHandler(mLooper);
   1990             mAsyncChannel.connect(mContext, handler, messenger);
   1991             try {
   1992                 mConnected.await();
   1993             } catch (InterruptedException e) {
   1994                 Log.e(TAG, "interrupted wait at init");
   1995             }
   1996         }
   1997         return mAsyncChannel;
   1998     }
   1999 
   2000     /**
   2001      * Connect to a network with the given configuration. The network also
   2002      * gets added to the supplicant configuration.
   2003      *
   2004      * For a new network, this function is used instead of a
   2005      * sequence of addNetwork(), enableNetwork(), saveConfiguration() and
   2006      * reconnect()
   2007      *
   2008      * @param config the set of variables that describe the configuration,
   2009      *            contained in a {@link WifiConfiguration} object.
   2010      * @param listener for callbacks on success or failure. Can be null.
   2011      * @throws IllegalStateException if the WifiManager instance needs to be
   2012      * initialized again
   2013      *
   2014      * @hide
   2015      */
   2016     public void connect(WifiConfiguration config, ActionListener listener) {
   2017         if (config == null) throw new IllegalArgumentException("config cannot be null");
   2018         // Use INVALID_NETWORK_ID for arg1 when passing a config object
   2019         // arg1 is used to pass network id when the network already exists
   2020         getChannel().sendMessage(CONNECT_NETWORK, WifiConfiguration.INVALID_NETWORK_ID,
   2021                 putListener(listener), config);
   2022     }
   2023 
   2024     /**
   2025      * Connect to a network with the given networkId.
   2026      *
   2027      * This function is used instead of a enableNetwork(), saveConfiguration() and
   2028      * reconnect()
   2029      *
   2030      * @param networkId the network id identifiying the network in the
   2031      *                supplicant configuration list
   2032      * @param listener for callbacks on success or failure. Can be null.
   2033      * @throws IllegalStateException if the WifiManager instance needs to be
   2034      * initialized again
   2035      * @hide
   2036      */
   2037     public void connect(int networkId, ActionListener listener) {
   2038         if (networkId < 0) throw new IllegalArgumentException("Network id cannot be negative");
   2039         getChannel().sendMessage(CONNECT_NETWORK, networkId, putListener(listener));
   2040     }
   2041 
   2042     /**
   2043      * Save the given network in the supplicant config. If the network already
   2044      * exists, the configuration is updated. A new network is enabled
   2045      * by default.
   2046      *
   2047      * For a new network, this function is used instead of a
   2048      * sequence of addNetwork(), enableNetwork() and saveConfiguration().
   2049      *
   2050      * For an existing network, it accomplishes the task of updateNetwork()
   2051      * and saveConfiguration()
   2052      *
   2053      * @param config the set of variables that describe the configuration,
   2054      *            contained in a {@link WifiConfiguration} object.
   2055      * @param listener for callbacks on success or failure. Can be null.
   2056      * @throws IllegalStateException if the WifiManager instance needs to be
   2057      * initialized again
   2058      * @hide
   2059      */
   2060     public void save(WifiConfiguration config, ActionListener listener) {
   2061         if (config == null) throw new IllegalArgumentException("config cannot be null");
   2062         getChannel().sendMessage(SAVE_NETWORK, 0, putListener(listener), config);
   2063     }
   2064 
   2065     /**
   2066      * Delete the network in the supplicant config.
   2067      *
   2068      * This function is used instead of a sequence of removeNetwork()
   2069      * and saveConfiguration().
   2070      *
   2071      * @param config the set of variables that describe the configuration,
   2072      *            contained in a {@link WifiConfiguration} object.
   2073      * @param listener for callbacks on success or failure. Can be null.
   2074      * @throws IllegalStateException if the WifiManager instance needs to be
   2075      * initialized again
   2076      * @hide
   2077      */
   2078     public void forget(int netId, ActionListener listener) {
   2079         if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
   2080         getChannel().sendMessage(FORGET_NETWORK, netId, putListener(listener));
   2081     }
   2082 
   2083     /**
   2084      * Disable network
   2085      *
   2086      * @param netId is the network Id
   2087      * @param listener for callbacks on success or failure. Can be null.
   2088      * @throws IllegalStateException if the WifiManager instance needs to be
   2089      * initialized again
   2090      * @hide
   2091      */
   2092     public void disable(int netId, ActionListener listener) {
   2093         if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
   2094         getChannel().sendMessage(DISABLE_NETWORK, netId, putListener(listener));
   2095     }
   2096 
   2097     /**
   2098      * Disable ephemeral Network
   2099      *
   2100      * @param SSID, in the format of WifiConfiguration's SSID.
   2101      * @hide
   2102      */
   2103     public void disableEphemeralNetwork(String SSID) {
   2104         if (SSID == null) throw new IllegalArgumentException("SSID cannot be null");
   2105         try {
   2106             mService.disableEphemeralNetwork(SSID);
   2107         } catch (RemoteException e) {
   2108             throw e.rethrowFromSystemServer();
   2109         }
   2110     }
   2111 
   2112     /**
   2113      * Start Wi-fi Protected Setup
   2114      *
   2115      * @param config WPS configuration (does not support {@link WpsInfo#LABEL})
   2116      * @param listener for callbacks on success or failure. Can be null.
   2117      * @throws IllegalStateException if the WifiManager instance needs to be
   2118      * initialized again
   2119      */
   2120     public void startWps(WpsInfo config, WpsCallback listener) {
   2121         if (config == null) throw new IllegalArgumentException("config cannot be null");
   2122         getChannel().sendMessage(START_WPS, 0, putListener(listener), config);
   2123     }
   2124 
   2125     /**
   2126      * Cancel any ongoing Wi-fi Protected Setup
   2127      *
   2128      * @param listener for callbacks on success or failure. Can be null.
   2129      * @throws IllegalStateException if the WifiManager instance needs to be
   2130      * initialized again
   2131      */
   2132     public void cancelWps(WpsCallback listener) {
   2133         getChannel().sendMessage(CANCEL_WPS, 0, putListener(listener));
   2134     }
   2135 
   2136     /**
   2137      * Get a reference to WifiService handler. This is used by a client to establish
   2138      * an AsyncChannel communication with WifiService
   2139      *
   2140      * @return Messenger pointing to the WifiService handler
   2141      * @hide
   2142      */
   2143     public Messenger getWifiServiceMessenger() {
   2144         try {
   2145             return mService.getWifiServiceMessenger();
   2146         } catch (RemoteException e) {
   2147             throw e.rethrowFromSystemServer();
   2148         }
   2149     }
   2150 
   2151 
   2152     /**
   2153      * Returns the file in which IP and proxy configuration data is stored
   2154      * @hide
   2155      */
   2156     public String getConfigFile() {
   2157         try {
   2158             return mService.getConfigFile();
   2159         } catch (RemoteException e) {
   2160             throw e.rethrowFromSystemServer();
   2161         }
   2162     }
   2163 
   2164     /**
   2165      * Allows an application to keep the Wi-Fi radio awake.
   2166      * Normally the Wi-Fi radio may turn off when the user has not used the device in a while.
   2167      * Acquiring a WifiLock will keep the radio on until the lock is released.  Multiple
   2168      * applications may hold WifiLocks, and the radio will only be allowed to turn off when no
   2169      * WifiLocks are held in any application.
   2170      * <p>
   2171      * Before using a WifiLock, consider carefully if your application requires Wi-Fi access, or
   2172      * could function over a mobile network, if available.  A program that needs to download large
   2173      * files should hold a WifiLock to ensure that the download will complete, but a program whose
   2174      * network usage is occasional or low-bandwidth should not hold a WifiLock to avoid adversely
   2175      * affecting battery life.
   2176      * <p>
   2177      * Note that WifiLocks cannot override the user-level "Wi-Fi Enabled" setting, nor Airplane
   2178      * Mode.  They simply keep the radio from turning off when Wi-Fi is already on but the device
   2179      * is idle.
   2180      * <p>
   2181      * Any application using a WifiLock must request the {@code android.permission.WAKE_LOCK}
   2182      * permission in an {@code <uses-permission>} element of the application's manifest.
   2183      */
   2184     public class WifiLock {
   2185         private String mTag;
   2186         private final IBinder mBinder;
   2187         private int mRefCount;
   2188         int mLockType;
   2189         private boolean mRefCounted;
   2190         private boolean mHeld;
   2191         private WorkSource mWorkSource;
   2192 
   2193         private WifiLock(int lockType, String tag) {
   2194             mTag = tag;
   2195             mLockType = lockType;
   2196             mBinder = new Binder();
   2197             mRefCount = 0;
   2198             mRefCounted = true;
   2199             mHeld = false;
   2200         }
   2201 
   2202         /**
   2203          * Locks the Wi-Fi radio on until {@link #release} is called.
   2204          *
   2205          * If this WifiLock is reference-counted, each call to {@code acquire} will increment the
   2206          * reference count, and the radio will remain locked as long as the reference count is
   2207          * above zero.
   2208          *
   2209          * If this WifiLock is not reference-counted, the first call to {@code acquire} will lock
   2210          * the radio, but subsequent calls will be ignored.  Only one call to {@link #release}
   2211          * will be required, regardless of the number of times that {@code acquire} is called.
   2212          */
   2213         public void acquire() {
   2214             synchronized (mBinder) {
   2215                 if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) {
   2216                     try {
   2217                         mService.acquireWifiLock(mBinder, mLockType, mTag, mWorkSource);
   2218                         synchronized (WifiManager.this) {
   2219                             if (mActiveLockCount >= MAX_ACTIVE_LOCKS) {
   2220                                 mService.releaseWifiLock(mBinder);
   2221                                 throw new UnsupportedOperationException(
   2222                                             "Exceeded maximum number of wifi locks");
   2223                             }
   2224                             mActiveLockCount++;
   2225                         }
   2226                     } catch (RemoteException e) {
   2227                         throw e.rethrowFromSystemServer();
   2228                     }
   2229                     mHeld = true;
   2230                 }
   2231             }
   2232         }
   2233 
   2234         /**
   2235          * Unlocks the Wi-Fi radio, allowing it to turn off when the device is idle.
   2236          *
   2237          * If this WifiLock is reference-counted, each call to {@code release} will decrement the
   2238          * reference count, and the radio will be unlocked only when the reference count reaches
   2239          * zero.  If the reference count goes below zero (that is, if {@code release} is called
   2240          * a greater number of times than {@link #acquire}), an exception is thrown.
   2241          *
   2242          * If this WifiLock is not reference-counted, the first call to {@code release} (after
   2243          * the radio was locked using {@link #acquire}) will unlock the radio, and subsequent
   2244          * calls will be ignored.
   2245          */
   2246         public void release() {
   2247             synchronized (mBinder) {
   2248                 if (mRefCounted ? (--mRefCount == 0) : (mHeld)) {
   2249                     try {
   2250                         mService.releaseWifiLock(mBinder);
   2251                         synchronized (WifiManager.this) {
   2252                             mActiveLockCount--;
   2253                         }
   2254                     } catch (RemoteException e) {
   2255                         throw e.rethrowFromSystemServer();
   2256                     }
   2257                     mHeld = false;
   2258                 }
   2259                 if (mRefCount < 0) {
   2260                     throw new RuntimeException("WifiLock under-locked " + mTag);
   2261                 }
   2262             }
   2263         }
   2264 
   2265         /**
   2266          * Controls whether this is a reference-counted or non-reference-counted WifiLock.
   2267          *
   2268          * Reference-counted WifiLocks keep track of the number of calls to {@link #acquire} and
   2269          * {@link #release}, and only allow the radio to sleep when every call to {@link #acquire}
   2270          * has been balanced with a call to {@link #release}.  Non-reference-counted WifiLocks
   2271          * lock the radio whenever {@link #acquire} is called and it is unlocked, and unlock the
   2272          * radio whenever {@link #release} is called and it is locked.
   2273          *
   2274          * @param refCounted true if this WifiLock should keep a reference count
   2275          */
   2276         public void setReferenceCounted(boolean refCounted) {
   2277             mRefCounted = refCounted;
   2278         }
   2279 
   2280         /**
   2281          * Checks whether this WifiLock is currently held.
   2282          *
   2283          * @return true if this WifiLock is held, false otherwise
   2284          */
   2285         public boolean isHeld() {
   2286             synchronized (mBinder) {
   2287                 return mHeld;
   2288             }
   2289         }
   2290 
   2291         public void setWorkSource(WorkSource ws) {
   2292             synchronized (mBinder) {
   2293                 if (ws != null && ws.size() == 0) {
   2294                     ws = null;
   2295                 }
   2296                 boolean changed = true;
   2297                 if (ws == null) {
   2298                     mWorkSource = null;
   2299                 } else {
   2300                     ws.clearNames();
   2301                     if (mWorkSource == null) {
   2302                         changed = mWorkSource != null;
   2303                         mWorkSource = new WorkSource(ws);
   2304                     } else {
   2305                         changed = mWorkSource.diff(ws);
   2306                         if (changed) {
   2307                             mWorkSource.set(ws);
   2308                         }
   2309                     }
   2310                 }
   2311                 if (changed && mHeld) {
   2312                     try {
   2313                         mService.updateWifiLockWorkSource(mBinder, mWorkSource);
   2314                     } catch (RemoteException e) {
   2315                         throw e.rethrowFromSystemServer();
   2316                     }
   2317                 }
   2318             }
   2319         }
   2320 
   2321         public String toString() {
   2322             String s1, s2, s3;
   2323             synchronized (mBinder) {
   2324                 s1 = Integer.toHexString(System.identityHashCode(this));
   2325                 s2 = mHeld ? "held; " : "";
   2326                 if (mRefCounted) {
   2327                     s3 = "refcounted: refcount = " + mRefCount;
   2328                 } else {
   2329                     s3 = "not refcounted";
   2330                 }
   2331                 return "WifiLock{ " + s1 + "; " + s2 + s3 + " }";
   2332             }
   2333         }
   2334 
   2335         @Override
   2336         protected void finalize() throws Throwable {
   2337             super.finalize();
   2338             synchronized (mBinder) {
   2339                 if (mHeld) {
   2340                     try {
   2341                         mService.releaseWifiLock(mBinder);
   2342                         synchronized (WifiManager.this) {
   2343                             mActiveLockCount--;
   2344                         }
   2345                     } catch (RemoteException e) {
   2346                         throw e.rethrowFromSystemServer();
   2347                     }
   2348                 }
   2349             }
   2350         }
   2351     }
   2352 
   2353     /**
   2354      * Creates a new WifiLock.
   2355      *
   2356      * @param lockType the type of lock to create. See {@link #WIFI_MODE_FULL},
   2357      * {@link #WIFI_MODE_FULL_HIGH_PERF} and {@link #WIFI_MODE_SCAN_ONLY} for
   2358      * descriptions of the types of Wi-Fi locks.
   2359      * @param tag a tag for the WifiLock to identify it in debugging messages.  This string is
   2360      *            never shown to the user under normal conditions, but should be descriptive
   2361      *            enough to identify your application and the specific WifiLock within it, if it
   2362      *            holds multiple WifiLocks.
   2363      *
   2364      * @return a new, unacquired WifiLock with the given tag.
   2365      *
   2366      * @see WifiLock
   2367      */
   2368     public WifiLock createWifiLock(int lockType, String tag) {
   2369         return new WifiLock(lockType, tag);
   2370     }
   2371 
   2372     /**
   2373      * Creates a new WifiLock.
   2374      *
   2375      * @param tag a tag for the WifiLock to identify it in debugging messages.  This string is
   2376      *            never shown to the user under normal conditions, but should be descriptive
   2377      *            enough to identify your application and the specific WifiLock within it, if it
   2378      *            holds multiple WifiLocks.
   2379      *
   2380      * @return a new, unacquired WifiLock with the given tag.
   2381      *
   2382      * @see WifiLock
   2383      */
   2384     public WifiLock createWifiLock(String tag) {
   2385         return new WifiLock(WIFI_MODE_FULL, tag);
   2386     }
   2387 
   2388 
   2389     /**
   2390      * Create a new MulticastLock
   2391      *
   2392      * @param tag a tag for the MulticastLock to identify it in debugging
   2393      *            messages.  This string is never shown to the user under
   2394      *            normal conditions, but should be descriptive enough to
   2395      *            identify your application and the specific MulticastLock
   2396      *            within it, if it holds multiple MulticastLocks.
   2397      *
   2398      * @return a new, unacquired MulticastLock with the given tag.
   2399      *
   2400      * @see MulticastLock
   2401      */
   2402     public MulticastLock createMulticastLock(String tag) {
   2403         return new MulticastLock(tag);
   2404     }
   2405 
   2406     /**
   2407      * Allows an application to receive Wifi Multicast packets.
   2408      * Normally the Wifi stack filters out packets not explicitly
   2409      * addressed to this device.  Acquring a MulticastLock will
   2410      * cause the stack to receive packets addressed to multicast
   2411      * addresses.  Processing these extra packets can cause a noticable
   2412      * battery drain and should be disabled when not needed.
   2413      */
   2414     public class MulticastLock {
   2415         private String mTag;
   2416         private final IBinder mBinder;
   2417         private int mRefCount;
   2418         private boolean mRefCounted;
   2419         private boolean mHeld;
   2420 
   2421         private MulticastLock(String tag) {
   2422             mTag = tag;
   2423             mBinder = new Binder();
   2424             mRefCount = 0;
   2425             mRefCounted = true;
   2426             mHeld = false;
   2427         }
   2428 
   2429         /**
   2430          * Locks Wifi Multicast on until {@link #release} is called.
   2431          *
   2432          * If this MulticastLock is reference-counted each call to
   2433          * {@code acquire} will increment the reference count, and the
   2434          * wifi interface will receive multicast packets as long as the
   2435          * reference count is above zero.
   2436          *
   2437          * If this MulticastLock is not reference-counted, the first call to
   2438          * {@code acquire} will turn on the multicast packets, but subsequent
   2439          * calls will be ignored.  Only one call to {@link #release} will
   2440          * be required, regardless of the number of times that {@code acquire}
   2441          * is called.
   2442          *
   2443          * Note that other applications may also lock Wifi Multicast on.
   2444          * Only they can relinquish their lock.
   2445          *
   2446          * Also note that applications cannot leave Multicast locked on.
   2447          * When an app exits or crashes, any Multicast locks will be released.
   2448          */
   2449         public void acquire() {
   2450             synchronized (mBinder) {
   2451                 if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) {
   2452                     try {
   2453                         mService.acquireMulticastLock(mBinder, mTag);
   2454                         synchronized (WifiManager.this) {
   2455                             if (mActiveLockCount >= MAX_ACTIVE_LOCKS) {
   2456                                 mService.releaseMulticastLock();
   2457                                 throw new UnsupportedOperationException(
   2458                                         "Exceeded maximum number of wifi locks");
   2459                             }
   2460                             mActiveLockCount++;
   2461                         }
   2462                     } catch (RemoteException e) {
   2463                         throw e.rethrowFromSystemServer();
   2464                     }
   2465                     mHeld = true;
   2466                 }
   2467             }
   2468         }
   2469 
   2470         /**
   2471          * Unlocks Wifi Multicast, restoring the filter of packets
   2472          * not addressed specifically to this device and saving power.
   2473          *
   2474          * If this MulticastLock is reference-counted, each call to
   2475          * {@code release} will decrement the reference count, and the
   2476          * multicast packets will only stop being received when the reference
   2477          * count reaches zero.  If the reference count goes below zero (that
   2478          * is, if {@code release} is called a greater number of times than
   2479          * {@link #acquire}), an exception is thrown.
   2480          *
   2481          * If this MulticastLock is not reference-counted, the first call to
   2482          * {@code release} (after the radio was multicast locked using
   2483          * {@link #acquire}) will unlock the multicast, and subsequent calls
   2484          * will be ignored.
   2485          *
   2486          * Note that if any other Wifi Multicast Locks are still outstanding
   2487          * this {@code release} call will not have an immediate effect.  Only
   2488          * when all applications have released all their Multicast Locks will
   2489          * the Multicast filter be turned back on.
   2490          *
   2491          * Also note that when an app exits or crashes all of its Multicast
   2492          * Locks will be automatically released.
   2493          */
   2494         public void release() {
   2495             synchronized (mBinder) {
   2496                 if (mRefCounted ? (--mRefCount == 0) : (mHeld)) {
   2497                     try {
   2498                         mService.releaseMulticastLock();
   2499                         synchronized (WifiManager.this) {
   2500                             mActiveLockCount--;
   2501                         }
   2502                     } catch (RemoteException e) {
   2503                         throw e.rethrowFromSystemServer();
   2504                     }
   2505                     mHeld = false;
   2506                 }
   2507                 if (mRefCount < 0) {
   2508                     throw new RuntimeException("MulticastLock under-locked "
   2509                             + mTag);
   2510                 }
   2511             }
   2512         }
   2513 
   2514         /**
   2515          * Controls whether this is a reference-counted or non-reference-
   2516          * counted MulticastLock.
   2517          *
   2518          * Reference-counted MulticastLocks keep track of the number of calls
   2519          * to {@link #acquire} and {@link #release}, and only stop the
   2520          * reception of multicast packets when every call to {@link #acquire}
   2521          * has been balanced with a call to {@link #release}.  Non-reference-
   2522          * counted MulticastLocks allow the reception of multicast packets
   2523          * whenever {@link #acquire} is called and stop accepting multicast
   2524          * packets whenever {@link #release} is called.
   2525          *
   2526          * @param refCounted true if this MulticastLock should keep a reference
   2527          * count
   2528          */
   2529         public void setReferenceCounted(boolean refCounted) {
   2530             mRefCounted = refCounted;
   2531         }
   2532 
   2533         /**
   2534          * Checks whether this MulticastLock is currently held.
   2535          *
   2536          * @return true if this MulticastLock is held, false otherwise
   2537          */
   2538         public boolean isHeld() {
   2539             synchronized (mBinder) {
   2540                 return mHeld;
   2541             }
   2542         }
   2543 
   2544         public String toString() {
   2545             String s1, s2, s3;
   2546             synchronized (mBinder) {
   2547                 s1 = Integer.toHexString(System.identityHashCode(this));
   2548                 s2 = mHeld ? "held; " : "";
   2549                 if (mRefCounted) {
   2550                     s3 = "refcounted: refcount = " + mRefCount;
   2551                 } else {
   2552                     s3 = "not refcounted";
   2553                 }
   2554                 return "MulticastLock{ " + s1 + "; " + s2 + s3 + " }";
   2555             }
   2556         }
   2557 
   2558         @Override
   2559         protected void finalize() throws Throwable {
   2560             super.finalize();
   2561             setReferenceCounted(false);
   2562             release();
   2563         }
   2564     }
   2565 
   2566     /**
   2567      * Check multicast filter status.
   2568      *
   2569      * @return true if multicast packets are allowed.
   2570      *
   2571      * @hide pending API council approval
   2572      */
   2573     public boolean isMulticastEnabled() {
   2574         try {
   2575             return mService.isMulticastEnabled();
   2576         } catch (RemoteException e) {
   2577             throw e.rethrowFromSystemServer();
   2578         }
   2579     }
   2580 
   2581     /**
   2582      * Initialize the multicast filtering to 'on'
   2583      * @hide no intent to publish
   2584      */
   2585     public boolean initializeMulticastFiltering() {
   2586         try {
   2587             mService.initializeMulticastFiltering();
   2588             return true;
   2589         } catch (RemoteException e) {
   2590             throw e.rethrowFromSystemServer();
   2591         }
   2592     }
   2593 
   2594     protected void finalize() throws Throwable {
   2595         try {
   2596             if (mAsyncChannel != null) {
   2597                 mAsyncChannel.disconnect();
   2598             }
   2599         } finally {
   2600             super.finalize();
   2601         }
   2602     }
   2603 
   2604     /**
   2605      * Set wifi verbose log. Called from developer settings.
   2606      * @hide
   2607      */
   2608     public void enableVerboseLogging (int verbose) {
   2609         try {
   2610             mService.enableVerboseLogging(verbose);
   2611         } catch (Exception e) {
   2612             //ignore any failure here
   2613             Log.e(TAG, "enableVerboseLogging " + e.toString());
   2614         }
   2615     }
   2616 
   2617     /**
   2618      * Get the WiFi verbose logging level.This is used by settings
   2619      * to decide what to show within the picker.
   2620      * @hide
   2621      */
   2622     public int getVerboseLoggingLevel() {
   2623         try {
   2624             return mService.getVerboseLoggingLevel();
   2625         } catch (RemoteException e) {
   2626             throw e.rethrowFromSystemServer();
   2627         }
   2628     }
   2629 
   2630     /**
   2631      * Set wifi Aggressive Handover. Called from developer settings.
   2632      * @hide
   2633      */
   2634     public void enableAggressiveHandover(int enabled) {
   2635         try {
   2636             mService.enableAggressiveHandover(enabled);
   2637         } catch (RemoteException e) {
   2638             throw e.rethrowFromSystemServer();
   2639         }
   2640     }
   2641 
   2642     /**
   2643      * Get the WiFi Handover aggressiveness.This is used by settings
   2644      * to decide what to show within the picker.
   2645      * @hide
   2646      */
   2647     public int getAggressiveHandover() {
   2648         try {
   2649             return mService.getAggressiveHandover();
   2650         } catch (RemoteException e) {
   2651             throw e.rethrowFromSystemServer();
   2652         }
   2653     }
   2654 
   2655     /**
   2656      * Set setting for allowing Scans when traffic is ongoing.
   2657      * @hide
   2658      */
   2659     public void setAllowScansWithTraffic(int enabled) {
   2660         try {
   2661             mService.setAllowScansWithTraffic(enabled);
   2662         } catch (RemoteException e) {
   2663             throw e.rethrowFromSystemServer();
   2664         }
   2665     }
   2666 
   2667     /**
   2668      * Get setting for allowing Scans when traffic is ongoing.
   2669      * @hide
   2670      */
   2671     public int getAllowScansWithTraffic() {
   2672         try {
   2673             return mService.getAllowScansWithTraffic();
   2674         } catch (RemoteException e) {
   2675             throw e.rethrowFromSystemServer();
   2676         }
   2677     }
   2678 
   2679     /**
   2680      * Resets all wifi manager settings back to factory defaults.
   2681      *
   2682      * @hide
   2683      */
   2684     public void factoryReset() {
   2685         try {
   2686             mService.factoryReset();
   2687         } catch (RemoteException e) {
   2688             throw e.rethrowFromSystemServer();
   2689         }
   2690     }
   2691 
   2692     /**
   2693      * Get Network object of current wifi network
   2694      * @return Get Network object of current wifi network
   2695      * @hide
   2696      */
   2697     public Network getCurrentNetwork() {
   2698         try {
   2699             return mService.getCurrentNetwork();
   2700         } catch (RemoteException e) {
   2701             throw e.rethrowFromSystemServer();
   2702         }
   2703     }
   2704 
   2705     /**
   2706      * Framework layer autojoin enable/disable when device is associated
   2707      * this will enable/disable autojoin scan and switch network when connected
   2708      * @return true -- if set successful false -- if set failed
   2709      * @hide
   2710      */
   2711     public boolean setEnableAutoJoinWhenAssociated(boolean enabled) {
   2712         try {
   2713             return mService.setEnableAutoJoinWhenAssociated(enabled);
   2714         } catch (RemoteException e) {
   2715             throw e.rethrowFromSystemServer();
   2716         }
   2717     }
   2718 
   2719     /**
   2720      * Get setting for Framework layer autojoin enable status
   2721      * @hide
   2722      */
   2723     public boolean getEnableAutoJoinWhenAssociated() {
   2724         try {
   2725             return mService.getEnableAutoJoinWhenAssociated();
   2726         } catch (RemoteException e) {
   2727             throw e.rethrowFromSystemServer();
   2728         }
   2729     }
   2730 
   2731     /**
   2732      * Enable/disable WifiConnectivityManager
   2733      * @hide
   2734      */
   2735     public void enableWifiConnectivityManager(boolean enabled) {
   2736         try {
   2737             mService.enableWifiConnectivityManager(enabled);
   2738         } catch (RemoteException e) {
   2739             throw e.rethrowFromSystemServer();
   2740         }
   2741     }
   2742 }
   2743