WifiManager.java revision c808a1955f7571108e8c22502897ed82c69a7c3b
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
1149    /**
1150     * Passed with {@link ActionListener#onFailure}.
1151     * Indicates that the operation failed due to an internal error.
1152     * @hide
1153     */
1154    public static final int ERROR                       = 0;
1155
1156    /**
1157     * Passed with {@link ActionListener#onFailure}.
1158     * Indicates that the operation is already in progress
1159     * @hide
1160     */
1161    public static final int IN_PROGRESS                 = 1;
1162
1163    /**
1164     * Passed with {@link ActionListener#onFailure}.
1165     * Indicates that the operation failed because the framework is busy and
1166     * unable to service the request
1167     * @hide
1168     */
1169    public static final int BUSY                        = 2;
1170
1171    /* WPS specific errors */
1172    /** WPS overlap detected {@hide} */
1173    public static final int WPS_OVERLAP_ERROR           = 3;
1174    /** WEP on WPS is prohibited {@hide} */
1175    public static final int WPS_WEP_PROHIBITED          = 4;
1176    /** TKIP only prohibited {@hide} */
1177    public static final int WPS_TKIP_ONLY_PROHIBITED    = 5;
1178    /** Authentication failure on WPS {@hide} */
1179    public static final int WPS_AUTH_FAILURE            = 6;
1180    /** WPS timed out {@hide} */
1181    public static final int WPS_TIMED_OUT               = 7;
1182
1183    /** Interface for callback invocation on an application action {@hide} */
1184    public interface ActionListener {
1185        /** The operation succeeded */
1186        public void onSuccess();
1187        /**
1188         * The operation failed
1189         * @param reason The reason for failure could be one of
1190         * {@link #ERROR}, {@link #IN_PROGRESS} or {@link #BUSY}
1191         */
1192        public void onFailure(int reason);
1193    }
1194
1195    /** Interface for callback invocation on a start WPS action {@hide} */
1196    public interface WpsListener {
1197        /** WPS start succeeded */
1198        public void onStartSuccess(String pin);
1199
1200        /** WPS operation completed succesfully */
1201        public void onCompletion();
1202
1203        /**
1204         * WPS operation failed
1205         * @param reason The reason for failure could be one of
1206         * {@link #IN_PROGRESS}, {@link #WPS_OVERLAP_ERROR},{@link #ERROR} or {@link #BUSY}
1207         */
1208        public void onFailure(int reason);
1209    }
1210
1211    /** Interface for callback invocation on a TX packet count poll action {@hide} */
1212    public interface TxPacketCountListener {
1213        /**
1214         * The operation succeeded
1215         * @param count TX packet counter
1216         */
1217        public void onSuccess(int count);
1218        /**
1219         * The operation failed
1220         * @param reason The reason for failure could be one of
1221         * {@link #ERROR}, {@link #IN_PROGRESS} or {@link #BUSY}
1222         */
1223        public void onFailure(int reason);
1224    }
1225
1226    private static class ServiceHandler extends Handler {
1227        ServiceHandler(Looper looper) {
1228            super(looper);
1229        }
1230
1231        @Override
1232        public void handleMessage(Message message) {
1233            Object listener = removeListener(message.arg2);
1234            switch (message.what) {
1235                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
1236                    if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1237                        sAsyncChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
1238                    } else {
1239                        Log.e(TAG, "Failed to set up channel connection");
1240                        // This will cause all further async API calls on the WifiManager
1241                        // to fail and throw an exception
1242                        sAsyncChannel = null;
1243                    }
1244                    sConnected.countDown();
1245                    break;
1246                case AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED:
1247                    // Ignore
1248                    break;
1249                case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
1250                    Log.e(TAG, "Channel connection lost");
1251                    // This will cause all further async API calls on the WifiManager
1252                    // to fail and throw an exception
1253                    sAsyncChannel = null;
1254                    getLooper().quit();
1255                    break;
1256                    /* ActionListeners grouped together */
1257                case WifiManager.CONNECT_NETWORK_FAILED:
1258                case WifiManager.FORGET_NETWORK_FAILED:
1259                case WifiManager.SAVE_NETWORK_FAILED:
1260                case WifiManager.CANCEL_WPS_FAILED:
1261                case WifiManager.DISABLE_NETWORK_FAILED:
1262                    if (listener != null) {
1263                        ((ActionListener) listener).onFailure(message.arg1);
1264                    }
1265                    break;
1266                    /* ActionListeners grouped together */
1267                case WifiManager.CONNECT_NETWORK_SUCCEEDED:
1268                case WifiManager.FORGET_NETWORK_SUCCEEDED:
1269                case WifiManager.SAVE_NETWORK_SUCCEEDED:
1270                case WifiManager.CANCEL_WPS_SUCCEDED:
1271                case WifiManager.DISABLE_NETWORK_SUCCEEDED:
1272                    if (listener != null) {
1273                        ((ActionListener) listener).onSuccess();
1274                    }
1275                    break;
1276                case WifiManager.START_WPS_SUCCEEDED:
1277                    if (listener != null) {
1278                        WpsResult result = (WpsResult) message.obj;
1279                        ((WpsListener) listener).onStartSuccess(result.pin);
1280                        //Listener needs to stay until completion or failure
1281                        synchronized(sListenerMapLock) {
1282                            sListenerMap.put(message.arg2, listener);
1283                        }
1284                    }
1285                    break;
1286                case WifiManager.WPS_COMPLETED:
1287                    if (listener != null) {
1288                        ((WpsListener) listener).onCompletion();
1289                    }
1290                    break;
1291                case WifiManager.WPS_FAILED:
1292                    if (listener != null) {
1293                        ((WpsListener) listener).onFailure(message.arg1);
1294                    }
1295                    break;
1296                case WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED:
1297                    if (listener != null) {
1298                        RssiPacketCountInfo info = (RssiPacketCountInfo) message.obj;
1299                        if (info != null)
1300                            ((TxPacketCountListener) listener).onSuccess(info.txgood + info.txbad);
1301                        else
1302                            ((TxPacketCountListener) listener).onFailure(ERROR);
1303                    }
1304                    break;
1305                case WifiManager.RSSI_PKTCNT_FETCH_FAILED:
1306                    if (listener != null) {
1307                        ((TxPacketCountListener) listener).onFailure(message.arg1);
1308                    }
1309                    break;
1310                default:
1311                    //ignore
1312                    break;
1313            }
1314        }
1315    }
1316
1317    private static int putListener(Object listener) {
1318        if (listener == null) return INVALID_KEY;
1319        int key;
1320        synchronized (sListenerMapLock) {
1321            do {
1322                key = sListenerKey++;
1323            } while (key == INVALID_KEY);
1324            sListenerMap.put(key, listener);
1325        }
1326        return key;
1327    }
1328
1329    private static Object removeListener(int key) {
1330        if (key == INVALID_KEY) return null;
1331        synchronized (sListenerMapLock) {
1332            Object listener = sListenerMap.get(key);
1333            sListenerMap.remove(key);
1334            return listener;
1335        }
1336    }
1337
1338    private void init() {
1339        synchronized (sThreadRefLock) {
1340            if (++sThreadRefCount == 1) {
1341                Messenger messenger = getWifiServiceMessenger();
1342                if (messenger == null) {
1343                    sAsyncChannel = null;
1344                    return;
1345                }
1346
1347                sHandlerThread = new HandlerThread("WifiManager");
1348                sAsyncChannel = new AsyncChannel();
1349                sConnected = new CountDownLatch(1);
1350
1351                sHandlerThread.start();
1352                Handler handler = new ServiceHandler(sHandlerThread.getLooper());
1353                sAsyncChannel.connect(mContext, handler, messenger);
1354                try {
1355                    sConnected.await();
1356                } catch (InterruptedException e) {
1357                    Log.e(TAG, "interrupted wait at init");
1358                }
1359            }
1360        }
1361    }
1362
1363    private void validateChannel() {
1364        if (sAsyncChannel == null) throw new IllegalStateException(
1365                "No permission to access and change wifi or a bad initialization");
1366    }
1367
1368    /**
1369     * Connect to a network with the given configuration. The network also
1370     * gets added to the supplicant configuration.
1371     *
1372     * For a new network, this function is used instead of a
1373     * sequence of addNetwork(), enableNetwork(), saveConfiguration() and
1374     * reconnect()
1375     *
1376     * @param config the set of variables that describe the configuration,
1377     *            contained in a {@link WifiConfiguration} object.
1378     * @param listener for callbacks on success or failure. Can be null.
1379     * @throws IllegalStateException if the WifiManager instance needs to be
1380     * initialized again
1381     *
1382     * @hide
1383     */
1384    public void connect(WifiConfiguration config, ActionListener listener) {
1385        if (config == null) throw new IllegalArgumentException("config cannot be null");
1386        validateChannel();
1387        // Use INVALID_NETWORK_ID for arg1 when passing a config object
1388        // arg1 is used to pass network id when the network already exists
1389        sAsyncChannel.sendMessage(CONNECT_NETWORK, WifiConfiguration.INVALID_NETWORK_ID,
1390                putListener(listener), config);
1391    }
1392
1393    /**
1394     * Connect to a network with the given networkId.
1395     *
1396     * This function is used instead of a enableNetwork(), saveConfiguration() and
1397     * reconnect()
1398     *
1399     * @param networkId the network id identifiying the network in the
1400     *                supplicant configuration list
1401     * @param listener for callbacks on success or failure. Can be null.
1402     * @throws IllegalStateException if the WifiManager instance needs to be
1403     * initialized again
1404     * @hide
1405     */
1406    public void connect(int networkId, ActionListener listener) {
1407        if (networkId < 0) throw new IllegalArgumentException("Network id cannot be negative");
1408        validateChannel();
1409        sAsyncChannel.sendMessage(CONNECT_NETWORK, networkId, putListener(listener));
1410    }
1411
1412    /**
1413     * Save the given network in the supplicant config. If the network already
1414     * exists, the configuration is updated. A new network is enabled
1415     * by default.
1416     *
1417     * For a new network, this function is used instead of a
1418     * sequence of addNetwork(), enableNetwork() and saveConfiguration().
1419     *
1420     * For an existing network, it accomplishes the task of updateNetwork()
1421     * and saveConfiguration()
1422     *
1423     * @param config the set of variables that describe the configuration,
1424     *            contained in a {@link WifiConfiguration} object.
1425     * @param listener for callbacks on success or failure. Can be null.
1426     * @throws IllegalStateException if the WifiManager instance needs to be
1427     * initialized again
1428     * @hide
1429     */
1430    public void save(WifiConfiguration config, ActionListener listener) {
1431        if (config == null) throw new IllegalArgumentException("config cannot be null");
1432        validateChannel();
1433        sAsyncChannel.sendMessage(SAVE_NETWORK, 0, putListener(listener), config);
1434    }
1435
1436    /**
1437     * Delete the network in the supplicant config.
1438     *
1439     * This function is used instead of a sequence of removeNetwork()
1440     * and saveConfiguration().
1441     *
1442     * @param config the set of variables that describe the configuration,
1443     *            contained in a {@link WifiConfiguration} object.
1444     * @param listener for callbacks on success or failure. Can be null.
1445     * @throws IllegalStateException if the WifiManager instance needs to be
1446     * initialized again
1447     * @hide
1448     */
1449    public void forget(int netId, ActionListener listener) {
1450        if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
1451        validateChannel();
1452        sAsyncChannel.sendMessage(FORGET_NETWORK, netId, putListener(listener));
1453    }
1454
1455    /**
1456     * Disable network
1457     *
1458     * @param netId is the network Id
1459     * @param listener for callbacks on success or failure. Can be null.
1460     * @throws IllegalStateException if the WifiManager instance needs to be
1461     * initialized again
1462     * @hide
1463     */
1464    public void disable(int netId, ActionListener listener) {
1465        if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
1466        validateChannel();
1467        sAsyncChannel.sendMessage(DISABLE_NETWORK, netId, putListener(listener));
1468    }
1469
1470    /**
1471     * Start Wi-fi Protected Setup
1472     *
1473     * @param config WPS configuration
1474     * @param listener for callbacks on success or failure. Can be null.
1475     * @throws IllegalStateException if the WifiManager instance needs to be
1476     * initialized again
1477     * @hide
1478     */
1479    public void startWps(WpsInfo config, WpsListener listener) {
1480        if (config == null) throw new IllegalArgumentException("config cannot be null");
1481        validateChannel();
1482        sAsyncChannel.sendMessage(START_WPS, 0, putListener(listener), config);
1483    }
1484
1485    /**
1486     * Cancel any ongoing Wi-fi Protected Setup
1487     *
1488     * @param listener for callbacks on success or failure. Can be null.
1489     * @throws IllegalStateException if the WifiManager instance needs to be
1490     * initialized again
1491     * @hide
1492     */
1493    public void cancelWps(ActionListener listener) {
1494        validateChannel();
1495        sAsyncChannel.sendMessage(CANCEL_WPS, 0, putListener(listener));
1496    }
1497
1498    /**
1499     * Get a reference to WifiService handler. This is used by a client to establish
1500     * an AsyncChannel communication with WifiService
1501     *
1502     * @return Messenger pointing to the WifiService handler
1503     * @hide
1504     */
1505    public Messenger getWifiServiceMessenger() {
1506        try {
1507            return mService.getWifiServiceMessenger();
1508        } catch (RemoteException e) {
1509            return null;
1510        } catch (SecurityException e) {
1511            return null;
1512        }
1513    }
1514
1515    /**
1516     * Get a reference to WifiStateMachine handler.
1517     * @return Messenger pointing to the WifiService handler
1518     * @hide
1519     */
1520    public Messenger getWifiStateMachineMessenger() {
1521        try {
1522            return mService.getWifiStateMachineMessenger();
1523        } catch (RemoteException e) {
1524            return null;
1525        }
1526    }
1527
1528    /**
1529     * Returns the file in which IP and proxy configuration data is stored
1530     * @hide
1531     */
1532    public String getConfigFile() {
1533        try {
1534            return mService.getConfigFile();
1535        } catch (RemoteException e) {
1536            return null;
1537        }
1538    }
1539
1540    /**
1541     * Allows an application to keep the Wi-Fi radio awake.
1542     * Normally the Wi-Fi radio may turn off when the user has not used the device in a while.
1543     * Acquiring a WifiLock will keep the radio on until the lock is released.  Multiple
1544     * applications may hold WifiLocks, and the radio will only be allowed to turn off when no
1545     * WifiLocks are held in any application.
1546     * <p>
1547     * Before using a WifiLock, consider carefully if your application requires Wi-Fi access, or
1548     * could function over a mobile network, if available.  A program that needs to download large
1549     * files should hold a WifiLock to ensure that the download will complete, but a program whose
1550     * network usage is occasional or low-bandwidth should not hold a WifiLock to avoid adversely
1551     * affecting battery life.
1552     * <p>
1553     * Note that WifiLocks cannot override the user-level "Wi-Fi Enabled" setting, nor Airplane
1554     * Mode.  They simply keep the radio from turning off when Wi-Fi is already on but the device
1555     * is idle.
1556     * <p>
1557     * Any application using a WifiLock must request the {@code android.permission.WAKE_LOCK}
1558     * permission in an {@code &lt;uses-permission&gt;} element of the application's manifest.
1559     */
1560    public class WifiLock {
1561        private String mTag;
1562        private final IBinder mBinder;
1563        private int mRefCount;
1564        int mLockType;
1565        private boolean mRefCounted;
1566        private boolean mHeld;
1567        private WorkSource mWorkSource;
1568
1569        private WifiLock(int lockType, String tag) {
1570            mTag = tag;
1571            mLockType = lockType;
1572            mBinder = new Binder();
1573            mRefCount = 0;
1574            mRefCounted = true;
1575            mHeld = false;
1576        }
1577
1578        /**
1579         * Locks the Wi-Fi radio on until {@link #release} is called.
1580         *
1581         * If this WifiLock is reference-counted, each call to {@code acquire} will increment the
1582         * reference count, and the radio will remain locked as long as the reference count is
1583         * above zero.
1584         *
1585         * If this WifiLock is not reference-counted, the first call to {@code acquire} will lock
1586         * the radio, but subsequent calls will be ignored.  Only one call to {@link #release}
1587         * will be required, regardless of the number of times that {@code acquire} is called.
1588         */
1589        public void acquire() {
1590            synchronized (mBinder) {
1591                if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) {
1592                    try {
1593                        mService.acquireWifiLock(mBinder, mLockType, mTag, mWorkSource);
1594                        synchronized (WifiManager.this) {
1595                            if (mActiveLockCount >= MAX_ACTIVE_LOCKS) {
1596                                mService.releaseWifiLock(mBinder);
1597                                throw new UnsupportedOperationException(
1598                                            "Exceeded maximum number of wifi locks");
1599                            }
1600                            mActiveLockCount++;
1601                        }
1602                    } catch (RemoteException ignore) {
1603                    }
1604                    mHeld = true;
1605                }
1606            }
1607        }
1608
1609        /**
1610         * Unlocks the Wi-Fi radio, allowing it to turn off when the device is idle.
1611         *
1612         * If this WifiLock is reference-counted, each call to {@code release} will decrement the
1613         * reference count, and the radio will be unlocked only when the reference count reaches
1614         * zero.  If the reference count goes below zero (that is, if {@code release} is called
1615         * a greater number of times than {@link #acquire}), an exception is thrown.
1616         *
1617         * If this WifiLock is not reference-counted, the first call to {@code release} (after
1618         * the radio was locked using {@link #acquire}) will unlock the radio, and subsequent
1619         * calls will be ignored.
1620         */
1621        public void release() {
1622            synchronized (mBinder) {
1623                if (mRefCounted ? (--mRefCount == 0) : (mHeld)) {
1624                    try {
1625                        mService.releaseWifiLock(mBinder);
1626                        synchronized (WifiManager.this) {
1627                            mActiveLockCount--;
1628                        }
1629                    } catch (RemoteException ignore) {
1630                    }
1631                    mHeld = false;
1632                }
1633                if (mRefCount < 0) {
1634                    throw new RuntimeException("WifiLock under-locked " + mTag);
1635                }
1636            }
1637        }
1638
1639        /**
1640         * Controls whether this is a reference-counted or non-reference-counted WifiLock.
1641         *
1642         * Reference-counted WifiLocks keep track of the number of calls to {@link #acquire} and
1643         * {@link #release}, and only allow the radio to sleep when every call to {@link #acquire}
1644         * has been balanced with a call to {@link #release}.  Non-reference-counted WifiLocks
1645         * lock the radio whenever {@link #acquire} is called and it is unlocked, and unlock the
1646         * radio whenever {@link #release} is called and it is locked.
1647         *
1648         * @param refCounted true if this WifiLock should keep a reference count
1649         */
1650        public void setReferenceCounted(boolean refCounted) {
1651            mRefCounted = refCounted;
1652        }
1653
1654        /**
1655         * Checks whether this WifiLock is currently held.
1656         *
1657         * @return true if this WifiLock is held, false otherwise
1658         */
1659        public boolean isHeld() {
1660            synchronized (mBinder) {
1661                return mHeld;
1662            }
1663        }
1664
1665        public void setWorkSource(WorkSource ws) {
1666            synchronized (mBinder) {
1667                if (ws != null && ws.size() == 0) {
1668                    ws = null;
1669                }
1670                boolean changed = true;
1671                if (ws == null) {
1672                    mWorkSource = null;
1673                } else if (mWorkSource == null) {
1674                    changed = mWorkSource != null;
1675                    mWorkSource = new WorkSource(ws);
1676                } else {
1677                    changed = mWorkSource.diff(ws);
1678                    if (changed) {
1679                        mWorkSource.set(ws);
1680                    }
1681                }
1682                if (changed && mHeld) {
1683                    try {
1684                        mService.updateWifiLockWorkSource(mBinder, mWorkSource);
1685                    } catch (RemoteException e) {
1686                    }
1687                }
1688            }
1689        }
1690
1691        public String toString() {
1692            String s1, s2, s3;
1693            synchronized (mBinder) {
1694                s1 = Integer.toHexString(System.identityHashCode(this));
1695                s2 = mHeld ? "held; " : "";
1696                if (mRefCounted) {
1697                    s3 = "refcounted: refcount = " + mRefCount;
1698                } else {
1699                    s3 = "not refcounted";
1700                }
1701                return "WifiLock{ " + s1 + "; " + s2 + s3 + " }";
1702            }
1703        }
1704
1705        @Override
1706        protected void finalize() throws Throwable {
1707            super.finalize();
1708            synchronized (mBinder) {
1709                if (mHeld) {
1710                    try {
1711                        mService.releaseWifiLock(mBinder);
1712                        synchronized (WifiManager.this) {
1713                            mActiveLockCount--;
1714                        }
1715                    } catch (RemoteException ignore) {
1716                    }
1717                }
1718            }
1719        }
1720    }
1721
1722    /**
1723     * Creates a new WifiLock.
1724     *
1725     * @param lockType the type of lock to create. See {@link #WIFI_MODE_FULL},
1726     * {@link #WIFI_MODE_FULL_HIGH_PERF} and {@link #WIFI_MODE_SCAN_ONLY} for
1727     * descriptions of the types of Wi-Fi locks.
1728     * @param tag a tag for the WifiLock to identify it in debugging messages.  This string is
1729     *            never shown to the user under normal conditions, but should be descriptive
1730     *            enough to identify your application and the specific WifiLock within it, if it
1731     *            holds multiple WifiLocks.
1732     *
1733     * @return a new, unacquired WifiLock with the given tag.
1734     *
1735     * @see WifiLock
1736     */
1737    public WifiLock createWifiLock(int lockType, String tag) {
1738        return new WifiLock(lockType, tag);
1739    }
1740
1741    /**
1742     * Creates a new WifiLock.
1743     *
1744     * @param tag a tag for the WifiLock to identify it in debugging messages.  This string is
1745     *            never shown to the user under normal conditions, but should be descriptive
1746     *            enough to identify your application and the specific WifiLock within it, if it
1747     *            holds multiple WifiLocks.
1748     *
1749     * @return a new, unacquired WifiLock with the given tag.
1750     *
1751     * @see WifiLock
1752     */
1753    public WifiLock createWifiLock(String tag) {
1754        return new WifiLock(WIFI_MODE_FULL, tag);
1755    }
1756
1757
1758    /**
1759     * Create a new MulticastLock
1760     *
1761     * @param tag a tag for the MulticastLock to identify it in debugging
1762     *            messages.  This string is never shown to the user under
1763     *            normal conditions, but should be descriptive enough to
1764     *            identify your application and the specific MulticastLock
1765     *            within it, if it holds multiple MulticastLocks.
1766     *
1767     * @return a new, unacquired MulticastLock with the given tag.
1768     *
1769     * @see MulticastLock
1770     */
1771    public MulticastLock createMulticastLock(String tag) {
1772        return new MulticastLock(tag);
1773    }
1774
1775    /**
1776     * Allows an application to receive Wifi Multicast packets.
1777     * Normally the Wifi stack filters out packets not explicitly
1778     * addressed to this device.  Acquring a MulticastLock will
1779     * cause the stack to receive packets addressed to multicast
1780     * addresses.  Processing these extra packets can cause a noticable
1781     * battery drain and should be disabled when not needed.
1782     */
1783    public class MulticastLock {
1784        private String mTag;
1785        private final IBinder mBinder;
1786        private int mRefCount;
1787        private boolean mRefCounted;
1788        private boolean mHeld;
1789
1790        private MulticastLock(String tag) {
1791            mTag = tag;
1792            mBinder = new Binder();
1793            mRefCount = 0;
1794            mRefCounted = true;
1795            mHeld = false;
1796        }
1797
1798        /**
1799         * Locks Wifi Multicast on until {@link #release} is called.
1800         *
1801         * If this MulticastLock is reference-counted each call to
1802         * {@code acquire} will increment the reference count, and the
1803         * wifi interface will receive multicast packets as long as the
1804         * reference count is above zero.
1805         *
1806         * If this MulticastLock is not reference-counted, the first call to
1807         * {@code acquire} will turn on the multicast packets, but subsequent
1808         * calls will be ignored.  Only one call to {@link #release} will
1809         * be required, regardless of the number of times that {@code acquire}
1810         * is called.
1811         *
1812         * Note that other applications may also lock Wifi Multicast on.
1813         * Only they can relinquish their lock.
1814         *
1815         * Also note that applications cannot leave Multicast locked on.
1816         * When an app exits or crashes, any Multicast locks will be released.
1817         */
1818        public void acquire() {
1819            synchronized (mBinder) {
1820                if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) {
1821                    try {
1822                        mService.acquireMulticastLock(mBinder, mTag);
1823                        synchronized (WifiManager.this) {
1824                            if (mActiveLockCount >= MAX_ACTIVE_LOCKS) {
1825                                mService.releaseMulticastLock();
1826                                throw new UnsupportedOperationException(
1827                                        "Exceeded maximum number of wifi locks");
1828                            }
1829                            mActiveLockCount++;
1830                        }
1831                    } catch (RemoteException ignore) {
1832                    }
1833                    mHeld = true;
1834                }
1835            }
1836        }
1837
1838        /**
1839         * Unlocks Wifi Multicast, restoring the filter of packets
1840         * not addressed specifically to this device and saving power.
1841         *
1842         * If this MulticastLock is reference-counted, each call to
1843         * {@code release} will decrement the reference count, and the
1844         * multicast packets will only stop being received when the reference
1845         * count reaches zero.  If the reference count goes below zero (that
1846         * is, if {@code release} is called a greater number of times than
1847         * {@link #acquire}), an exception is thrown.
1848         *
1849         * If this MulticastLock is not reference-counted, the first call to
1850         * {@code release} (after the radio was multicast locked using
1851         * {@link #acquire}) will unlock the multicast, and subsequent calls
1852         * will be ignored.
1853         *
1854         * Note that if any other Wifi Multicast Locks are still outstanding
1855         * this {@code release} call will not have an immediate effect.  Only
1856         * when all applications have released all their Multicast Locks will
1857         * the Multicast filter be turned back on.
1858         *
1859         * Also note that when an app exits or crashes all of its Multicast
1860         * Locks will be automatically released.
1861         */
1862        public void release() {
1863            synchronized (mBinder) {
1864                if (mRefCounted ? (--mRefCount == 0) : (mHeld)) {
1865                    try {
1866                        mService.releaseMulticastLock();
1867                        synchronized (WifiManager.this) {
1868                            mActiveLockCount--;
1869                        }
1870                    } catch (RemoteException ignore) {
1871                    }
1872                    mHeld = false;
1873                }
1874                if (mRefCount < 0) {
1875                    throw new RuntimeException("MulticastLock under-locked "
1876                            + mTag);
1877                }
1878            }
1879        }
1880
1881        /**
1882         * Controls whether this is a reference-counted or non-reference-
1883         * counted MulticastLock.
1884         *
1885         * Reference-counted MulticastLocks keep track of the number of calls
1886         * to {@link #acquire} and {@link #release}, and only stop the
1887         * reception of multicast packets when every call to {@link #acquire}
1888         * has been balanced with a call to {@link #release}.  Non-reference-
1889         * counted MulticastLocks allow the reception of multicast packets
1890         * whenever {@link #acquire} is called and stop accepting multicast
1891         * packets whenever {@link #release} is called.
1892         *
1893         * @param refCounted true if this MulticastLock should keep a reference
1894         * count
1895         */
1896        public void setReferenceCounted(boolean refCounted) {
1897            mRefCounted = refCounted;
1898        }
1899
1900        /**
1901         * Checks whether this MulticastLock is currently held.
1902         *
1903         * @return true if this MulticastLock is held, false otherwise
1904         */
1905        public boolean isHeld() {
1906            synchronized (mBinder) {
1907                return mHeld;
1908            }
1909        }
1910
1911        public String toString() {
1912            String s1, s2, s3;
1913            synchronized (mBinder) {
1914                s1 = Integer.toHexString(System.identityHashCode(this));
1915                s2 = mHeld ? "held; " : "";
1916                if (mRefCounted) {
1917                    s3 = "refcounted: refcount = " + mRefCount;
1918                } else {
1919                    s3 = "not refcounted";
1920                }
1921                return "MulticastLock{ " + s1 + "; " + s2 + s3 + " }";
1922            }
1923        }
1924
1925        @Override
1926        protected void finalize() throws Throwable {
1927            super.finalize();
1928            setReferenceCounted(false);
1929            release();
1930        }
1931    }
1932
1933    /**
1934     * Check multicast filter status.
1935     *
1936     * @return true if multicast packets are allowed.
1937     *
1938     * @hide pending API council approval
1939     */
1940    public boolean isMulticastEnabled() {
1941        try {
1942            return mService.isMulticastEnabled();
1943        } catch (RemoteException e) {
1944            return false;
1945        }
1946    }
1947
1948    /**
1949     * Initialize the multicast filtering to 'on'
1950     * @hide no intent to publish
1951     */
1952    public boolean initializeMulticastFiltering() {
1953        try {
1954            mService.initializeMulticastFiltering();
1955            return true;
1956        } catch (RemoteException e) {
1957             return false;
1958        }
1959    }
1960
1961    /** @hide */
1962    public void captivePortalCheckComplete() {
1963        try {
1964            mService.captivePortalCheckComplete();
1965        } catch (RemoteException e) {}
1966    }
1967
1968    protected void finalize() throws Throwable {
1969        try {
1970            synchronized (sThreadRefLock) {
1971                if (--sThreadRefCount == 0 && sAsyncChannel != null) {
1972                    sAsyncChannel.disconnect();
1973                }
1974            }
1975        } finally {
1976            super.finalize();
1977        }
1978    }
1979}
1980