WifiManager.java revision 302b06de7ea7ac97ac4a2189213a1133220bfdc8
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
17package android.net.wifi;
18
19import android.annotation.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
21import android.content.Context;
22import android.net.DhcpInfo;
23import android.os.Binder;
24import android.os.IBinder;
25import android.os.Handler;
26import android.os.HandlerThread;
27import android.os.Looper;
28import android.os.Message;
29import android.os.RemoteException;
30import android.os.WorkSource;
31import android.os.Messenger;
32import android.util.Log;
33import android.util.SparseArray;
34
35import java.util.concurrent.CountDownLatch;
36
37import com.android.internal.util.AsyncChannel;
38import com.android.internal.util.Protocol;
39
40import java.util.List;
41
42/**
43 * This class provides the primary API for managing all aspects of Wi-Fi
44 * connectivity. Get an instance of this class by calling
45 * {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.WIFI_SERVICE)}.
46
47 * It deals with several categories of items:
48 * <ul>
49 * <li>The list of configured networks. The list can be viewed and updated,
50 * and attributes of individual entries can be modified.</li>
51 * <li>The currently active Wi-Fi network, if any. Connectivity can be
52 * established or torn down, and dynamic information about the state of
53 * the network can be queried.</li>
54 * <li>Results of access point scans, containing enough information to
55 * make decisions about what access point to connect to.</li>
56 * <li>It defines the names of various Intent actions that are broadcast
57 * upon any sort of change in Wi-Fi state.
58 * </ul>
59 * This is the API to use when performing Wi-Fi specific operations. To
60 * perform operations that pertain to network connectivity at an abstract
61 * level, use {@link android.net.ConnectivityManager}.
62 */
63public class WifiManager {
64
65    private static final String TAG = "WifiManager";
66    // Supplicant error codes:
67    /**
68     * The error code if there was a problem authenticating.
69     */
70    public static final int ERROR_AUTHENTICATING = 1;
71
72    /**
73     * Broadcast intent action indicating that Wi-Fi has been enabled, disabled,
74     * enabling, disabling, or unknown. One extra provides this state as an int.
75     * Another extra provides the previous state, if available.
76     *
77     * @see #EXTRA_WIFI_STATE
78     * @see #EXTRA_PREVIOUS_WIFI_STATE
79     */
80    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
81    public static final String WIFI_STATE_CHANGED_ACTION =
82        "android.net.wifi.WIFI_STATE_CHANGED";
83    /**
84     * The lookup key for an int that indicates whether Wi-Fi is enabled,
85     * disabled, enabling, disabling, or unknown.  Retrieve it with
86     * {@link android.content.Intent#getIntExtra(String,int)}.
87     *
88     * @see #WIFI_STATE_DISABLED
89     * @see #WIFI_STATE_DISABLING
90     * @see #WIFI_STATE_ENABLED
91     * @see #WIFI_STATE_ENABLING
92     * @see #WIFI_STATE_UNKNOWN
93     */
94    public static final String EXTRA_WIFI_STATE = "wifi_state";
95    /**
96     * The previous Wi-Fi state.
97     *
98     * @see #EXTRA_WIFI_STATE
99     */
100    public static final String EXTRA_PREVIOUS_WIFI_STATE = "previous_wifi_state";
101
102    /**
103     * Wi-Fi is currently being disabled. The state will change to {@link #WIFI_STATE_DISABLED} if
104     * it finishes successfully.
105     *
106     * @see #WIFI_STATE_CHANGED_ACTION
107     * @see #getWifiState()
108     */
109    public static final int WIFI_STATE_DISABLING = 0;
110    /**
111     * Wi-Fi is disabled.
112     *
113     * @see #WIFI_STATE_CHANGED_ACTION
114     * @see #getWifiState()
115     */
116    public static final int WIFI_STATE_DISABLED = 1;
117    /**
118     * Wi-Fi is currently being enabled. The state will change to {@link #WIFI_STATE_ENABLED} if
119     * it finishes successfully.
120     *
121     * @see #WIFI_STATE_CHANGED_ACTION
122     * @see #getWifiState()
123     */
124    public static final int WIFI_STATE_ENABLING = 2;
125    /**
126     * Wi-Fi is enabled.
127     *
128     * @see #WIFI_STATE_CHANGED_ACTION
129     * @see #getWifiState()
130     */
131    public static final int WIFI_STATE_ENABLED = 3;
132    /**
133     * Wi-Fi is in an unknown state. This state will occur when an error happens while enabling
134     * or disabling.
135     *
136     * @see #WIFI_STATE_CHANGED_ACTION
137     * @see #getWifiState()
138     */
139    public static final int WIFI_STATE_UNKNOWN = 4;
140
141    /**
142     * Broadcast intent action indicating that Wi-Fi AP has been enabled, disabled,
143     * enabling, disabling, or failed.
144     *
145     * @hide
146     */
147    public static final String WIFI_AP_STATE_CHANGED_ACTION =
148        "android.net.wifi.WIFI_AP_STATE_CHANGED";
149
150    /**
151     * The lookup key for an int that indicates whether Wi-Fi AP is enabled,
152     * disabled, enabling, disabling, or failed.  Retrieve it with
153     * {@link android.content.Intent#getIntExtra(String,int)}.
154     *
155     * @see #WIFI_AP_STATE_DISABLED
156     * @see #WIFI_AP_STATE_DISABLING
157     * @see #WIFI_AP_STATE_ENABLED
158     * @see #WIFI_AP_STATE_ENABLING
159     * @see #WIFI_AP_STATE_FAILED
160     *
161     * @hide
162     */
163    public static final String EXTRA_WIFI_AP_STATE = "wifi_state";
164    /**
165     * The previous Wi-Fi state.
166     *
167     * @see #EXTRA_WIFI_AP_STATE
168     *
169     * @hide
170     */
171    public static final String EXTRA_PREVIOUS_WIFI_AP_STATE = "previous_wifi_state";
172    /**
173     * Wi-Fi AP is currently being disabled. The state will change to
174     * {@link #WIFI_AP_STATE_DISABLED} if it finishes successfully.
175     *
176     * @see #WIFI_AP_STATE_CHANGED_ACTION
177     * @see #getWifiApState()
178     *
179     * @hide
180     */
181    public static final int WIFI_AP_STATE_DISABLING = 10;
182    /**
183     * Wi-Fi AP is disabled.
184     *
185     * @see #WIFI_AP_STATE_CHANGED_ACTION
186     * @see #getWifiState()
187     *
188     * @hide
189     */
190    public static final int WIFI_AP_STATE_DISABLED = 11;
191    /**
192     * Wi-Fi AP is currently being enabled. The state will change to
193     * {@link #WIFI_AP_STATE_ENABLED} if it finishes successfully.
194     *
195     * @see #WIFI_AP_STATE_CHANGED_ACTION
196     * @see #getWifiApState()
197     *
198     * @hide
199     */
200    public static final int WIFI_AP_STATE_ENABLING = 12;
201    /**
202     * Wi-Fi AP is enabled.
203     *
204     * @see #WIFI_AP_STATE_CHANGED_ACTION
205     * @see #getWifiApState()
206     *
207     * @hide
208     */
209    public static final int WIFI_AP_STATE_ENABLED = 13;
210    /**
211     * Wi-Fi AP is in a failed state. This state will occur when an error occurs during
212     * enabling or disabling
213     *
214     * @see #WIFI_AP_STATE_CHANGED_ACTION
215     * @see #getWifiApState()
216     *
217     * @hide
218     */
219    public static final int WIFI_AP_STATE_FAILED = 14;
220
221    /**
222     * Broadcast intent action indicating that a connection to the supplicant has
223     * been established (and it is now possible
224     * to perform Wi-Fi operations) or the connection to the supplicant has been
225     * lost. One extra provides the connection state as a boolean, where {@code true}
226     * means CONNECTED.
227     * @see #EXTRA_SUPPLICANT_CONNECTED
228     */
229    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
230    public static final String SUPPLICANT_CONNECTION_CHANGE_ACTION =
231        "android.net.wifi.supplicant.CONNECTION_CHANGE";
232    /**
233     * The lookup key for a boolean that indicates whether a connection to
234     * the supplicant daemon has been gained or lost. {@code true} means
235     * a connection now exists.
236     * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
237     */
238    public static final String EXTRA_SUPPLICANT_CONNECTED = "connected";
239    /**
240     * Broadcast intent action indicating that the state of Wi-Fi connectivity
241     * has changed. One extra provides the new state
242     * in the form of a {@link android.net.NetworkInfo} object. If the new
243     * state is CONNECTED, additional extras may provide the BSSID and WifiInfo of
244     * the access point.
245     * as a {@code String}.
246     * @see #EXTRA_NETWORK_INFO
247     * @see #EXTRA_BSSID
248     * @see #EXTRA_WIFI_INFO
249     */
250    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
251    public static final String NETWORK_STATE_CHANGED_ACTION = "android.net.wifi.STATE_CHANGE";
252    /**
253     * The lookup key for a {@link android.net.NetworkInfo} object associated with the
254     * Wi-Fi network. Retrieve with
255     * {@link android.content.Intent#getParcelableExtra(String)}.
256     */
257    public static final String EXTRA_NETWORK_INFO = "networkInfo";
258    /**
259     * The lookup key for a String giving the BSSID of the access point to which
260     * we are connected. Only present when the new state is CONNECTED.
261     * Retrieve with
262     * {@link android.content.Intent#getStringExtra(String)}.
263     */
264    public static final String EXTRA_BSSID = "bssid";
265    /**
266     * The lookup key for a {@link android.net.wifi.WifiInfo} object giving the
267     * information about the access point to which we are connected. Only present
268     * when the new state is CONNECTED.  Retrieve with
269     * {@link android.content.Intent#getParcelableExtra(String)}.
270     */
271    public static final String EXTRA_WIFI_INFO = "wifiInfo";
272    /**
273     * Broadcast intent action indicating that the state of establishing a connection to
274     * an access point has changed.One extra provides the new
275     * {@link SupplicantState}. Note that the supplicant state is Wi-Fi specific, and
276     * is not generally the most useful thing to look at if you are just interested in
277     * the overall state of connectivity.
278     * @see #EXTRA_NEW_STATE
279     * @see #EXTRA_SUPPLICANT_ERROR
280     */
281    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
282    public static final String SUPPLICANT_STATE_CHANGED_ACTION =
283        "android.net.wifi.supplicant.STATE_CHANGE";
284    /**
285     * The lookup key for a {@link SupplicantState} describing the new state
286     * Retrieve with
287     * {@link android.content.Intent#getParcelableExtra(String)}.
288     */
289    public static final String EXTRA_NEW_STATE = "newState";
290
291    /**
292     * The lookup key for a {@link SupplicantState} describing the supplicant
293     * error code if any
294     * Retrieve with
295     * {@link android.content.Intent#getIntExtra(String, int)}.
296     * @see #ERROR_AUTHENTICATING
297     */
298    public static final String EXTRA_SUPPLICANT_ERROR = "supplicantError";
299
300    /**
301     * Broadcast intent action indicating that the configured networks changed.
302     * This can be as a result of adding/updating/deleting a network. If
303     * {@link #EXTRA_MULTIPLE_NETWORKS_CHANGED} is set to true the new configuration
304     * can be retreived with the {@link #EXTRA_WIFI_CONFIGURATION} extra. If multiple
305     * Wi-Fi configurations changed, {@link #EXTRA_WIFI_CONFIGURATION} will not be present.
306     * @hide
307     */
308    public static final String CONFIGURED_NETWORKS_CHANGED_ACTION =
309        "android.net.wifi.CONFIGURED_NETWORKS_CHANGE";
310    /**
311     * The lookup key for a (@link android.net.wifi.WifiConfiguration} object representing
312     * the changed Wi-Fi configuration when the {@link #CONFIGURED_NETWORKS_CHANGED_ACTION}
313     * broadcast is sent.
314     * @hide
315     */
316    public static final String EXTRA_WIFI_CONFIGURATION = "wifiConfiguration";
317    /**
318     * Multiple network configurations have changed.
319     * @see #CONFIGURED_NETWORKS_CHANGED_ACTION
320     *
321     * @hide
322     */
323    public static final String EXTRA_MULTIPLE_NETWORKS_CHANGED = "multipleChanges";
324    /**
325     * The lookup key for an integer indicating the reason a Wi-Fi network configuration
326     * has changed. Only present if {@link #EXTRA_MULTIPLE_NETWORKS_CHANGED} is {@code false}
327     * @see #CONFIGURED_NETWORKS_CHANGED_ACTION
328     * @hide
329     */
330    public static final String EXTRA_CHANGE_REASON = "changeReason";
331    /**
332     * The configuration is new and was added.
333     * @hide
334     */
335    public static final int CHANGE_REASON_ADDED = 0;
336    /**
337     * The configuration was removed and is no longer present in the system's list of
338     * configured networks.
339     * @hide
340     */
341    public static final int CHANGE_REASON_REMOVED = 1;
342    /**
343     * The configuration has changed as a result of explicit action or because the system
344     * took an automated action such as disabling a malfunctioning configuration.
345     * @hide
346     */
347    public static final int CHANGE_REASON_CONFIG_CHANGE = 2;
348    /**
349     * An access point scan has completed, and results are available from the supplicant.
350     * Call {@link #getScanResults()} to obtain the results.
351     */
352    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
353    public static final String SCAN_RESULTS_AVAILABLE_ACTION = "android.net.wifi.SCAN_RESULTS";
354    /**
355     * The RSSI (signal strength) has changed.
356     * @see #EXTRA_NEW_RSSI
357     */
358    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
359    public static final String RSSI_CHANGED_ACTION = "android.net.wifi.RSSI_CHANGED";
360    /**
361     * The lookup key for an {@code int} giving the new RSSI in dBm.
362     */
363    public static final String EXTRA_NEW_RSSI = "newRssi";
364
365    /**
366     * Broadcast intent action indicating that the link configuration
367     * changed on wifi.
368     * @hide
369     */
370    public static final String LINK_CONFIGURATION_CHANGED_ACTION =
371        "android.net.wifi.LINK_CONFIGURATION_CHANGED";
372
373    /**
374     * The lookup key for a {@link android.net.LinkProperties} object associated with the
375     * Wi-Fi network. Retrieve with
376     * {@link android.content.Intent#getParcelableExtra(String)}.
377     * @hide
378     */
379    public static final String EXTRA_LINK_PROPERTIES = "linkProperties";
380
381    /**
382     * The lookup key for a {@link android.net.LinkCapabilities} object associated with the
383     * Wi-Fi network. Retrieve with
384     * {@link android.content.Intent#getParcelableExtra(String)}.
385     * @hide
386     */
387    public static final String EXTRA_LINK_CAPABILITIES = "linkCapabilities";
388
389    /**
390     * The network IDs of the configured networks could have changed.
391     */
392    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
393    public static final String NETWORK_IDS_CHANGED_ACTION = "android.net.wifi.NETWORK_IDS_CHANGED";
394
395    /**
396     * Activity Action: Pick a Wi-Fi network to connect to.
397     * <p>Input: Nothing.
398     * <p>Output: Nothing.
399     */
400    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
401    public static final String ACTION_PICK_WIFI_NETWORK = "android.net.wifi.PICK_WIFI_NETWORK";
402
403    /**
404     * In this Wi-Fi lock mode, Wi-Fi will be kept active,
405     * and will behave normally, i.e., it will attempt to automatically
406     * establish a connection to a remembered access point that is
407     * within range, and will do periodic scans if there are remembered
408     * access points but none are in range.
409     */
410    public static final int WIFI_MODE_FULL = 1;
411    /**
412     * In this Wi-Fi lock mode, Wi-Fi will be kept active,
413     * but the only operation that will be supported is initiation of
414     * scans, and the subsequent reporting of scan results. No attempts
415     * will be made to automatically connect to remembered access points,
416     * nor will periodic scans be automatically performed looking for
417     * remembered access points. Scans must be explicitly requested by
418     * an application in this mode.
419     */
420    public static final int WIFI_MODE_SCAN_ONLY = 2;
421    /**
422     * In this Wi-Fi lock mode, Wi-Fi will be kept active as in mode
423     * {@link #WIFI_MODE_FULL} but it operates at high performance
424     * with minimum packet loss and low packet latency even when
425     * the device screen is off. This mode will consume more power
426     * and hence should be used only when there is a need for such
427     * an active connection.
428     * <p>
429     * An example use case is when a voice connection needs to be
430     * kept active even after the device screen goes off. Holding the
431     * regular {@link #WIFI_MODE_FULL} lock will keep the wifi
432     * connection active, but the connection can be lossy.
433     * Holding a {@link #WIFI_MODE_FULL_HIGH_PERF} lock for the
434     * duration of the voice call will improve the call quality.
435     * <p>
436     * When there is no support from the hardware, this lock mode
437     * will have the same behavior as {@link #WIFI_MODE_FULL}
438     */
439    public static final int WIFI_MODE_FULL_HIGH_PERF = 3;
440
441    /** Anything worse than or equal to this will show 0 bars. */
442    private static final int MIN_RSSI = -100;
443
444    /** Anything better than or equal to this will show the max bars. */
445    private static final int MAX_RSSI = -55;
446
447    /**
448     * Number of RSSI levels used in the framework to initiate
449     * {@link #RSSI_CHANGED_ACTION} broadcast
450     * @hide
451     */
452    public static final int RSSI_LEVELS = 5;
453
454    /**
455     * Auto settings in the driver. The driver could choose to operate on both
456     * 2.4 GHz and 5 GHz or make a dynamic decision on selecting the band.
457     * @hide
458     */
459    public static final int WIFI_FREQUENCY_BAND_AUTO = 0;
460
461    /**
462     * Operation on 5 GHz alone
463     * @hide
464     */
465    public static final int WIFI_FREQUENCY_BAND_5GHZ = 1;
466
467    /**
468     * Operation on 2.4 GHz alone
469     * @hide
470     */
471    public static final int WIFI_FREQUENCY_BAND_2GHZ = 2;
472
473    /** List of asyncronous notifications
474     * @hide
475     */
476    public static final int DATA_ACTIVITY_NOTIFICATION = 1;
477
478    //Lowest bit indicates data reception and the second lowest
479    //bit indicates data transmitted
480    /** @hide */
481    public static final int DATA_ACTIVITY_NONE         = 0x00;
482    /** @hide */
483    public static final int DATA_ACTIVITY_IN           = 0x01;
484    /** @hide */
485    public static final int DATA_ACTIVITY_OUT          = 0x02;
486    /** @hide */
487    public static final int DATA_ACTIVITY_INOUT        = 0x03;
488
489    /* Maximum number of active locks we allow.
490     * This limit was added to prevent apps from creating a ridiculous number
491     * of locks and crashing the system by overflowing the global ref table.
492     */
493    private static final int MAX_ACTIVE_LOCKS = 50;
494
495    /* Number of currently active WifiLocks and MulticastLocks */
496    private int mActiveLockCount;
497
498    private Context mContext;
499    IWifiManager mService;
500
501    private static final int INVALID_KEY = 0;
502    private static int sListenerKey = 1;
503    private static final SparseArray sListenerMap = new SparseArray();
504    private static final Object sListenerMapLock = new Object();
505
506    private static AsyncChannel sAsyncChannel;
507    private static CountDownLatch sConnected;
508
509    private static final Object sThreadRefLock = new Object();
510    private static int sThreadRefCount;
511    private static HandlerThread sHandlerThread;
512
513    /**
514     * Create a new WifiManager instance.
515     * Applications will almost always want to use
516     * {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve
517     * the standard {@link android.content.Context#WIFI_SERVICE Context.WIFI_SERVICE}.
518     * @param context the application context
519     * @param service the Binder interface
520     * @hide - hide this because it takes in a parameter of type IWifiManager, which
521     * is a system private class.
522     */
523    public WifiManager(Context context, IWifiManager service) {
524        mContext = context;
525        mService = service;
526        init();
527    }
528
529    /**
530     * Return a list of all the networks configured in the supplicant.
531     * Not all fields of WifiConfiguration are returned. Only the following
532     * fields are filled in:
533     * <ul>
534     * <li>networkId</li>
535     * <li>SSID</li>
536     * <li>BSSID</li>
537     * <li>priority</li>
538     * <li>allowedProtocols</li>
539     * <li>allowedKeyManagement</li>
540     * <li>allowedAuthAlgorithms</li>
541     * <li>allowedPairwiseCiphers</li>
542     * <li>allowedGroupCiphers</li>
543     * </ul>
544     * @return a list of network configurations in the form of a list
545     * of {@link WifiConfiguration} objects. Upon failure to fetch or
546     * when when Wi-Fi is turned off, it can be null.
547     */
548    public List<WifiConfiguration> getConfiguredNetworks() {
549        try {
550            return mService.getConfiguredNetworks();
551        } catch (RemoteException e) {
552            return null;
553        }
554    }
555
556    /**
557     * Add a new network description to the set of configured networks.
558     * The {@code networkId} field of the supplied configuration object
559     * is ignored.
560     * <p/>
561     * The new network will be marked DISABLED by default. To enable it,
562     * called {@link #enableNetwork}.
563     *
564     * @param config the set of variables that describe the configuration,
565     *            contained in a {@link WifiConfiguration} object.
566     * @return the ID of the newly created network description. This is used in
567     *         other operations to specified the network to be acted upon.
568     *         Returns {@code -1} on failure.
569     */
570    public int addNetwork(WifiConfiguration config) {
571        if (config == null) {
572            return -1;
573        }
574        config.networkId = -1;
575        return addOrUpdateNetwork(config);
576    }
577
578    /**
579     * Update the network description of an existing configured network.
580     *
581     * @param config the set of variables that describe the configuration,
582     *            contained in a {@link WifiConfiguration} object. It may
583     *            be sparse, so that only the items that are being changed
584     *            are non-<code>null</code>. The {@code networkId} field
585     *            must be set to the ID of the existing network being updated.
586     * @return Returns the {@code networkId} of the supplied
587     *         {@code WifiConfiguration} on success.
588     *         <br/>
589     *         Returns {@code -1} on failure, including when the {@code networkId}
590     *         field of the {@code WifiConfiguration} does not refer to an
591     *         existing network.
592     */
593    public int updateNetwork(WifiConfiguration config) {
594        if (config == null || config.networkId < 0) {
595            return -1;
596        }
597        return addOrUpdateNetwork(config);
598    }
599
600    /**
601     * Internal method for doing the RPC that creates a new network description
602     * or updates an existing one.
603     *
604     * @param config The possibly sparse object containing the variables that
605     *         are to set or updated in the network description.
606     * @return the ID of the network on success, {@code -1} on failure.
607     */
608    private int addOrUpdateNetwork(WifiConfiguration config) {
609        try {
610            return mService.addOrUpdateNetwork(config);
611        } catch (RemoteException e) {
612            return -1;
613        }
614    }
615
616    /**
617     * Remove the specified network from the list of configured networks.
618     * This may result in the asynchronous delivery of state change
619     * events.
620     * @param netId the integer that identifies the network configuration
621     * to the supplicant
622     * @return {@code true} if the operation succeeded
623     */
624    public boolean removeNetwork(int netId) {
625        try {
626            return mService.removeNetwork(netId);
627        } catch (RemoteException e) {
628            return false;
629        }
630    }
631
632    /**
633     * Allow a previously configured network to be associated with. If
634     * <code>disableOthers</code> is true, then all other configured
635     * networks are disabled, and an attempt to connect to the selected
636     * network is initiated. This may result in the asynchronous delivery
637     * of state change events.
638     * @param netId the ID of the network in the list of configured networks
639     * @param disableOthers if true, disable all other networks. The way to
640     * select a particular network to connect to is specify {@code true}
641     * for this parameter.
642     * @return {@code true} if the operation succeeded
643     */
644    public boolean enableNetwork(int netId, boolean disableOthers) {
645        try {
646            return mService.enableNetwork(netId, disableOthers);
647        } catch (RemoteException e) {
648            return false;
649        }
650    }
651
652    /**
653     * Disable a configured network. The specified network will not be
654     * a candidate for associating. This may result in the asynchronous
655     * delivery of state change events.
656     * @param netId the ID of the network as returned by {@link #addNetwork}.
657     * @return {@code true} if the operation succeeded
658     */
659    public boolean disableNetwork(int netId) {
660        try {
661            return mService.disableNetwork(netId);
662        } catch (RemoteException e) {
663            return false;
664        }
665    }
666
667    /**
668     * Disassociate from the currently active access point. This may result
669     * in the asynchronous delivery of state change events.
670     * @return {@code true} if the operation succeeded
671     */
672    public boolean disconnect() {
673        try {
674            mService.disconnect();
675            return true;
676        } catch (RemoteException e) {
677            return false;
678        }
679    }
680
681    /**
682     * Reconnect to the currently active access point, if we are currently
683     * disconnected. This may result in the asynchronous delivery of state
684     * change events.
685     * @return {@code true} if the operation succeeded
686     */
687    public boolean reconnect() {
688        try {
689            mService.reconnect();
690            return true;
691        } catch (RemoteException e) {
692            return false;
693        }
694    }
695
696    /**
697     * Reconnect to the currently active access point, even if we are already
698     * connected. This may result in the asynchronous delivery of state
699     * change events.
700     * @return {@code true} if the operation succeeded
701     */
702    public boolean reassociate() {
703        try {
704            mService.reassociate();
705            return true;
706        } catch (RemoteException e) {
707            return false;
708        }
709    }
710
711    /**
712     * Check that the supplicant daemon is responding to requests.
713     * @return {@code true} if we were able to communicate with the supplicant and
714     * it returned the expected response to the PING message.
715     */
716    public boolean pingSupplicant() {
717        if (mService == null)
718            return false;
719        try {
720            return mService.pingSupplicant();
721        } catch (RemoteException e) {
722            return false;
723        }
724    }
725
726    /**
727     * Request a scan for access points. Returns immediately. The availability
728     * of the results is made known later by means of an asynchronous event sent
729     * on completion of the scan.
730     * @return {@code true} if the operation succeeded, i.e., the scan was initiated
731     */
732    public boolean startScan() {
733        try {
734            mService.startScan();
735            return true;
736        } catch (RemoteException e) {
737            return false;
738        }
739    }
740
741    /**
742     * Return dynamic information about the current Wi-Fi connection, if any is active.
743     * @return the Wi-Fi information, contained in {@link WifiInfo}.
744     */
745    public WifiInfo getConnectionInfo() {
746        try {
747            return mService.getConnectionInfo();
748        } catch (RemoteException e) {
749            return null;
750        }
751    }
752
753    /**
754     * Return the results of the latest access point scan.
755     * @return the list of access points found in the most recent scan.
756     */
757    public List<ScanResult> getScanResults() {
758        try {
759            return mService.getScanResults(mContext.getBasePackageName());
760        } catch (RemoteException e) {
761            return null;
762        }
763    }
764
765    /**
766     * Tell the supplicant to persist the current list of configured networks.
767     * <p>
768     * Note: It is possible for this method to change the network IDs of
769     * existing networks. You should assume the network IDs can be different
770     * after calling this method.
771     *
772     * @return {@code true} if the operation succeeded
773     */
774    public boolean saveConfiguration() {
775        try {
776            return mService.saveConfiguration();
777        } catch (RemoteException e) {
778            return false;
779        }
780    }
781
782    /**
783     * Set the country code.
784     * @param countryCode country code in ISO 3166 format.
785     * @param persist {@code true} if this needs to be remembered
786     *
787     * @hide
788     */
789    public void setCountryCode(String country, boolean persist) {
790        try {
791            mService.setCountryCode(country, persist);
792        } catch (RemoteException e) { }
793    }
794
795    /**
796     * Set the operational frequency band.
797     * @param band  One of
798     *     {@link #WIFI_FREQUENCY_BAND_AUTO},
799     *     {@link #WIFI_FREQUENCY_BAND_5GHZ},
800     *     {@link #WIFI_FREQUENCY_BAND_2GHZ},
801     * @param persist {@code true} if this needs to be remembered
802     * @hide
803     */
804    public void setFrequencyBand(int band, boolean persist) {
805        try {
806            mService.setFrequencyBand(band, persist);
807        } catch (RemoteException e) { }
808    }
809
810    /**
811     * Get the operational frequency band.
812     * @return One of
813     *     {@link #WIFI_FREQUENCY_BAND_AUTO},
814     *     {@link #WIFI_FREQUENCY_BAND_5GHZ},
815     *     {@link #WIFI_FREQUENCY_BAND_2GHZ} or
816     *     {@code -1} on failure.
817     * @hide
818     */
819    public int getFrequencyBand() {
820        try {
821            return mService.getFrequencyBand();
822        } catch (RemoteException e) {
823            return -1;
824        }
825    }
826
827    /**
828     * Check if the chipset supports dual frequency band (2.4 GHz and 5 GHz)
829     * @return {@code true} if supported, {@code false} otherwise.
830     * @hide
831     */
832    public boolean isDualBandSupported() {
833        try {
834            return mService.isDualBandSupported();
835        } catch (RemoteException e) {
836            return false;
837        }
838    }
839
840    /**
841     * Return the DHCP-assigned addresses from the last successful DHCP request,
842     * if any.
843     * @return the DHCP information
844     * @deprecated - use ConnectivityManager.getLinkProperties instead.  TODO - remove 11/2013
845     */
846    public DhcpInfo getDhcpInfo() {
847        try {
848            return mService.getDhcpInfo();
849        } catch (RemoteException e) {
850            return null;
851        }
852    }
853
854    /**
855     * Enable or disable Wi-Fi.
856     * @param enabled {@code true} to enable, {@code false} to disable.
857     * @return {@code true} if the operation succeeds (or if the existing state
858     *         is the same as the requested state).
859     */
860    public boolean setWifiEnabled(boolean enabled) {
861        try {
862            return mService.setWifiEnabled(enabled);
863        } catch (RemoteException e) {
864            return false;
865        }
866    }
867
868    /**
869     * Gets the Wi-Fi enabled state.
870     * @return One of {@link #WIFI_STATE_DISABLED},
871     *         {@link #WIFI_STATE_DISABLING}, {@link #WIFI_STATE_ENABLED},
872     *         {@link #WIFI_STATE_ENABLING}, {@link #WIFI_STATE_UNKNOWN}
873     * @see #isWifiEnabled()
874     */
875    public int getWifiState() {
876        try {
877            return mService.getWifiEnabledState();
878        } catch (RemoteException e) {
879            return WIFI_STATE_UNKNOWN;
880        }
881    }
882
883    /**
884     * Return whether Wi-Fi is enabled or disabled.
885     * @return {@code true} if Wi-Fi is enabled
886     * @see #getWifiState()
887     */
888    public boolean isWifiEnabled() {
889        return getWifiState() == WIFI_STATE_ENABLED;
890    }
891
892    /**
893     * Return TX packet counter, for CTS test of WiFi watchdog.
894     * @param listener is the interface to receive result
895     *
896     * @hide for CTS test only
897     */
898    public void getTxPacketCount(TxPacketCountListener listener) {
899        validateChannel();
900        sAsyncChannel.sendMessage(RSSI_PKTCNT_FETCH, 0, putListener(listener));
901    }
902
903    /**
904     * Calculates the level of the signal. This should be used any time a signal
905     * is being shown.
906     *
907     * @param rssi The power of the signal measured in RSSI.
908     * @param numLevels The number of levels to consider in the calculated
909     *            level.
910     * @return A level of the signal, given in the range of 0 to numLevels-1
911     *         (both inclusive).
912     */
913    public static int calculateSignalLevel(int rssi, int numLevels) {
914        if (rssi <= MIN_RSSI) {
915            return 0;
916        } else if (rssi >= MAX_RSSI) {
917            return numLevels - 1;
918        } else {
919            float inputRange = (MAX_RSSI - MIN_RSSI);
920            float outputRange = (numLevels - 1);
921            return (int)((float)(rssi - MIN_RSSI) * outputRange / inputRange);
922        }
923    }
924
925    /**
926     * Compares two signal strengths.
927     *
928     * @param rssiA The power of the first signal measured in RSSI.
929     * @param rssiB The power of the second signal measured in RSSI.
930     * @return Returns <0 if the first signal is weaker than the second signal,
931     *         0 if the two signals have the same strength, and >0 if the first
932     *         signal is stronger than the second signal.
933     */
934    public static int compareSignalLevel(int rssiA, int rssiB) {
935        return rssiA - rssiB;
936    }
937
938    /**
939     * Start AccessPoint mode with the specified
940     * configuration. If the radio is already running in
941     * AP mode, update the new configuration
942     * Note that starting in access point mode disables station
943     * mode operation
944     * @param wifiConfig SSID, security and channel details as
945     *        part of WifiConfiguration
946     * @return {@code true} if the operation succeeds, {@code false} otherwise
947     *
948     * @hide Dont open up yet
949     */
950    public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
951        try {
952            mService.setWifiApEnabled(wifiConfig, enabled);
953            return true;
954        } catch (RemoteException e) {
955            return false;
956        }
957    }
958
959    /**
960     * Gets the Wi-Fi enabled state.
961     * @return One of {@link #WIFI_AP_STATE_DISABLED},
962     *         {@link #WIFI_AP_STATE_DISABLING}, {@link #WIFI_AP_STATE_ENABLED},
963     *         {@link #WIFI_AP_STATE_ENABLING}, {@link #WIFI_AP_STATE_FAILED}
964     * @see #isWifiApEnabled()
965     *
966     * @hide Dont open yet
967     */
968    public int getWifiApState() {
969        try {
970            return mService.getWifiApEnabledState();
971        } catch (RemoteException e) {
972            return WIFI_AP_STATE_FAILED;
973        }
974    }
975
976    /**
977     * Return whether Wi-Fi AP is enabled or disabled.
978     * @return {@code true} if Wi-Fi AP is enabled
979     * @see #getWifiApState()
980     *
981     * @hide Dont open yet
982     */
983    public boolean isWifiApEnabled() {
984        return getWifiApState() == WIFI_AP_STATE_ENABLED;
985    }
986
987    /**
988     * Gets the Wi-Fi AP Configuration.
989     * @return AP details in WifiConfiguration
990     *
991     * @hide Dont open yet
992     */
993    public WifiConfiguration getWifiApConfiguration() {
994        try {
995            return mService.getWifiApConfiguration();
996        } catch (RemoteException e) {
997            return null;
998        }
999    }
1000
1001    /**
1002     * Sets the Wi-Fi AP Configuration.
1003     * @return {@code true} if the operation succeeded, {@code false} otherwise
1004     *
1005     * @hide Dont open yet
1006     */
1007    public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
1008        try {
1009            mService.setWifiApConfiguration(wifiConfig);
1010            return true;
1011        } catch (RemoteException e) {
1012            return false;
1013        }
1014    }
1015
1016   /**
1017     * Start the driver and connect to network.
1018     *
1019     * This function will over-ride WifiLock and device idle status. For example,
1020     * even if the device is idle or there is only a scan-only lock held,
1021     * a start wifi would mean that wifi connection is kept active until
1022     * a stopWifi() is sent.
1023     *
1024     * This API is used by WifiStateTracker
1025     *
1026     * @return {@code true} if the operation succeeds else {@code false}
1027     * @hide
1028     */
1029    public boolean startWifi() {
1030        try {
1031            mService.startWifi();
1032            return true;
1033        } catch (RemoteException e) {
1034            return false;
1035        }
1036    }
1037
1038    /**
1039     * Disconnect from a network (if any) and stop the driver.
1040     *
1041     * This function will over-ride WifiLock and device idle status. Wi-Fi
1042     * stays inactive until a startWifi() is issued.
1043     *
1044     * This API is used by WifiStateTracker
1045     *
1046     * @return {@code true} if the operation succeeds else {@code false}
1047     * @hide
1048     */
1049    public boolean stopWifi() {
1050        try {
1051            mService.stopWifi();
1052            return true;
1053        } catch (RemoteException e) {
1054            return false;
1055        }
1056    }
1057
1058    /**
1059     * Add a bssid to the supplicant blacklist
1060     *
1061     * This API is used by WifiWatchdogService
1062     *
1063     * @return {@code true} if the operation succeeds else {@code false}
1064     * @hide
1065     */
1066    public boolean addToBlacklist(String bssid) {
1067        try {
1068            mService.addToBlacklist(bssid);
1069            return true;
1070        } catch (RemoteException e) {
1071            return false;
1072        }
1073    }
1074
1075    /**
1076     * Clear the supplicant blacklist
1077     *
1078     * This API is used by WifiWatchdogService
1079     *
1080     * @return {@code true} if the operation succeeds else {@code false}
1081     * @hide
1082     */
1083    public boolean clearBlacklist() {
1084        try {
1085            mService.clearBlacklist();
1086            return true;
1087        } catch (RemoteException e) {
1088            return false;
1089        }
1090    }
1091
1092    /* TODO: deprecate synchronous API and open up the following API */
1093
1094    private static final int BASE = Protocol.BASE_WIFI_MANAGER;
1095
1096    /* Commands to WifiService */
1097    /** @hide */
1098    public static final int CONNECT_NETWORK                 = BASE + 1;
1099    /** @hide */
1100    public static final int CONNECT_NETWORK_FAILED          = BASE + 2;
1101    /** @hide */
1102    public static final int CONNECT_NETWORK_SUCCEEDED       = BASE + 3;
1103
1104    /** @hide */
1105    public static final int FORGET_NETWORK                  = BASE + 4;
1106    /** @hide */
1107    public static final int FORGET_NETWORK_FAILED           = BASE + 5;
1108    /** @hide */
1109    public static final int FORGET_NETWORK_SUCCEEDED        = BASE + 6;
1110
1111    /** @hide */
1112    public static final int SAVE_NETWORK                    = BASE + 7;
1113    /** @hide */
1114    public static final int SAVE_NETWORK_FAILED             = BASE + 8;
1115    /** @hide */
1116    public static final int SAVE_NETWORK_SUCCEEDED          = BASE + 9;
1117
1118    /** @hide */
1119    public static final int START_WPS                       = BASE + 10;
1120    /** @hide */
1121    public static final int START_WPS_SUCCEEDED             = BASE + 11;
1122    /** @hide */
1123    public static final int WPS_FAILED                      = BASE + 12;
1124    /** @hide */
1125    public static final int WPS_COMPLETED                   = BASE + 13;
1126
1127    /** @hide */
1128    public static final int CANCEL_WPS                      = BASE + 14;
1129    /** @hide */
1130    public static final int CANCEL_WPS_FAILED               = BASE + 15;
1131    /** @hide */
1132    public static final int CANCEL_WPS_SUCCEDED             = BASE + 16;
1133
1134    /** @hide */
1135    public static final int DISABLE_NETWORK                 = BASE + 17;
1136    /** @hide */
1137    public static final int DISABLE_NETWORK_FAILED          = BASE + 18;
1138    /** @hide */
1139    public static final int DISABLE_NETWORK_SUCCEEDED       = BASE + 19;
1140
1141    /** @hide */
1142    public static final int RSSI_PKTCNT_FETCH               = BASE + 20;
1143    /** @hide */
1144    public static final int RSSI_PKTCNT_FETCH_SUCCEEDED     = BASE + 21;
1145    /** @hide */
1146    public static final int RSSI_PKTCNT_FETCH_FAILED        = BASE + 22;
1147
1148    /* For system use only */
1149    /** @hide */
1150    public static final int ENABLE_TRAFFIC_STATS_POLL       = BASE + 31;
1151    /** @hide */
1152    public static final int TRAFFIC_STATS_POLL              = BASE + 32;
1153
1154
1155    /**
1156     * Passed with {@link ActionListener#onFailure}.
1157     * Indicates that the operation failed due to an internal error.
1158     * @hide
1159     */
1160    public static final int ERROR                       = 0;
1161
1162    /**
1163     * Passed with {@link ActionListener#onFailure}.
1164     * Indicates that the operation is already in progress
1165     * @hide
1166     */
1167    public static final int IN_PROGRESS                 = 1;
1168
1169    /**
1170     * Passed with {@link ActionListener#onFailure}.
1171     * Indicates that the operation failed because the framework is busy and
1172     * unable to service the request
1173     * @hide
1174     */
1175    public static final int BUSY                        = 2;
1176
1177    /* WPS specific errors */
1178    /** WPS overlap detected {@hide} */
1179    public static final int WPS_OVERLAP_ERROR           = 3;
1180    /** WEP on WPS is prohibited {@hide} */
1181    public static final int WPS_WEP_PROHIBITED          = 4;
1182    /** TKIP only prohibited {@hide} */
1183    public static final int WPS_TKIP_ONLY_PROHIBITED    = 5;
1184    /** Authentication failure on WPS {@hide} */
1185    public static final int WPS_AUTH_FAILURE            = 6;
1186    /** WPS timed out {@hide} */
1187    public static final int WPS_TIMED_OUT               = 7;
1188
1189    /** Interface for callback invocation on an application action {@hide} */
1190    public interface ActionListener {
1191        /** The operation succeeded */
1192        public void onSuccess();
1193        /**
1194         * The operation failed
1195         * @param reason The reason for failure could be one of
1196         * {@link #ERROR}, {@link #IN_PROGRESS} or {@link #BUSY}
1197         */
1198        public void onFailure(int reason);
1199    }
1200
1201    /** Interface for callback invocation on a start WPS action {@hide} */
1202    public interface WpsListener {
1203        /** WPS start succeeded */
1204        public void onStartSuccess(String pin);
1205
1206        /** WPS operation completed succesfully */
1207        public void onCompletion();
1208
1209        /**
1210         * WPS operation failed
1211         * @param reason The reason for failure could be one of
1212         * {@link #IN_PROGRESS}, {@link #WPS_OVERLAP_ERROR},{@link #ERROR} or {@link #BUSY}
1213         */
1214        public void onFailure(int reason);
1215    }
1216
1217    /** Interface for callback invocation on a TX packet count poll action {@hide} */
1218    public interface TxPacketCountListener {
1219        /**
1220         * The operation succeeded
1221         * @param count TX packet counter
1222         */
1223        public void onSuccess(int count);
1224        /**
1225         * The operation failed
1226         * @param reason The reason for failure could be one of
1227         * {@link #ERROR}, {@link #IN_PROGRESS} or {@link #BUSY}
1228         */
1229        public void onFailure(int reason);
1230    }
1231
1232    private static class ServiceHandler extends Handler {
1233        ServiceHandler(Looper looper) {
1234            super(looper);
1235        }
1236
1237        @Override
1238        public void handleMessage(Message message) {
1239            Object listener = removeListener(message.arg2);
1240            switch (message.what) {
1241                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
1242                    if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1243                        sAsyncChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
1244                    } else {
1245                        Log.e(TAG, "Failed to set up channel connection");
1246                        // This will cause all further async API calls on the WifiManager
1247                        // to fail and throw an exception
1248                        sAsyncChannel = null;
1249                    }
1250                    sConnected.countDown();
1251                    break;
1252                case AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED:
1253                    // Ignore
1254                    break;
1255                case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
1256                    Log.e(TAG, "Channel connection lost");
1257                    // This will cause all further async API calls on the WifiManager
1258                    // to fail and throw an exception
1259                    sAsyncChannel = null;
1260                    getLooper().quit();
1261                    break;
1262                    /* ActionListeners grouped together */
1263                case WifiManager.CONNECT_NETWORK_FAILED:
1264                case WifiManager.FORGET_NETWORK_FAILED:
1265                case WifiManager.SAVE_NETWORK_FAILED:
1266                case WifiManager.CANCEL_WPS_FAILED:
1267                case WifiManager.DISABLE_NETWORK_FAILED:
1268                    if (listener != null) {
1269                        ((ActionListener) listener).onFailure(message.arg1);
1270                    }
1271                    break;
1272                    /* ActionListeners grouped together */
1273                case WifiManager.CONNECT_NETWORK_SUCCEEDED:
1274                case WifiManager.FORGET_NETWORK_SUCCEEDED:
1275                case WifiManager.SAVE_NETWORK_SUCCEEDED:
1276                case WifiManager.CANCEL_WPS_SUCCEDED:
1277                case WifiManager.DISABLE_NETWORK_SUCCEEDED:
1278                    if (listener != null) {
1279                        ((ActionListener) listener).onSuccess();
1280                    }
1281                    break;
1282                case WifiManager.START_WPS_SUCCEEDED:
1283                    if (listener != null) {
1284                        WpsResult result = (WpsResult) message.obj;
1285                        ((WpsListener) listener).onStartSuccess(result.pin);
1286                        //Listener needs to stay until completion or failure
1287                        synchronized(sListenerMapLock) {
1288                            sListenerMap.put(message.arg2, listener);
1289                        }
1290                    }
1291                    break;
1292                case WifiManager.WPS_COMPLETED:
1293                    if (listener != null) {
1294                        ((WpsListener) listener).onCompletion();
1295                    }
1296                    break;
1297                case WifiManager.WPS_FAILED:
1298                    if (listener != null) {
1299                        ((WpsListener) listener).onFailure(message.arg1);
1300                    }
1301                    break;
1302                case WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED:
1303                    if (listener != null) {
1304                        RssiPacketCountInfo info = (RssiPacketCountInfo) message.obj;
1305                        if (info != null)
1306                            ((TxPacketCountListener) listener).onSuccess(info.txgood + info.txbad);
1307                        else
1308                            ((TxPacketCountListener) listener).onFailure(ERROR);
1309                    }
1310                    break;
1311                case WifiManager.RSSI_PKTCNT_FETCH_FAILED:
1312                    if (listener != null) {
1313                        ((TxPacketCountListener) listener).onFailure(message.arg1);
1314                    }
1315                    break;
1316                default:
1317                    //ignore
1318                    break;
1319            }
1320        }
1321    }
1322
1323    private static int putListener(Object listener) {
1324        if (listener == null) return INVALID_KEY;
1325        int key;
1326        synchronized (sListenerMapLock) {
1327            do {
1328                key = sListenerKey++;
1329            } while (key == INVALID_KEY);
1330            sListenerMap.put(key, listener);
1331        }
1332        return key;
1333    }
1334
1335    private static Object removeListener(int key) {
1336        if (key == INVALID_KEY) return null;
1337        synchronized (sListenerMapLock) {
1338            Object listener = sListenerMap.get(key);
1339            sListenerMap.remove(key);
1340            return listener;
1341        }
1342    }
1343
1344    private void init() {
1345        synchronized (sThreadRefLock) {
1346            if (++sThreadRefCount == 1) {
1347                Messenger messenger = getWifiServiceMessenger();
1348                if (messenger == null) {
1349                    sAsyncChannel = null;
1350                    return;
1351                }
1352
1353                sHandlerThread = new HandlerThread("WifiManager");
1354                sAsyncChannel = new AsyncChannel();
1355                sConnected = new CountDownLatch(1);
1356
1357                sHandlerThread.start();
1358                Handler handler = new ServiceHandler(sHandlerThread.getLooper());
1359                sAsyncChannel.connect(mContext, handler, messenger);
1360                try {
1361                    sConnected.await();
1362                } catch (InterruptedException e) {
1363                    Log.e(TAG, "interrupted wait at init");
1364                }
1365            }
1366        }
1367    }
1368
1369    private void validateChannel() {
1370        if (sAsyncChannel == null) throw new IllegalStateException(
1371                "No permission to access and change wifi or a bad initialization");
1372    }
1373
1374    /**
1375     * Connect to a network with the given configuration. The network also
1376     * gets added to the supplicant configuration.
1377     *
1378     * For a new network, this function is used instead of a
1379     * sequence of addNetwork(), enableNetwork(), saveConfiguration() and
1380     * reconnect()
1381     *
1382     * @param config the set of variables that describe the configuration,
1383     *            contained in a {@link WifiConfiguration} object.
1384     * @param listener for callbacks on success or failure. Can be null.
1385     * @throws IllegalStateException if the WifiManager instance needs to be
1386     * initialized again
1387     *
1388     * @hide
1389     */
1390    public void connect(WifiConfiguration config, ActionListener listener) {
1391        if (config == null) throw new IllegalArgumentException("config cannot be null");
1392        validateChannel();
1393        // Use INVALID_NETWORK_ID for arg1 when passing a config object
1394        // arg1 is used to pass network id when the network already exists
1395        sAsyncChannel.sendMessage(CONNECT_NETWORK, WifiConfiguration.INVALID_NETWORK_ID,
1396                putListener(listener), config);
1397    }
1398
1399    /**
1400     * Connect to a network with the given networkId.
1401     *
1402     * This function is used instead of a enableNetwork(), saveConfiguration() and
1403     * reconnect()
1404     *
1405     * @param networkId the network id identifiying the network in the
1406     *                supplicant configuration list
1407     * @param listener for callbacks on success or failure. Can be null.
1408     * @throws IllegalStateException if the WifiManager instance needs to be
1409     * initialized again
1410     * @hide
1411     */
1412    public void connect(int networkId, ActionListener listener) {
1413        if (networkId < 0) throw new IllegalArgumentException("Network id cannot be negative");
1414        validateChannel();
1415        sAsyncChannel.sendMessage(CONNECT_NETWORK, networkId, putListener(listener));
1416    }
1417
1418    /**
1419     * Save the given network in the supplicant config. If the network already
1420     * exists, the configuration is updated. A new network is enabled
1421     * by default.
1422     *
1423     * For a new network, this function is used instead of a
1424     * sequence of addNetwork(), enableNetwork() and saveConfiguration().
1425     *
1426     * For an existing network, it accomplishes the task of updateNetwork()
1427     * and saveConfiguration()
1428     *
1429     * @param config the set of variables that describe the configuration,
1430     *            contained in a {@link WifiConfiguration} object.
1431     * @param listener for callbacks on success or failure. Can be null.
1432     * @throws IllegalStateException if the WifiManager instance needs to be
1433     * initialized again
1434     * @hide
1435     */
1436    public void save(WifiConfiguration config, ActionListener listener) {
1437        if (config == null) throw new IllegalArgumentException("config cannot be null");
1438        validateChannel();
1439        sAsyncChannel.sendMessage(SAVE_NETWORK, 0, putListener(listener), config);
1440    }
1441
1442    /**
1443     * Delete the network in the supplicant config.
1444     *
1445     * This function is used instead of a sequence of removeNetwork()
1446     * and saveConfiguration().
1447     *
1448     * @param config the set of variables that describe the configuration,
1449     *            contained in a {@link WifiConfiguration} object.
1450     * @param listener for callbacks on success or failure. Can be null.
1451     * @throws IllegalStateException if the WifiManager instance needs to be
1452     * initialized again
1453     * @hide
1454     */
1455    public void forget(int netId, ActionListener listener) {
1456        if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
1457        validateChannel();
1458        sAsyncChannel.sendMessage(FORGET_NETWORK, netId, putListener(listener));
1459    }
1460
1461    /**
1462     * Disable network
1463     *
1464     * @param netId is the network Id
1465     * @param listener for callbacks on success or failure. Can be null.
1466     * @throws IllegalStateException if the WifiManager instance needs to be
1467     * initialized again
1468     * @hide
1469     */
1470    public void disable(int netId, ActionListener listener) {
1471        if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
1472        validateChannel();
1473        sAsyncChannel.sendMessage(DISABLE_NETWORK, netId, putListener(listener));
1474    }
1475
1476    /**
1477     * Start Wi-fi Protected Setup
1478     *
1479     * @param config WPS configuration
1480     * @param listener for callbacks on success or failure. Can be null.
1481     * @throws IllegalStateException if the WifiManager instance needs to be
1482     * initialized again
1483     * @hide
1484     */
1485    public void startWps(WpsInfo config, WpsListener listener) {
1486        if (config == null) throw new IllegalArgumentException("config cannot be null");
1487        validateChannel();
1488        sAsyncChannel.sendMessage(START_WPS, 0, putListener(listener), config);
1489    }
1490
1491    /**
1492     * Cancel any ongoing Wi-fi Protected Setup
1493     *
1494     * @param listener for callbacks on success or failure. Can be null.
1495     * @throws IllegalStateException if the WifiManager instance needs to be
1496     * initialized again
1497     * @hide
1498     */
1499    public void cancelWps(ActionListener listener) {
1500        validateChannel();
1501        sAsyncChannel.sendMessage(CANCEL_WPS, 0, putListener(listener));
1502    }
1503
1504    /**
1505     * Get a reference to WifiService handler. This is used by a client to establish
1506     * an AsyncChannel communication with WifiService
1507     *
1508     * @return Messenger pointing to the WifiService handler
1509     * @hide
1510     */
1511    public Messenger getWifiServiceMessenger() {
1512        try {
1513            return mService.getWifiServiceMessenger();
1514        } catch (RemoteException e) {
1515            return null;
1516        } catch (SecurityException e) {
1517            return null;
1518        }
1519    }
1520
1521    /**
1522     * Get a reference to WifiStateMachine handler.
1523     * @return Messenger pointing to the WifiService handler
1524     * @hide
1525     */
1526    public Messenger getWifiStateMachineMessenger() {
1527        try {
1528            return mService.getWifiStateMachineMessenger();
1529        } catch (RemoteException e) {
1530            return null;
1531        }
1532    }
1533
1534    /**
1535     * Returns the file in which IP and proxy configuration data is stored
1536     * @hide
1537     */
1538    public String getConfigFile() {
1539        try {
1540            return mService.getConfigFile();
1541        } catch (RemoteException e) {
1542            return null;
1543        }
1544    }
1545
1546    /**
1547     * Allows an application to keep the Wi-Fi radio awake.
1548     * Normally the Wi-Fi radio may turn off when the user has not used the device in a while.
1549     * Acquiring a WifiLock will keep the radio on until the lock is released.  Multiple
1550     * applications may hold WifiLocks, and the radio will only be allowed to turn off when no
1551     * WifiLocks are held in any application.
1552     * <p>
1553     * Before using a WifiLock, consider carefully if your application requires Wi-Fi access, or
1554     * could function over a mobile network, if available.  A program that needs to download large
1555     * files should hold a WifiLock to ensure that the download will complete, but a program whose
1556     * network usage is occasional or low-bandwidth should not hold a WifiLock to avoid adversely
1557     * affecting battery life.
1558     * <p>
1559     * Note that WifiLocks cannot override the user-level "Wi-Fi Enabled" setting, nor Airplane
1560     * Mode.  They simply keep the radio from turning off when Wi-Fi is already on but the device
1561     * is idle.
1562     * <p>
1563     * Any application using a WifiLock must request the {@code android.permission.WAKE_LOCK}
1564     * permission in an {@code &lt;uses-permission&gt;} element of the application's manifest.
1565     */
1566    public class WifiLock {
1567        private String mTag;
1568        private final IBinder mBinder;
1569        private int mRefCount;
1570        int mLockType;
1571        private boolean mRefCounted;
1572        private boolean mHeld;
1573        private WorkSource mWorkSource;
1574
1575        private WifiLock(int lockType, String tag) {
1576            mTag = tag;
1577            mLockType = lockType;
1578            mBinder = new Binder();
1579            mRefCount = 0;
1580            mRefCounted = true;
1581            mHeld = false;
1582        }
1583
1584        /**
1585         * Locks the Wi-Fi radio on until {@link #release} is called.
1586         *
1587         * If this WifiLock is reference-counted, each call to {@code acquire} will increment the
1588         * reference count, and the radio will remain locked as long as the reference count is
1589         * above zero.
1590         *
1591         * If this WifiLock is not reference-counted, the first call to {@code acquire} will lock
1592         * the radio, but subsequent calls will be ignored.  Only one call to {@link #release}
1593         * will be required, regardless of the number of times that {@code acquire} is called.
1594         */
1595        public void acquire() {
1596            synchronized (mBinder) {
1597                if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) {
1598                    try {
1599                        mService.acquireWifiLock(mBinder, mLockType, mTag, mWorkSource);
1600                        synchronized (WifiManager.this) {
1601                            if (mActiveLockCount >= MAX_ACTIVE_LOCKS) {
1602                                mService.releaseWifiLock(mBinder);
1603                                throw new UnsupportedOperationException(
1604                                            "Exceeded maximum number of wifi locks");
1605                            }
1606                            mActiveLockCount++;
1607                        }
1608                    } catch (RemoteException ignore) {
1609                    }
1610                    mHeld = true;
1611                }
1612            }
1613        }
1614
1615        /**
1616         * Unlocks the Wi-Fi radio, allowing it to turn off when the device is idle.
1617         *
1618         * If this WifiLock is reference-counted, each call to {@code release} will decrement the
1619         * reference count, and the radio will be unlocked only when the reference count reaches
1620         * zero.  If the reference count goes below zero (that is, if {@code release} is called
1621         * a greater number of times than {@link #acquire}), an exception is thrown.
1622         *
1623         * If this WifiLock is not reference-counted, the first call to {@code release} (after
1624         * the radio was locked using {@link #acquire}) will unlock the radio, and subsequent
1625         * calls will be ignored.
1626         */
1627        public void release() {
1628            synchronized (mBinder) {
1629                if (mRefCounted ? (--mRefCount == 0) : (mHeld)) {
1630                    try {
1631                        mService.releaseWifiLock(mBinder);
1632                        synchronized (WifiManager.this) {
1633                            mActiveLockCount--;
1634                        }
1635                    } catch (RemoteException ignore) {
1636                    }
1637                    mHeld = false;
1638                }
1639                if (mRefCount < 0) {
1640                    throw new RuntimeException("WifiLock under-locked " + mTag);
1641                }
1642            }
1643        }
1644
1645        /**
1646         * Controls whether this is a reference-counted or non-reference-counted WifiLock.
1647         *
1648         * Reference-counted WifiLocks keep track of the number of calls to {@link #acquire} and
1649         * {@link #release}, and only allow the radio to sleep when every call to {@link #acquire}
1650         * has been balanced with a call to {@link #release}.  Non-reference-counted WifiLocks
1651         * lock the radio whenever {@link #acquire} is called and it is unlocked, and unlock the
1652         * radio whenever {@link #release} is called and it is locked.
1653         *
1654         * @param refCounted true if this WifiLock should keep a reference count
1655         */
1656        public void setReferenceCounted(boolean refCounted) {
1657            mRefCounted = refCounted;
1658        }
1659
1660        /**
1661         * Checks whether this WifiLock is currently held.
1662         *
1663         * @return true if this WifiLock is held, false otherwise
1664         */
1665        public boolean isHeld() {
1666            synchronized (mBinder) {
1667                return mHeld;
1668            }
1669        }
1670
1671        public void setWorkSource(WorkSource ws) {
1672            synchronized (mBinder) {
1673                if (ws != null && ws.size() == 0) {
1674                    ws = null;
1675                }
1676                boolean changed = true;
1677                if (ws == null) {
1678                    mWorkSource = null;
1679                } else if (mWorkSource == null) {
1680                    changed = mWorkSource != null;
1681                    mWorkSource = new WorkSource(ws);
1682                } else {
1683                    changed = mWorkSource.diff(ws);
1684                    if (changed) {
1685                        mWorkSource.set(ws);
1686                    }
1687                }
1688                if (changed && mHeld) {
1689                    try {
1690                        mService.updateWifiLockWorkSource(mBinder, mWorkSource);
1691                    } catch (RemoteException e) {
1692                    }
1693                }
1694            }
1695        }
1696
1697        public String toString() {
1698            String s1, s2, s3;
1699            synchronized (mBinder) {
1700                s1 = Integer.toHexString(System.identityHashCode(this));
1701                s2 = mHeld ? "held; " : "";
1702                if (mRefCounted) {
1703                    s3 = "refcounted: refcount = " + mRefCount;
1704                } else {
1705                    s3 = "not refcounted";
1706                }
1707                return "WifiLock{ " + s1 + "; " + s2 + s3 + " }";
1708            }
1709        }
1710
1711        @Override
1712        protected void finalize() throws Throwable {
1713            super.finalize();
1714            synchronized (mBinder) {
1715                if (mHeld) {
1716                    try {
1717                        mService.releaseWifiLock(mBinder);
1718                        synchronized (WifiManager.this) {
1719                            mActiveLockCount--;
1720                        }
1721                    } catch (RemoteException ignore) {
1722                    }
1723                }
1724            }
1725        }
1726    }
1727
1728    /**
1729     * Creates a new WifiLock.
1730     *
1731     * @param lockType the type of lock to create. See {@link #WIFI_MODE_FULL},
1732     * {@link #WIFI_MODE_FULL_HIGH_PERF} and {@link #WIFI_MODE_SCAN_ONLY} for
1733     * descriptions of the types of Wi-Fi locks.
1734     * @param tag a tag for the WifiLock to identify it in debugging messages.  This string is
1735     *            never shown to the user under normal conditions, but should be descriptive
1736     *            enough to identify your application and the specific WifiLock within it, if it
1737     *            holds multiple WifiLocks.
1738     *
1739     * @return a new, unacquired WifiLock with the given tag.
1740     *
1741     * @see WifiLock
1742     */
1743    public WifiLock createWifiLock(int lockType, String tag) {
1744        return new WifiLock(lockType, tag);
1745    }
1746
1747    /**
1748     * Creates a new WifiLock.
1749     *
1750     * @param tag a tag for the WifiLock to identify it in debugging messages.  This string is
1751     *            never shown to the user under normal conditions, but should be descriptive
1752     *            enough to identify your application and the specific WifiLock within it, if it
1753     *            holds multiple WifiLocks.
1754     *
1755     * @return a new, unacquired WifiLock with the given tag.
1756     *
1757     * @see WifiLock
1758     */
1759    public WifiLock createWifiLock(String tag) {
1760        return new WifiLock(WIFI_MODE_FULL, tag);
1761    }
1762
1763
1764    /**
1765     * Create a new MulticastLock
1766     *
1767     * @param tag a tag for the MulticastLock to identify it in debugging
1768     *            messages.  This string is never shown to the user under
1769     *            normal conditions, but should be descriptive enough to
1770     *            identify your application and the specific MulticastLock
1771     *            within it, if it holds multiple MulticastLocks.
1772     *
1773     * @return a new, unacquired MulticastLock with the given tag.
1774     *
1775     * @see MulticastLock
1776     */
1777    public MulticastLock createMulticastLock(String tag) {
1778        return new MulticastLock(tag);
1779    }
1780
1781    /**
1782     * Allows an application to receive Wifi Multicast packets.
1783     * Normally the Wifi stack filters out packets not explicitly
1784     * addressed to this device.  Acquring a MulticastLock will
1785     * cause the stack to receive packets addressed to multicast
1786     * addresses.  Processing these extra packets can cause a noticable
1787     * battery drain and should be disabled when not needed.
1788     */
1789    public class MulticastLock {
1790        private String mTag;
1791        private final IBinder mBinder;
1792        private int mRefCount;
1793        private boolean mRefCounted;
1794        private boolean mHeld;
1795
1796        private MulticastLock(String tag) {
1797            mTag = tag;
1798            mBinder = new Binder();
1799            mRefCount = 0;
1800            mRefCounted = true;
1801            mHeld = false;
1802        }
1803
1804        /**
1805         * Locks Wifi Multicast on until {@link #release} is called.
1806         *
1807         * If this MulticastLock is reference-counted each call to
1808         * {@code acquire} will increment the reference count, and the
1809         * wifi interface will receive multicast packets as long as the
1810         * reference count is above zero.
1811         *
1812         * If this MulticastLock is not reference-counted, the first call to
1813         * {@code acquire} will turn on the multicast packets, but subsequent
1814         * calls will be ignored.  Only one call to {@link #release} will
1815         * be required, regardless of the number of times that {@code acquire}
1816         * is called.
1817         *
1818         * Note that other applications may also lock Wifi Multicast on.
1819         * Only they can relinquish their lock.
1820         *
1821         * Also note that applications cannot leave Multicast locked on.
1822         * When an app exits or crashes, any Multicast locks will be released.
1823         */
1824        public void acquire() {
1825            synchronized (mBinder) {
1826                if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) {
1827                    try {
1828                        mService.acquireMulticastLock(mBinder, mTag);
1829                        synchronized (WifiManager.this) {
1830                            if (mActiveLockCount >= MAX_ACTIVE_LOCKS) {
1831                                mService.releaseMulticastLock();
1832                                throw new UnsupportedOperationException(
1833                                        "Exceeded maximum number of wifi locks");
1834                            }
1835                            mActiveLockCount++;
1836                        }
1837                    } catch (RemoteException ignore) {
1838                    }
1839                    mHeld = true;
1840                }
1841            }
1842        }
1843
1844        /**
1845         * Unlocks Wifi Multicast, restoring the filter of packets
1846         * not addressed specifically to this device and saving power.
1847         *
1848         * If this MulticastLock is reference-counted, each call to
1849         * {@code release} will decrement the reference count, and the
1850         * multicast packets will only stop being received when the reference
1851         * count reaches zero.  If the reference count goes below zero (that
1852         * is, if {@code release} is called a greater number of times than
1853         * {@link #acquire}), an exception is thrown.
1854         *
1855         * If this MulticastLock is not reference-counted, the first call to
1856         * {@code release} (after the radio was multicast locked using
1857         * {@link #acquire}) will unlock the multicast, and subsequent calls
1858         * will be ignored.
1859         *
1860         * Note that if any other Wifi Multicast Locks are still outstanding
1861         * this {@code release} call will not have an immediate effect.  Only
1862         * when all applications have released all their Multicast Locks will
1863         * the Multicast filter be turned back on.
1864         *
1865         * Also note that when an app exits or crashes all of its Multicast
1866         * Locks will be automatically released.
1867         */
1868        public void release() {
1869            synchronized (mBinder) {
1870                if (mRefCounted ? (--mRefCount == 0) : (mHeld)) {
1871                    try {
1872                        mService.releaseMulticastLock();
1873                        synchronized (WifiManager.this) {
1874                            mActiveLockCount--;
1875                        }
1876                    } catch (RemoteException ignore) {
1877                    }
1878                    mHeld = false;
1879                }
1880                if (mRefCount < 0) {
1881                    throw new RuntimeException("MulticastLock under-locked "
1882                            + mTag);
1883                }
1884            }
1885        }
1886
1887        /**
1888         * Controls whether this is a reference-counted or non-reference-
1889         * counted MulticastLock.
1890         *
1891         * Reference-counted MulticastLocks keep track of the number of calls
1892         * to {@link #acquire} and {@link #release}, and only stop the
1893         * reception of multicast packets when every call to {@link #acquire}
1894         * has been balanced with a call to {@link #release}.  Non-reference-
1895         * counted MulticastLocks allow the reception of multicast packets
1896         * whenever {@link #acquire} is called and stop accepting multicast
1897         * packets whenever {@link #release} is called.
1898         *
1899         * @param refCounted true if this MulticastLock should keep a reference
1900         * count
1901         */
1902        public void setReferenceCounted(boolean refCounted) {
1903            mRefCounted = refCounted;
1904        }
1905
1906        /**
1907         * Checks whether this MulticastLock is currently held.
1908         *
1909         * @return true if this MulticastLock is held, false otherwise
1910         */
1911        public boolean isHeld() {
1912            synchronized (mBinder) {
1913                return mHeld;
1914            }
1915        }
1916
1917        public String toString() {
1918            String s1, s2, s3;
1919            synchronized (mBinder) {
1920                s1 = Integer.toHexString(System.identityHashCode(this));
1921                s2 = mHeld ? "held; " : "";
1922                if (mRefCounted) {
1923                    s3 = "refcounted: refcount = " + mRefCount;
1924                } else {
1925                    s3 = "not refcounted";
1926                }
1927                return "MulticastLock{ " + s1 + "; " + s2 + s3 + " }";
1928            }
1929        }
1930
1931        @Override
1932        protected void finalize() throws Throwable {
1933            super.finalize();
1934            setReferenceCounted(false);
1935            release();
1936        }
1937    }
1938
1939    /**
1940     * Check multicast filter status.
1941     *
1942     * @return true if multicast packets are allowed.
1943     *
1944     * @hide pending API council approval
1945     */
1946    public boolean isMulticastEnabled() {
1947        try {
1948            return mService.isMulticastEnabled();
1949        } catch (RemoteException e) {
1950            return false;
1951        }
1952    }
1953
1954    /**
1955     * Initialize the multicast filtering to 'on'
1956     * @hide no intent to publish
1957     */
1958    public boolean initializeMulticastFiltering() {
1959        try {
1960            mService.initializeMulticastFiltering();
1961            return true;
1962        } catch (RemoteException e) {
1963             return false;
1964        }
1965    }
1966
1967    /** @hide */
1968    public void captivePortalCheckComplete() {
1969        try {
1970            mService.captivePortalCheckComplete();
1971        } catch (RemoteException e) {}
1972    }
1973
1974    protected void finalize() throws Throwable {
1975        try {
1976            synchronized (sThreadRefLock) {
1977                if (--sThreadRefCount == 0 && sAsyncChannel != null) {
1978                    sAsyncChannel.disconnect();
1979                }
1980            }
1981        } finally {
1982            super.finalize();
1983        }
1984    }
1985}
1986