blob: 54e77f02223807608f4af50f9d4954d39fefcb4f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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 com.android.server;
18
19import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
20import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING;
21import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
22import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
23import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
24
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.app.AlarmManager;
26import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070027import android.bluetooth.BluetoothA2dp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.BroadcastReceiver;
29import android.content.ContentResolver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.pm.PackageManager;
34import android.net.wifi.IWifiManager;
35import android.net.wifi.WifiInfo;
36import android.net.wifi.WifiManager;
37import android.net.wifi.WifiNative;
38import android.net.wifi.WifiStateTracker;
39import android.net.wifi.ScanResult;
40import android.net.wifi.WifiConfiguration;
41import android.net.NetworkStateTracker;
42import android.net.DhcpInfo;
43import android.os.Binder;
44import android.os.Handler;
45import android.os.HandlerThread;
46import android.os.IBinder;
47import android.os.Looper;
48import android.os.Message;
49import android.os.PowerManager;
Dianne Hackborn617f8772009-03-31 15:04:46 -070050import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.RemoteException;
52import android.provider.Settings;
53import android.util.Log;
54import android.text.TextUtils;
55
56import java.util.ArrayList;
57import java.util.BitSet;
58import java.util.HashMap;
59import java.util.LinkedHashMap;
60import java.util.List;
61import java.util.Map;
62import java.util.regex.Pattern;
63import java.io.FileDescriptor;
64import java.io.PrintWriter;
65
The Android Open Source Project10592532009-03-18 17:39:46 -070066import com.android.internal.app.IBatteryStats;
The Android Open Source Project10592532009-03-18 17:39:46 -070067import com.android.server.am.BatteryStatsService;
68
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069/**
70 * WifiService handles remote WiFi operation requests by implementing
71 * the IWifiManager interface. It also creates a WifiMonitor to listen
72 * for Wifi-related events.
73 *
74 * @hide
75 */
76public class WifiService extends IWifiManager.Stub {
77 private static final String TAG = "WifiService";
78 private static final boolean DBG = false;
79 private static final Pattern scanResultPattern = Pattern.compile("\t+");
80 private final WifiStateTracker mWifiStateTracker;
81
82 private Context mContext;
83 private int mWifiState;
84
85 private AlarmManager mAlarmManager;
86 private PendingIntent mIdleIntent;
87 private static final int IDLE_REQUEST = 0;
88 private boolean mScreenOff;
89 private boolean mDeviceIdle;
90 private int mPluggedType;
91
92 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -070093 // some wifi lock statistics
94 private int mFullLocksAcquired;
95 private int mFullLocksReleased;
96 private int mScanLocksAcquired;
97 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -070098
99 private final IBatteryStats mBatteryStats;
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 /**
102 * See {@link Settings.Gservices#WIFI_IDLE_MS}. This is the default value if a
103 * Settings.Gservices value is not present. This timeout value is chosen as
104 * the approximate point at which the battery drain caused by Wi-Fi
105 * being enabled but not active exceeds the battery drain caused by
106 * re-establishing a connection to the mobile data network.
107 */
108 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
109
110 private static final String WAKELOCK_TAG = "WifiService";
111
112 /**
113 * The maximum amount of time to hold the wake lock after a disconnect
114 * caused by stopping the driver. Establishing an EDGE connection has been
115 * observed to take about 5 seconds under normal circumstances. This
116 * provides a bit of extra margin.
117 * <p>
118 * See {@link android.provider.Settings.Secure#WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS}.
119 * This is the default value if a Settings.Secure value is not present.
120 */
121 private static final int DEFAULT_WAKELOCK_TIMEOUT = 8000;
122
123 // Wake lock used by driver-stop operation
124 private static PowerManager.WakeLock sDriverStopWakeLock;
125 // Wake lock used by other operations
126 private static PowerManager.WakeLock sWakeLock;
127
128 private static final int MESSAGE_ENABLE_WIFI = 0;
129 private static final int MESSAGE_DISABLE_WIFI = 1;
130 private static final int MESSAGE_STOP_WIFI = 2;
131 private static final int MESSAGE_START_WIFI = 3;
132 private static final int MESSAGE_RELEASE_WAKELOCK = 4;
133
134 private final WifiHandler mWifiHandler;
135
136 /*
137 * Map used to keep track of hidden networks presence, which
138 * is needed to switch between active and passive scan modes.
139 * If there is at least one hidden network that is currently
140 * present (enabled), we want to do active scans instead of
141 * passive.
142 */
143 private final Map<Integer, Boolean> mIsHiddenNetworkPresent;
144 /*
145 * The number of currently present hidden networks. When this
146 * counter goes from 0 to 1 or from 1 to 0, we change the
147 * scan mode to active or passive respectively. Initially, we
148 * set the counter to 0 and we increment it every time we add
149 * a new present (enabled) hidden network.
150 */
151 private int mNumHiddenNetworkPresent;
152 /*
153 * Whether we change the scan mode is due to a hidden network
154 * (in this class, this is always the case)
155 */
156 private final static boolean SET_DUE_TO_A_HIDDEN_NETWORK = true;
157
158 /*
159 * Cache of scan results objects (size is somewhat arbitrary)
160 */
161 private static final int SCAN_RESULT_CACHE_SIZE = 80;
162 private final LinkedHashMap<String, ScanResult> mScanResultCache;
163
164 /*
165 * Character buffer used to parse scan results (optimization)
166 */
167 private static final int SCAN_RESULT_BUFFER_SIZE = 512;
168 private char[] mScanResultBuffer;
169 private boolean mNeedReconfig;
170
Dianne Hackborn617f8772009-03-31 15:04:46 -0700171 /*
172 * Last UID that asked to enable WIFI.
173 */
174 private int mLastEnableUid = Process.myUid();
175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 /**
177 * Number of allowed radio frequency channels in various regulatory domains.
178 * This list is sufficient for 802.11b/g networks (2.4GHz range).
179 */
180 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
181
182 private static final String ACTION_DEVICE_IDLE =
183 "com.android.server.WifiManager.action.DEVICE_IDLE";
184
185 WifiService(Context context, WifiStateTracker tracker) {
186 mContext = context;
187 mWifiStateTracker = tracker;
The Android Open Source Project10592532009-03-18 17:39:46 -0700188 mBatteryStats = BatteryStatsService.getService();
189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 /*
191 * Initialize the hidden-networks state
192 */
193 mIsHiddenNetworkPresent = new HashMap<Integer, Boolean>();
194 mNumHiddenNetworkPresent = 0;
195
196 mScanResultCache = new LinkedHashMap<String, ScanResult>(
197 SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
198 /*
199 * Limit the cache size by SCAN_RESULT_CACHE_SIZE
200 * elements
201 */
202 public boolean removeEldestEntry(Map.Entry eldest) {
203 return SCAN_RESULT_CACHE_SIZE < this.size();
204 }
205 };
206
207 mScanResultBuffer = new char [SCAN_RESULT_BUFFER_SIZE];
208
209 HandlerThread wifiThread = new HandlerThread("WifiService");
210 wifiThread.start();
211 mWifiHandler = new WifiHandler(wifiThread.getLooper());
212
213 mWifiState = WIFI_STATE_DISABLED;
214 boolean wifiEnabled = getPersistedWifiEnabled();
215
216 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
217 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
218 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
219
220 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
221 sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
222 sDriverStopWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
223 mWifiStateTracker.setReleaseWakeLockCallback(
224 new Runnable() {
225 public void run() {
226 mWifiHandler.removeMessages(MESSAGE_RELEASE_WAKELOCK);
227 synchronized (sDriverStopWakeLock) {
228 if (sDriverStopWakeLock.isHeld()) {
229 sDriverStopWakeLock.release();
230 }
231 }
232 }
233 }
234 );
235
236 Log.i(TAG, "WifiService starting up with Wi-Fi " +
237 (wifiEnabled ? "enabled" : "disabled"));
238
239 mContext.registerReceiver(
240 new BroadcastReceiver() {
241 @Override
242 public void onReceive(Context context, Intent intent) {
243 updateWifiState();
244 }
245 },
246 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
247
Dianne Hackborn617f8772009-03-31 15:04:46 -0700248 setWifiEnabledBlocking(wifiEnabled, false, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 }
250
251 /**
252 * Initializes the hidden networks state. Must be called when we
253 * enable Wi-Fi.
254 */
255 private synchronized void initializeHiddenNetworksState() {
256 // First, reset the state
257 resetHiddenNetworksState();
258
259 // ... then add networks that are marked as hidden
260 List<WifiConfiguration> networks = getConfiguredNetworks();
261 if (!networks.isEmpty()) {
262 for (WifiConfiguration config : networks) {
263 if (config != null && config.hiddenSSID) {
264 addOrUpdateHiddenNetwork(
265 config.networkId,
266 config.status != WifiConfiguration.Status.DISABLED);
267 }
268 }
269
270 }
271 }
272
273 /**
274 * Resets the hidden networks state.
275 */
276 private synchronized void resetHiddenNetworksState() {
277 mNumHiddenNetworkPresent = 0;
278 mIsHiddenNetworkPresent.clear();
279 }
280
281 /**
282 * Marks all but netId network as not present.
283 */
284 private synchronized void markAllHiddenNetworksButOneAsNotPresent(int netId) {
285 for (Map.Entry<Integer, Boolean> entry : mIsHiddenNetworkPresent.entrySet()) {
286 if (entry != null) {
287 Integer networkId = entry.getKey();
288 if (networkId != netId) {
289 updateNetworkIfHidden(
290 networkId, false);
291 }
292 }
293 }
294 }
295
296 /**
297 * Updates the netId network presence status if netId is an existing
298 * hidden network.
299 */
300 private synchronized void updateNetworkIfHidden(int netId, boolean present) {
301 if (isHiddenNetwork(netId)) {
302 addOrUpdateHiddenNetwork(netId, present);
303 }
304 }
305
306 /**
307 * Updates the netId network presence status if netId is an existing
308 * hidden network. If the network does not exist, adds the network.
309 */
310 private synchronized void addOrUpdateHiddenNetwork(int netId, boolean present) {
311 if (0 <= netId) {
312
313 // If we are adding a new entry or modifying an existing one
314 Boolean isPresent = mIsHiddenNetworkPresent.get(netId);
315 if (isPresent == null || isPresent != present) {
316 if (present) {
317 incrementHiddentNetworkPresentCounter();
318 } else {
319 // If we add a new hidden network, no need to change
320 // the counter (it must be 0)
321 if (isPresent != null) {
322 decrementHiddentNetworkPresentCounter();
323 }
324 }
325 mIsHiddenNetworkPresent.put(netId, present);
326 }
327 } else {
328 Log.e(TAG, "addOrUpdateHiddenNetwork(): Invalid (negative) network id!");
329 }
330 }
331
332 /**
333 * Removes the netId network if it is hidden (being kept track of).
334 */
335 private synchronized void removeNetworkIfHidden(int netId) {
336 if (isHiddenNetwork(netId)) {
337 removeHiddenNetwork(netId);
338 }
339 }
340
341 /**
342 * Removes the netId network. For the call to be successful, the network
343 * must be hidden.
344 */
345 private synchronized void removeHiddenNetwork(int netId) {
346 if (0 <= netId) {
347 Boolean isPresent =
348 mIsHiddenNetworkPresent.remove(netId);
349 if (isPresent != null) {
350 // If we remove an existing hidden network that is not
351 // present, no need to change the counter
352 if (isPresent) {
353 decrementHiddentNetworkPresentCounter();
354 }
355 } else {
356 if (DBG) {
357 Log.d(TAG, "removeHiddenNetwork(): Removing a non-existent network!");
358 }
359 }
360 } else {
361 Log.e(TAG, "removeHiddenNetwork(): Invalid (negative) network id!");
362 }
363 }
364
365 /**
366 * Returns true if netId is an existing hidden network.
367 */
368 private synchronized boolean isHiddenNetwork(int netId) {
369 return mIsHiddenNetworkPresent.containsKey(netId);
370 }
371
372 /**
373 * Increments the present (enabled) hidden networks counter. If the
374 * counter value goes from 0 to 1, changes the scan mode to active.
375 */
376 private void incrementHiddentNetworkPresentCounter() {
377 ++mNumHiddenNetworkPresent;
378 if (1 == mNumHiddenNetworkPresent) {
379 // Switch the scan mode to "active"
380 mWifiStateTracker.setScanMode(true, SET_DUE_TO_A_HIDDEN_NETWORK);
381 }
382 }
383
384 /**
385 * Decrements the present (enabled) hidden networks counter. If the
386 * counter goes from 1 to 0, changes the scan mode back to passive.
387 */
388 private void decrementHiddentNetworkPresentCounter() {
389 if (0 < mNumHiddenNetworkPresent) {
390 --mNumHiddenNetworkPresent;
391 if (0 == mNumHiddenNetworkPresent) {
392 // Switch the scan mode to "passive"
393 mWifiStateTracker.setScanMode(false, SET_DUE_TO_A_HIDDEN_NETWORK);
394 }
395 } else {
396 Log.e(TAG, "Hidden-network counter invariant violation!");
397 }
398 }
399
400 private boolean getPersistedWifiEnabled() {
401 final ContentResolver cr = mContext.getContentResolver();
402 try {
403 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
404 } catch (Settings.SettingNotFoundException e) {
405 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
406 return false;
407 }
408 }
409
410 private void persistWifiEnabled(boolean enabled) {
411 final ContentResolver cr = mContext.getContentResolver();
412 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
413 }
414
415 NetworkStateTracker getNetworkStateTracker() {
416 return mWifiStateTracker;
417 }
418
419 /**
420 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
421 * @return {@code true} if the operation succeeds
422 */
423 public boolean pingSupplicant() {
424 enforceChangePermission();
425 synchronized (mWifiStateTracker) {
426 return WifiNative.pingCommand();
427 }
428 }
429
430 /**
431 * see {@link android.net.wifi.WifiManager#startScan()}
432 * @return {@code true} if the operation succeeds
433 */
434 public boolean startScan() {
435 enforceChangePermission();
436 synchronized (mWifiStateTracker) {
437 switch (mWifiStateTracker.getSupplicantState()) {
438 case DISCONNECTED:
439 case INACTIVE:
440 case SCANNING:
441 case DORMANT:
442 break;
443 default:
444 WifiNative.setScanResultHandlingCommand(
445 WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
446 break;
447 }
448 return WifiNative.scanCommand();
449 }
450 }
451
452 /**
453 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
454 * @param enable {@code true} to enable, {@code false} to disable.
455 * @return {@code true} if the enable/disable operation was
456 * started or is already in the queue.
457 */
458 public boolean setWifiEnabled(boolean enable) {
459 enforceChangePermission();
460 if (mWifiHandler == null) return false;
461
462 synchronized (mWifiHandler) {
463 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700464 mLastEnableUid = Binder.getCallingUid();
465 sendEnableMessage(enable, true, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 }
467
468 return true;
469 }
470
471 /**
472 * Enables/disables Wi-Fi synchronously.
473 * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
474 * @param persist {@code true} if the setting should be persisted.
Dianne Hackborn617f8772009-03-31 15:04:46 -0700475 * @param uid The UID of the process making the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 * @return {@code true} if the operation succeeds (or if the existing state
477 * is the same as the requested state)
478 */
Dianne Hackborn617f8772009-03-31 15:04:46 -0700479 private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
481
482 if (mWifiState == eventualWifiState) {
483 return true;
484 }
485 if (enable && isAirplaneModeOn()) {
486 return false;
487 }
488
Dianne Hackborn617f8772009-03-31 15:04:46 -0700489 setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490
491 if (enable) {
492 if (!WifiNative.loadDriver()) {
493 Log.e(TAG, "Failed to load Wi-Fi driver.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700494 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 return false;
496 }
497 if (!WifiNative.startSupplicant()) {
498 WifiNative.unloadDriver();
499 Log.e(TAG, "Failed to start supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700500 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 return false;
502 }
503 registerForBroadcasts();
504 mWifiStateTracker.startEventLoop();
505 } else {
506
507 mContext.unregisterReceiver(mReceiver);
508 // Remove notification (it will no-op if it isn't visible)
509 mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
510
511 boolean failedToStopSupplicantOrUnloadDriver = false;
512 if (!WifiNative.stopSupplicant()) {
513 Log.e(TAG, "Failed to stop supplicant daemon.");
Dianne Hackborn617f8772009-03-31 15:04:46 -0700514 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 failedToStopSupplicantOrUnloadDriver = true;
516 }
517
518 // We must reset the interface before we unload the driver
519 mWifiStateTracker.resetInterface();
520
521 if (!WifiNative.unloadDriver()) {
522 Log.e(TAG, "Failed to unload Wi-Fi driver.");
523 if (!failedToStopSupplicantOrUnloadDriver) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700524 setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 failedToStopSupplicantOrUnloadDriver = true;
526 }
527 }
528 if (failedToStopSupplicantOrUnloadDriver) {
529 return false;
530 }
531 }
532
533 // Success!
534
535 if (persist) {
536 persistWifiEnabled(enable);
537 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700538 setWifiEnabledState(eventualWifiState, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539
540 /*
541 * Initialize the hidden networks state and the number of allowed
542 * radio channels if Wi-Fi is being turned on.
543 */
544 if (enable) {
545 mWifiStateTracker.setNumAllowedChannels();
546 initializeHiddenNetworksState();
547 }
548
549 return true;
550 }
551
Dianne Hackborn617f8772009-03-31 15:04:46 -0700552 private void setWifiEnabledState(int wifiState, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 final int previousWifiState = mWifiState;
554
The Android Open Source Project10592532009-03-18 17:39:46 -0700555 long ident = Binder.clearCallingIdentity();
556 try {
557 if (wifiState == WIFI_STATE_ENABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700558 mBatteryStats.noteWifiOn(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700559 } else if (wifiState == WIFI_STATE_DISABLED) {
Dianne Hackborn617f8772009-03-31 15:04:46 -0700560 mBatteryStats.noteWifiOff(uid);
The Android Open Source Project10592532009-03-18 17:39:46 -0700561 }
562 } catch (RemoteException e) {
563 } finally {
564 Binder.restoreCallingIdentity(ident);
565 }
566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 // Update state
568 mWifiState = wifiState;
569
570 // Broadcast
571 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
572 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
573 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
574 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
575 mContext.sendStickyBroadcast(intent);
576 }
577
578 private void enforceAccessPermission() {
579 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
580 "WifiService");
581 }
582
583 private void enforceChangePermission() {
584 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
585 "WifiService");
586
587 }
588
589 /**
590 * see {@link WifiManager#getWifiState()}
591 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
592 * {@link WifiManager#WIFI_STATE_DISABLING},
593 * {@link WifiManager#WIFI_STATE_ENABLED},
594 * {@link WifiManager#WIFI_STATE_ENABLING},
595 * {@link WifiManager#WIFI_STATE_UNKNOWN}
596 */
597 public int getWifiEnabledState() {
598 enforceAccessPermission();
599 return mWifiState;
600 }
601
602 /**
603 * see {@link android.net.wifi.WifiManager#disconnect()}
604 * @return {@code true} if the operation succeeds
605 */
606 public boolean disconnect() {
607 enforceChangePermission();
608 synchronized (mWifiStateTracker) {
609 return WifiNative.disconnectCommand();
610 }
611 }
612
613 /**
614 * see {@link android.net.wifi.WifiManager#reconnect()}
615 * @return {@code true} if the operation succeeds
616 */
617 public boolean reconnect() {
618 enforceChangePermission();
619 synchronized (mWifiStateTracker) {
620 return WifiNative.reconnectCommand();
621 }
622 }
623
624 /**
625 * see {@link android.net.wifi.WifiManager#reassociate()}
626 * @return {@code true} if the operation succeeds
627 */
628 public boolean reassociate() {
629 enforceChangePermission();
630 synchronized (mWifiStateTracker) {
631 return WifiNative.reassociateCommand();
632 }
633 }
634
635 /**
636 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
637 * @return the list of configured networks
638 */
639 public List<WifiConfiguration> getConfiguredNetworks() {
640 enforceAccessPermission();
641 String listStr;
642 /*
643 * We don't cache the list, because we want to allow
644 * for the possibility that the configuration file
645 * has been modified through some external means,
646 * such as the wpa_cli command line program.
647 */
648 synchronized (mWifiStateTracker) {
649 listStr = WifiNative.listNetworksCommand();
650 }
651 List<WifiConfiguration> networks =
652 new ArrayList<WifiConfiguration>();
653 if (listStr == null)
654 return networks;
655
656 String[] lines = listStr.split("\n");
657 // Skip the first line, which is a header
658 for (int i = 1; i < lines.length; i++) {
659 String[] result = lines[i].split("\t");
660 // network-id | ssid | bssid | flags
661 WifiConfiguration config = new WifiConfiguration();
662 try {
663 config.networkId = Integer.parseInt(result[0]);
664 } catch(NumberFormatException e) {
665 continue;
666 }
667 if (result.length > 3) {
668 if (result[3].indexOf("[CURRENT]") != -1)
669 config.status = WifiConfiguration.Status.CURRENT;
670 else if (result[3].indexOf("[DISABLED]") != -1)
671 config.status = WifiConfiguration.Status.DISABLED;
672 else
673 config.status = WifiConfiguration.Status.ENABLED;
674 } else
675 config.status = WifiConfiguration.Status.ENABLED;
676 synchronized (mWifiStateTracker) {
677 readNetworkVariables(config);
678 }
679 networks.add(config);
680 }
681
682 return networks;
683 }
684
685 /**
686 * Read the variables from the supplicant daemon that are needed to
687 * fill in the WifiConfiguration object.
688 * <p/>
689 * The caller must hold the synchronization monitor.
690 * @param config the {@link WifiConfiguration} object to be filled in.
691 */
692 private static void readNetworkVariables(WifiConfiguration config) {
693
694 int netId = config.networkId;
695 if (netId < 0)
696 return;
697
698 /*
699 * TODO: maybe should have a native method that takes an array of
700 * variable names and returns an array of values. But we'd still
701 * be doing a round trip to the supplicant daemon for each variable.
702 */
703 String value;
704
705 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
706 if (!TextUtils.isEmpty(value)) {
707 config.SSID = value;
708 } else {
709 config.SSID = null;
710 }
711
712 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
713 if (!TextUtils.isEmpty(value)) {
714 config.BSSID = value;
715 } else {
716 config.BSSID = null;
717 }
718
719 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
720 config.priority = -1;
721 if (!TextUtils.isEmpty(value)) {
722 try {
723 config.priority = Integer.parseInt(value);
724 } catch (NumberFormatException ignore) {
725 }
726 }
727
728 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
729 config.hiddenSSID = false;
730 if (!TextUtils.isEmpty(value)) {
731 try {
732 config.hiddenSSID = Integer.parseInt(value) != 0;
733 } catch (NumberFormatException ignore) {
734 }
735 }
736
737 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
738 config.wepTxKeyIndex = -1;
739 if (!TextUtils.isEmpty(value)) {
740 try {
741 config.wepTxKeyIndex = Integer.parseInt(value);
742 } catch (NumberFormatException ignore) {
743 }
744 }
745
746 /*
747 * Get up to 4 WEP keys. Note that the actual keys are not passed back,
748 * just a "*" if the key is set, or the null string otherwise.
749 */
750 for (int i = 0; i < 4; i++) {
751 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
752 if (!TextUtils.isEmpty(value)) {
753 config.wepKeys[i] = value;
754 } else {
755 config.wepKeys[i] = null;
756 }
757 }
758
759 /*
760 * Get the private shared key. Note that the actual keys are not passed back,
761 * just a "*" if the key is set, or the null string otherwise.
762 */
763 value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
764 if (!TextUtils.isEmpty(value)) {
765 config.preSharedKey = value;
766 } else {
767 config.preSharedKey = null;
768 }
769
770 value = WifiNative.getNetworkVariableCommand(config.networkId,
771 WifiConfiguration.Protocol.varName);
772 if (!TextUtils.isEmpty(value)) {
773 String vals[] = value.split(" ");
774 for (String val : vals) {
775 int index =
776 lookupString(val, WifiConfiguration.Protocol.strings);
777 if (0 <= index) {
778 config.allowedProtocols.set(index);
779 }
780 }
781 }
782
783 value = WifiNative.getNetworkVariableCommand(config.networkId,
784 WifiConfiguration.KeyMgmt.varName);
785 if (!TextUtils.isEmpty(value)) {
786 String vals[] = value.split(" ");
787 for (String val : vals) {
788 int index =
789 lookupString(val, WifiConfiguration.KeyMgmt.strings);
790 if (0 <= index) {
791 config.allowedKeyManagement.set(index);
792 }
793 }
794 }
795
796 value = WifiNative.getNetworkVariableCommand(config.networkId,
797 WifiConfiguration.AuthAlgorithm.varName);
798 if (!TextUtils.isEmpty(value)) {
799 String vals[] = value.split(" ");
800 for (String val : vals) {
801 int index =
802 lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
803 if (0 <= index) {
804 config.allowedAuthAlgorithms.set(index);
805 }
806 }
807 }
808
809 value = WifiNative.getNetworkVariableCommand(config.networkId,
810 WifiConfiguration.PairwiseCipher.varName);
811 if (!TextUtils.isEmpty(value)) {
812 String vals[] = value.split(" ");
813 for (String val : vals) {
814 int index =
815 lookupString(val, WifiConfiguration.PairwiseCipher.strings);
816 if (0 <= index) {
817 config.allowedPairwiseCiphers.set(index);
818 }
819 }
820 }
821
822 value = WifiNative.getNetworkVariableCommand(config.networkId,
823 WifiConfiguration.GroupCipher.varName);
824 if (!TextUtils.isEmpty(value)) {
825 String vals[] = value.split(" ");
826 for (String val : vals) {
827 int index =
828 lookupString(val, WifiConfiguration.GroupCipher.strings);
829 if (0 <= index) {
830 config.allowedGroupCiphers.set(index);
831 }
832 }
833 }
834 }
835
836 /**
837 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
838 * @return the supplicant-assigned identifier for the new or updated
839 * network if the operation succeeds, or {@code -1} if it fails
840 */
841 public synchronized int addOrUpdateNetwork(WifiConfiguration config) {
842 enforceChangePermission();
843 /*
844 * If the supplied networkId is -1, we create a new empty
845 * network configuration. Otherwise, the networkId should
846 * refer to an existing configuration.
847 */
848 int netId = config.networkId;
849 boolean newNetwork = netId == -1;
850 boolean doReconfig;
851 int currentPriority;
852 // networkId of -1 means we want to create a new network
853 if (newNetwork) {
854 netId = WifiNative.addNetworkCommand();
855 if (netId < 0) {
856 if (DBG) {
857 Log.d(TAG, "Failed to add a network!");
858 }
859 return -1;
860 }
861 doReconfig = true;
862 } else {
863 String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
864 currentPriority = -1;
865 if (!TextUtils.isEmpty(priorityVal)) {
866 try {
867 currentPriority = Integer.parseInt(priorityVal);
868 } catch (NumberFormatException ignore) {
869 }
870 }
871 doReconfig = currentPriority != config.priority;
872 }
873 mNeedReconfig = mNeedReconfig || doReconfig;
874
875 /*
876 * If we have hidden networks, we may have to change the scan mode
877 */
878 if (config.hiddenSSID) {
879 // Mark the network as present unless it is disabled
880 addOrUpdateHiddenNetwork(
881 netId, config.status != WifiConfiguration.Status.DISABLED);
882 }
883
884 setVariables: {
885 /*
886 * Note that if a networkId for a non-existent network
887 * was supplied, then the first setNetworkVariableCommand()
888 * will fail, so we don't bother to make a separate check
889 * for the validity of the ID up front.
890 */
891
892 if (config.SSID != null &&
893 !WifiNative.setNetworkVariableCommand(
894 netId,
895 WifiConfiguration.ssidVarName,
896 config.SSID)) {
897 if (DBG) {
898 Log.d(TAG, "failed to set SSID: "+config.SSID);
899 }
900 break setVariables;
901 }
902
903 if (config.BSSID != null &&
904 !WifiNative.setNetworkVariableCommand(
905 netId,
906 WifiConfiguration.bssidVarName,
907 config.BSSID)) {
908 if (DBG) {
909 Log.d(TAG, "failed to set BSSID: "+config.BSSID);
910 }
911 break setVariables;
912 }
913
914 String allowedKeyManagementString =
915 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
916 if (config.allowedKeyManagement.cardinality() != 0 &&
917 !WifiNative.setNetworkVariableCommand(
918 netId,
919 WifiConfiguration.KeyMgmt.varName,
920 allowedKeyManagementString)) {
921 if (DBG) {
922 Log.d(TAG, "failed to set key_mgmt: "+
923 allowedKeyManagementString);
924 }
925 break setVariables;
926 }
927
928 String allowedProtocolsString =
929 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
930 if (config.allowedProtocols.cardinality() != 0 &&
931 !WifiNative.setNetworkVariableCommand(
932 netId,
933 WifiConfiguration.Protocol.varName,
934 allowedProtocolsString)) {
935 if (DBG) {
936 Log.d(TAG, "failed to set proto: "+
937 allowedProtocolsString);
938 }
939 break setVariables;
940 }
941
942 String allowedAuthAlgorithmsString =
943 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
944 if (config.allowedAuthAlgorithms.cardinality() != 0 &&
945 !WifiNative.setNetworkVariableCommand(
946 netId,
947 WifiConfiguration.AuthAlgorithm.varName,
948 allowedAuthAlgorithmsString)) {
949 if (DBG) {
950 Log.d(TAG, "failed to set auth_alg: "+
951 allowedAuthAlgorithmsString);
952 }
953 break setVariables;
954 }
955
956 String allowedPairwiseCiphersString =
957 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
958 if (config.allowedPairwiseCiphers.cardinality() != 0 &&
959 !WifiNative.setNetworkVariableCommand(
960 netId,
961 WifiConfiguration.PairwiseCipher.varName,
962 allowedPairwiseCiphersString)) {
963 if (DBG) {
964 Log.d(TAG, "failed to set pairwise: "+
965 allowedPairwiseCiphersString);
966 }
967 break setVariables;
968 }
969
970 String allowedGroupCiphersString =
971 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
972 if (config.allowedGroupCiphers.cardinality() != 0 &&
973 !WifiNative.setNetworkVariableCommand(
974 netId,
975 WifiConfiguration.GroupCipher.varName,
976 allowedGroupCiphersString)) {
977 if (DBG) {
978 Log.d(TAG, "failed to set group: "+
979 allowedGroupCiphersString);
980 }
981 break setVariables;
982 }
983
984 // Prevent client screw-up by passing in a WifiConfiguration we gave it
985 // by preventing "*" as a key.
986 if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
987 !WifiNative.setNetworkVariableCommand(
988 netId,
989 WifiConfiguration.pskVarName,
990 config.preSharedKey)) {
991 if (DBG) {
992 Log.d(TAG, "failed to set psk: "+config.preSharedKey);
993 }
994 break setVariables;
995 }
996
997 boolean hasSetKey = false;
998 if (config.wepKeys != null) {
999 for (int i = 0; i < config.wepKeys.length; i++) {
1000 // Prevent client screw-up by passing in a WifiConfiguration we gave it
1001 // by preventing "*" as a key.
1002 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
1003 if (!WifiNative.setNetworkVariableCommand(
1004 netId,
1005 WifiConfiguration.wepKeyVarNames[i],
1006 config.wepKeys[i])) {
1007 if (DBG) {
1008 Log.d(TAG,
1009 "failed to set wep_key"+i+": " +
1010 config.wepKeys[i]);
1011 }
1012 break setVariables;
1013 }
1014 hasSetKey = true;
1015 }
1016 }
1017 }
1018
1019 if (hasSetKey) {
1020 if (!WifiNative.setNetworkVariableCommand(
1021 netId,
1022 WifiConfiguration.wepTxKeyIdxVarName,
1023 Integer.toString(config.wepTxKeyIndex))) {
1024 if (DBG) {
1025 Log.d(TAG,
1026 "failed to set wep_tx_keyidx: "+
1027 config.wepTxKeyIndex);
1028 }
1029 break setVariables;
1030 }
1031 }
1032
1033 if (!WifiNative.setNetworkVariableCommand(
1034 netId,
1035 WifiConfiguration.priorityVarName,
1036 Integer.toString(config.priority))) {
1037 if (DBG) {
1038 Log.d(TAG, config.SSID + ": failed to set priority: "
1039 +config.priority);
1040 }
1041 break setVariables;
1042 }
1043
1044 if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
1045 netId,
1046 WifiConfiguration.hiddenSSIDVarName,
1047 Integer.toString(config.hiddenSSID ? 1 : 0))) {
1048 if (DBG) {
1049 Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
1050 config.hiddenSSID);
1051 }
1052 break setVariables;
1053 }
1054
1055 return netId;
1056 }
1057
1058 /*
1059 * For an update, if one of the setNetworkVariable operations fails,
1060 * we might want to roll back all the changes already made. But the
1061 * chances are that if anything is going to go wrong, it'll happen
1062 * the first time we try to set one of the variables.
1063 */
1064 if (newNetwork) {
1065 removeNetwork(netId);
1066 if (DBG) {
1067 Log.d(TAG,
1068 "Failed to set a network variable, removed network: "
1069 + netId);
1070 }
1071 }
1072 return -1;
1073 }
1074
1075 private static String makeString(BitSet set, String[] strings) {
1076 StringBuffer buf = new StringBuffer();
1077 int nextSetBit = -1;
1078
1079 /* Make sure all set bits are in [0, strings.length) to avoid
1080 * going out of bounds on strings. (Shouldn't happen, but...) */
1081 set = set.get(0, strings.length);
1082
1083 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
1084 buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
1085 }
1086
1087 // remove trailing space
1088 if (set.cardinality() > 0) {
1089 buf.setLength(buf.length() - 1);
1090 }
1091
1092 return buf.toString();
1093 }
1094
1095 private static int lookupString(String string, String[] strings) {
1096 int size = strings.length;
1097
1098 string = string.replace('-', '_');
1099
1100 for (int i = 0; i < size; i++)
1101 if (string.equals(strings[i]))
1102 return i;
1103
1104 if (DBG) {
1105 // if we ever get here, we should probably add the
1106 // value to WifiConfiguration to reflect that it's
1107 // supported by the WPA supplicant
1108 Log.w(TAG, "Failed to look-up a string: " + string);
1109 }
1110
1111 return -1;
1112 }
1113
1114 /**
1115 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
1116 * @param netId the integer that identifies the network configuration
1117 * to the supplicant
1118 * @return {@code true} if the operation succeeded
1119 */
1120 public boolean removeNetwork(int netId) {
1121 enforceChangePermission();
1122
1123 /*
1124 * If we have hidden networks, we may have to change the scan mode
1125 */
1126 removeNetworkIfHidden(netId);
1127
1128 return mWifiStateTracker.removeNetwork(netId);
1129 }
1130
1131 /**
1132 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
1133 * @param netId the integer that identifies the network configuration
1134 * to the supplicant
1135 * @param disableOthers if true, disable all other networks.
1136 * @return {@code true} if the operation succeeded
1137 */
1138 public boolean enableNetwork(int netId, boolean disableOthers) {
1139 enforceChangePermission();
1140
1141 /*
1142 * If we have hidden networks, we may have to change the scan mode
1143 */
1144 synchronized(this) {
1145 if (disableOthers) {
1146 markAllHiddenNetworksButOneAsNotPresent(netId);
1147 }
1148 updateNetworkIfHidden(netId, true);
1149 }
1150
1151 synchronized (mWifiStateTracker) {
1152 return WifiNative.enableNetworkCommand(netId, disableOthers);
1153 }
1154 }
1155
1156 /**
1157 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
1158 * @param netId the integer that identifies the network configuration
1159 * to the supplicant
1160 * @return {@code true} if the operation succeeded
1161 */
1162 public boolean disableNetwork(int netId) {
1163 enforceChangePermission();
1164
1165 /*
1166 * If we have hidden networks, we may have to change the scan mode
1167 */
1168 updateNetworkIfHidden(netId, false);
1169
1170 synchronized (mWifiStateTracker) {
1171 return WifiNative.disableNetworkCommand(netId);
1172 }
1173 }
1174
1175 /**
1176 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
1177 * @return the Wi-Fi information, contained in {@link WifiInfo}.
1178 */
1179 public WifiInfo getConnectionInfo() {
1180 enforceAccessPermission();
1181 /*
1182 * Make sure we have the latest information, by sending
1183 * a status request to the supplicant.
1184 */
1185 return mWifiStateTracker.requestConnectionInfo();
1186 }
1187
1188 /**
1189 * Return the results of the most recent access point scan, in the form of
1190 * a list of {@link ScanResult} objects.
1191 * @return the list of results
1192 */
1193 public List<ScanResult> getScanResults() {
1194 enforceAccessPermission();
1195 String reply;
1196 synchronized (mWifiStateTracker) {
1197 reply = WifiNative.scanResultsCommand();
1198 }
1199 if (reply == null) {
1200 return null;
1201 }
1202
1203 List<ScanResult> scanList = new ArrayList<ScanResult>();
1204
1205 int lineCount = 0;
1206
1207 int replyLen = reply.length();
1208 // Parse the result string, keeping in mind that the last line does
1209 // not end with a newline.
1210 for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
1211 if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
1212 ++lineCount;
1213 /*
1214 * Skip the first line, which is a header
1215 */
1216 if (lineCount == 1) {
1217 lineBeg = lineEnd + 1;
1218 continue;
1219 }
1220 int lineLen = lineEnd - lineBeg;
1221 if (0 < lineLen && lineLen <= SCAN_RESULT_BUFFER_SIZE) {
1222 int scanResultLevel = 0;
1223 /*
1224 * At most one thread should have access to the buffer at a time!
1225 */
1226 synchronized(mScanResultBuffer) {
1227 boolean parsingScanResultLevel = false;
1228 for (int i = lineBeg; i < lineEnd; ++i) {
1229 char ch = reply.charAt(i);
1230 /*
1231 * Assume that the signal level starts with a '-'
1232 */
1233 if (ch == '-') {
1234 /*
1235 * Skip whatever instances of '-' we may have
1236 * after we parse the signal level
1237 */
1238 parsingScanResultLevel = (scanResultLevel == 0);
1239 } else if (parsingScanResultLevel) {
1240 int digit = Character.digit(ch, 10);
1241 if (0 <= digit) {
1242 scanResultLevel =
1243 10 * scanResultLevel + digit;
1244 /*
1245 * Replace the signal level number in
1246 * the string with 0's for caching
1247 */
1248 ch = '0';
1249 } else {
1250 /*
1251 * Reset the flag if we meet a non-digit
1252 * character
1253 */
1254 parsingScanResultLevel = false;
1255 }
1256 }
1257 mScanResultBuffer[i - lineBeg] = ch;
1258 }
1259 if (scanResultLevel != 0) {
1260 ScanResult scanResult = parseScanResult(
1261 new String(mScanResultBuffer, 0, lineLen));
1262 if (scanResult != null) {
1263 scanResult.level = -scanResultLevel;
1264 scanList.add(scanResult);
1265 }
1266 } else if (DBG) {
1267 Log.w(TAG,
1268 "ScanResult.level=0: misformatted scan result?");
1269 }
1270 }
1271 } else if (0 < lineLen) {
1272 if (DBG) {
1273 Log.w(TAG, "Scan result line is too long: " +
1274 (lineEnd - lineBeg) + ", skipping the line!");
1275 }
1276 }
1277 lineBeg = lineEnd + 1;
1278 }
1279 }
1280 mWifiStateTracker.setScanResultsList(scanList);
1281 return scanList;
1282 }
1283
1284 /**
1285 * Parse the scan result line passed to us by wpa_supplicant (helper).
1286 * @param line the line to parse
1287 * @return the {@link ScanResult} object
1288 */
1289 private ScanResult parseScanResult(String line) {
1290 ScanResult scanResult = null;
1291 if (line != null) {
1292 /*
1293 * Cache implementation (LinkedHashMap) is not synchronized, thus,
1294 * must synchronized here!
1295 */
1296 synchronized (mScanResultCache) {
1297 scanResult = mScanResultCache.get(line);
1298 if (scanResult == null) {
1299 String[] result = scanResultPattern.split(line);
1300 if (3 <= result.length && result.length <= 5) {
1301 // bssid | frequency | level | flags | ssid
1302 int frequency;
1303 int level;
1304 try {
1305 frequency = Integer.parseInt(result[1]);
1306 level = Integer.parseInt(result[2]);
1307 } catch (NumberFormatException e) {
1308 frequency = 0;
1309 level = 0;
1310 }
1311
1312 /*
1313 * The formatting of the results returned by
1314 * wpa_supplicant is intended to make the fields
1315 * line up nicely when printed,
1316 * not to make them easy to parse. So we have to
1317 * apply some heuristics to figure out which field
1318 * is the SSID and which field is the flags.
1319 */
1320 String ssid;
1321 String flags;
1322 if (result.length == 4) {
1323 if (result[3].charAt(0) == '[') {
1324 flags = result[3];
1325 ssid = "";
1326 } else {
1327 flags = "";
1328 ssid = result[3];
1329 }
1330 } else if (result.length == 5) {
1331 flags = result[3];
1332 ssid = result[4];
1333 } else {
1334 // Here, we must have 3 fields: no flags and ssid
1335 // set
1336 flags = "";
1337 ssid = "";
1338 }
1339
1340 // Do not add scan results that have no SSID set
1341 if (0 < ssid.trim().length()) {
1342 scanResult =
1343 new ScanResult(
1344 ssid, result[0], flags, level, frequency);
1345 mScanResultCache.put(line, scanResult);
1346 }
1347 } else {
1348 Log.w(TAG, "Misformatted scan result text with " +
1349 result.length + " fields: " + line);
1350 }
1351 }
1352 }
1353 }
1354
1355 return scanResult;
1356 }
1357
1358 /**
1359 * Parse the "flags" field passed back in a scan result by wpa_supplicant,
1360 * and construct a {@code WifiConfiguration} that describes the encryption,
1361 * key management, and authenticaion capabilities of the access point.
1362 * @param flags the string returned by wpa_supplicant
1363 * @return the {@link WifiConfiguration} object, filled in
1364 */
1365 WifiConfiguration parseScanFlags(String flags) {
1366 WifiConfiguration config = new WifiConfiguration();
1367
1368 if (flags.length() == 0) {
1369 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
1370 }
1371 // ... to be implemented
1372 return config;
1373 }
1374
1375 /**
1376 * Tell the supplicant to persist the current list of configured networks.
1377 * @return {@code true} if the operation succeeded
1378 */
1379 public boolean saveConfiguration() {
1380 boolean result;
1381 enforceChangePermission();
1382 synchronized (mWifiStateTracker) {
1383 result = WifiNative.saveConfigCommand();
1384 if (result && mNeedReconfig) {
1385 mNeedReconfig = false;
1386 result = WifiNative.reloadConfigCommand();
1387
1388 if (result) {
1389 Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
1390 mContext.sendBroadcast(intent);
1391 }
1392 }
1393 }
1394 return result;
1395 }
1396
1397 /**
1398 * Set the number of radio frequency channels that are allowed to be used
1399 * in the current regulatory domain. This method should be used only
1400 * if the correct number of channels cannot be determined automatically
1401 * for some reason. If the operation is successful, the new value is
1402 * persisted as a Secure setting.
1403 * @param numChannels the number of allowed channels. Must be greater than 0
1404 * and less than or equal to 16.
1405 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
1406 * {@code numChannels} is outside the valid range.
1407 */
1408 public boolean setNumAllowedChannels(int numChannels) {
1409 enforceChangePermission();
1410 /*
1411 * Validate the argument. We'd like to let the Wi-Fi driver do this,
1412 * but if Wi-Fi isn't currently enabled, that's not possible, and
1413 * we want to persist the setting anyway,so that it will take
1414 * effect when Wi-Fi does become enabled.
1415 */
1416 boolean found = false;
1417 for (int validChan : sValidRegulatoryChannelCounts) {
1418 if (validChan == numChannels) {
1419 found = true;
1420 break;
1421 }
1422 }
1423 if (!found) {
1424 return false;
1425 }
1426
1427 Settings.Secure.putInt(mContext.getContentResolver(),
1428 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1429 numChannels);
1430 mWifiStateTracker.setNumAllowedChannels(numChannels);
1431 return true;
1432 }
1433
1434 /**
1435 * Return the number of frequency channels that are allowed
1436 * to be used in the current regulatory domain.
1437 * @return the number of allowed channels, or {@code -1} if an error occurs
1438 */
1439 public int getNumAllowedChannels() {
1440 int numChannels;
1441
1442 enforceAccessPermission();
1443 synchronized (mWifiStateTracker) {
1444 /*
1445 * If we can't get the value from the driver (e.g., because
1446 * Wi-Fi is not currently enabled), get the value from
1447 * Settings.
1448 */
1449 numChannels = WifiNative.getNumAllowedChannelsCommand();
1450 if (numChannels < 0) {
1451 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
1452 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
1453 -1);
1454 }
1455 }
1456 return numChannels;
1457 }
1458
1459 /**
1460 * Return the list of valid values for the number of allowed radio channels
1461 * for various regulatory domains.
1462 * @return the list of channel counts
1463 */
1464 public int[] getValidChannelCounts() {
1465 enforceAccessPermission();
1466 return sValidRegulatoryChannelCounts;
1467 }
1468
1469 /**
1470 * Return the DHCP-assigned addresses from the last successful DHCP request,
1471 * if any.
1472 * @return the DHCP information
1473 */
1474 public DhcpInfo getDhcpInfo() {
1475 enforceAccessPermission();
1476 return mWifiStateTracker.getDhcpInfo();
1477 }
1478
1479 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1480 @Override
1481 public void onReceive(Context context, Intent intent) {
1482 String action = intent.getAction();
1483
1484 long idleMillis = Settings.Gservices.getLong(mContext.getContentResolver(),
1485 Settings.Gservices.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
1486 int stayAwakeConditions =
1487 Settings.System.getInt(mContext.getContentResolver(),
1488 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
1489 if (action.equals(Intent.ACTION_SCREEN_ON)) {
1490 mAlarmManager.cancel(mIdleIntent);
1491 mDeviceIdle = false;
1492 mScreenOff = false;
1493 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1494 mScreenOff = true;
1495 /*
1496 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1497 * AND the "stay on while plugged in" setting doesn't match the
1498 * current power conditions (i.e, not plugged in, plugged in to USB,
1499 * or plugged in to AC).
1500 */
1501 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
1502 long triggerTime = System.currentTimeMillis() + idleMillis;
1503 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1504 }
1505 /* we can return now -- there's nothing to do until we get the idle intent back */
1506 return;
1507 } else if (action.equals(ACTION_DEVICE_IDLE)) {
1508 mDeviceIdle = true;
1509 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1510 /*
1511 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1512 * AND we are transitioning from a state in which the device was supposed
1513 * to stay awake to a state in which it is not supposed to stay awake.
1514 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1515 * the already-set timer.
1516 */
1517 int pluggedType = intent.getIntExtra("plugged", 0);
1518 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1519 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1520 long triggerTime = System.currentTimeMillis() + idleMillis;
1521 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
1522 mPluggedType = pluggedType;
1523 return;
1524 }
1525 mPluggedType = pluggedType;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001526 } else if (action.equals(BluetoothA2dp.SINK_STATE_CHANGED_ACTION)) {
1527 boolean isBluetoothPlaying =
1528 intent.getIntExtra(
1529 BluetoothA2dp.SINK_STATE,
1530 BluetoothA2dp.STATE_DISCONNECTED) == BluetoothA2dp.STATE_PLAYING;
1531 mWifiStateTracker.setBluetoothScanMode(isBluetoothPlaying);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 } else {
1533 return;
1534 }
1535
1536 updateWifiState();
1537 }
1538
1539 /**
1540 * Determines whether the Wi-Fi chipset should stay awake or be put to
1541 * sleep. Looks at the setting for the sleep policy and the current
1542 * conditions.
1543 *
1544 * @see #shouldDeviceStayAwake(int, int)
1545 */
1546 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
1547 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
1548 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
1549
1550 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1551 // Never sleep
1552 return true;
1553 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1554 (pluggedType != 0)) {
1555 // Never sleep while plugged, and we're plugged
1556 return true;
1557 } else {
1558 // Default
1559 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1560 }
1561 }
1562
1563 /**
1564 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1565 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1566 * of {@code 0} isn't really a plugged type, but rather an indication that the
1567 * device isn't plugged in at all, there is no bit value corresponding to a
1568 * {@code pluggedType} value of {@code 0}. That is why we shift by
1569 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
1570 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1571 * keep the device (and hence Wi-Fi) awake.
1572 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1573 * being made
1574 * @return {@code true} if {@code pluggedType} indicates that the device is
1575 * supposed to stay awake, {@code false} otherwise.
1576 */
1577 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1578 return (stayAwakeConditions & pluggedType) != 0;
1579 }
1580 };
1581
Dianne Hackborn617f8772009-03-31 15:04:46 -07001582 private void sendEnableMessage(boolean enable, boolean persist, int uid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 Message msg = Message.obtain(mWifiHandler,
1584 (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
Dianne Hackborn617f8772009-03-31 15:04:46 -07001585 (persist ? 1 : 0), uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 msg.sendToTarget();
1587 }
1588
1589 private void sendStartMessage(boolean scanOnlyMode) {
1590 Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
1591 }
1592
1593 private void updateWifiState() {
1594 boolean wifiEnabled = getPersistedWifiEnabled();
1595 boolean airplaneMode = isAirplaneModeOn();
1596 boolean lockHeld = mLocks.hasLocks();
1597 int strongestLockMode;
1598 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1599 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1600 if (mDeviceIdle && lockHeld) {
1601 strongestLockMode = mLocks.getStrongestLockMode();
1602 } else {
1603 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1604 }
1605
1606 synchronized (mWifiHandler) {
1607 if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
1608 return;
1609 }
1610 if (wifiShouldBeEnabled) {
1611 if (wifiShouldBeStarted) {
1612 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001613 sendEnableMessage(true, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 sWakeLock.acquire();
1615 sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
1616 } else {
1617 int wakeLockTimeout =
1618 Settings.Secure.getInt(
1619 mContext.getContentResolver(),
1620 Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS,
1621 DEFAULT_WAKELOCK_TIMEOUT);
1622 /*
1623 * The following wakelock is held in order to ensure
1624 * that the connectivity manager has time to fail over
1625 * to the mobile data network. The connectivity manager
1626 * releases it once mobile data connectivity has been
1627 * established. If connectivity cannot be established,
1628 * the wakelock is released after wakeLockTimeout
1629 * milliseconds have elapsed.
1630 */
1631 sDriverStopWakeLock.acquire();
1632 mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
1633 mWifiHandler.sendEmptyMessageDelayed(MESSAGE_RELEASE_WAKELOCK, wakeLockTimeout);
1634 }
1635 } else {
1636 sWakeLock.acquire();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001637 sendEnableMessage(false, false, mLastEnableUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 }
1639 }
1640 }
1641
1642 private void registerForBroadcasts() {
1643 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1645 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1646 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1647 intentFilter.addAction(ACTION_DEVICE_IDLE);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001648 intentFilter.addAction(BluetoothA2dp.SINK_STATE_CHANGED_ACTION);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 mContext.registerReceiver(mReceiver, intentFilter);
1650 }
1651
1652 private boolean isAirplaneSensitive() {
1653 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1654 Settings.System.AIRPLANE_MODE_RADIOS);
1655 return airplaneModeRadios == null
1656 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1657 }
1658
1659 /**
1660 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1661 * currently on.
1662 * @return {@code true} if airplane mode is on.
1663 */
1664 private boolean isAirplaneModeOn() {
1665 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1666 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1667 }
1668
1669 /**
1670 * Handler that allows posting to the WifiThread.
1671 */
1672 private class WifiHandler extends Handler {
1673 public WifiHandler(Looper looper) {
1674 super(looper);
1675 }
1676
1677 @Override
1678 public void handleMessage(Message msg) {
1679 switch (msg.what) {
1680
1681 case MESSAGE_ENABLE_WIFI:
Dianne Hackborn617f8772009-03-31 15:04:46 -07001682 setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 sWakeLock.release();
1684 break;
1685
1686 case MESSAGE_START_WIFI:
1687 mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
1688 mWifiStateTracker.restart();
1689 sWakeLock.release();
1690 break;
1691
1692 case MESSAGE_DISABLE_WIFI:
1693 // a non-zero msg.arg1 value means the "enabled" setting
1694 // should be persisted
Dianne Hackborn617f8772009-03-31 15:04:46 -07001695 setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 sWakeLock.release();
1697 break;
1698
1699 case MESSAGE_STOP_WIFI:
1700 mWifiStateTracker.disconnectAndStop();
1701 // don't release wakelock
1702 break;
1703
1704 case MESSAGE_RELEASE_WAKELOCK:
1705 synchronized (sDriverStopWakeLock) {
1706 if (sDriverStopWakeLock.isHeld()) {
1707 sDriverStopWakeLock.release();
1708 }
1709 }
1710 break;
1711 }
1712 }
1713 }
1714
1715 @Override
1716 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1717 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1718 != PackageManager.PERMISSION_GRANTED) {
1719 pw.println("Permission Denial: can't dump WifiService from from pid="
1720 + Binder.getCallingPid()
1721 + ", uid=" + Binder.getCallingUid());
1722 return;
1723 }
1724 pw.println("Wi-Fi is " + stateName(mWifiState));
1725 pw.println("Stay-awake conditions: " +
1726 Settings.System.getInt(mContext.getContentResolver(),
1727 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1728 pw.println();
1729
1730 pw.println("Internal state:");
1731 pw.println(mWifiStateTracker);
1732 pw.println();
1733 pw.println("Latest scan results:");
1734 List<ScanResult> scanResults = mWifiStateTracker.getScanResultsList();
1735 if (scanResults != null && scanResults.size() != 0) {
1736 pw.println(" BSSID Frequency RSSI Flags SSID");
1737 for (ScanResult r : scanResults) {
1738 pw.printf(" %17s %9d %5d %-16s %s%n",
1739 r.BSSID,
1740 r.frequency,
1741 r.level,
1742 r.capabilities,
1743 r.SSID == null ? "" : r.SSID);
1744 }
1745 }
1746 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001747 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1748 mScanLocksAcquired + " scan");
1749 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1750 mScanLocksReleased + " scan");
1751 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 pw.println("Locks held:");
1753 mLocks.dump(pw);
1754 }
1755
1756 private static String stateName(int wifiState) {
1757 switch (wifiState) {
1758 case WIFI_STATE_DISABLING:
1759 return "disabling";
1760 case WIFI_STATE_DISABLED:
1761 return "disabled";
1762 case WIFI_STATE_ENABLING:
1763 return "enabling";
1764 case WIFI_STATE_ENABLED:
1765 return "enabled";
1766 case WIFI_STATE_UNKNOWN:
1767 return "unknown state";
1768 default:
1769 return "[invalid state]";
1770 }
1771 }
1772
1773 private class WifiLock implements IBinder.DeathRecipient {
1774 String mTag;
1775 int mLockMode;
1776 IBinder mBinder;
1777
1778 WifiLock(int lockMode, String tag, IBinder binder) {
1779 super();
1780 mTag = tag;
1781 mLockMode = lockMode;
1782 mBinder = binder;
1783 try {
1784 mBinder.linkToDeath(this, 0);
1785 } catch (RemoteException e) {
1786 binderDied();
1787 }
1788 }
1789
1790 public void binderDied() {
1791 synchronized (mLocks) {
1792 releaseWifiLockLocked(mBinder);
1793 }
1794 }
1795
1796 public String toString() {
1797 return "WifiLock{" + mTag + " type=" + mLockMode + " binder=" + mBinder + "}";
1798 }
1799 }
1800
1801 private class LockList {
1802 private List<WifiLock> mList;
1803
1804 private LockList() {
1805 mList = new ArrayList<WifiLock>();
1806 }
1807
1808 private synchronized boolean hasLocks() {
1809 return !mList.isEmpty();
1810 }
1811
1812 private synchronized int getStrongestLockMode() {
1813 if (mList.isEmpty()) {
1814 return WifiManager.WIFI_MODE_FULL;
1815 }
1816 for (WifiLock l : mList) {
1817 if (l.mLockMode == WifiManager.WIFI_MODE_FULL) {
1818 return WifiManager.WIFI_MODE_FULL;
1819 }
1820 }
1821 return WifiManager.WIFI_MODE_SCAN_ONLY;
1822 }
1823
1824 private void addLock(WifiLock lock) {
1825 if (findLockByBinder(lock.mBinder) < 0) {
1826 mList.add(lock);
1827 }
1828 }
1829
1830 private WifiLock removeLock(IBinder binder) {
1831 int index = findLockByBinder(binder);
1832 if (index >= 0) {
1833 return mList.remove(index);
1834 } else {
1835 return null;
1836 }
1837 }
1838
1839 private int findLockByBinder(IBinder binder) {
1840 int size = mList.size();
1841 for (int i = size - 1; i >= 0; i--)
1842 if (mList.get(i).mBinder == binder)
1843 return i;
1844 return -1;
1845 }
1846
1847 private void dump(PrintWriter pw) {
1848 for (WifiLock l : mList) {
1849 pw.print(" ");
1850 pw.println(l);
1851 }
1852 }
1853 }
1854
1855 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1857 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1858 return false;
1859 }
1860 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1861 synchronized (mLocks) {
1862 return acquireWifiLockLocked(wifiLock);
1863 }
1864 }
1865
1866 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
1867 mLocks.addLock(wifiLock);
The Android Open Source Project10592532009-03-18 17:39:46 -07001868
1869 int uid = Binder.getCallingUid();
1870 long ident = Binder.clearCallingIdentity();
1871 try {
1872 switch(wifiLock.mLockMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001873 case WifiManager.WIFI_MODE_FULL:
1874 ++mFullLocksAcquired;
1875 mBatteryStats.noteFullWifiLockAcquired(uid);
1876 break;
1877 case WifiManager.WIFI_MODE_SCAN_ONLY:
1878 ++mScanLocksAcquired;
1879 mBatteryStats.noteScanWifiLockAcquired(uid);
1880 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001881 }
1882 } catch (RemoteException e) {
1883 } finally {
1884 Binder.restoreCallingIdentity(ident);
1885 }
1886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 updateWifiState();
1888 return true;
1889 }
1890
1891 public boolean releaseWifiLock(IBinder lock) {
1892 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1893 synchronized (mLocks) {
1894 return releaseWifiLockLocked(lock);
1895 }
1896 }
1897
1898 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001899 boolean hadLock;
The Android Open Source Project10592532009-03-18 17:39:46 -07001900
1901 WifiLock wifiLock = mLocks.removeLock(lock);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001902 hadLock = (wifiLock != null);
1903
1904 if (hadLock) {
1905 int uid = Binder.getCallingUid();
1906 long ident = Binder.clearCallingIdentity();
1907 try {
1908 switch(wifiLock.mLockMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001909 case WifiManager.WIFI_MODE_FULL:
1910 ++mFullLocksReleased;
1911 mBatteryStats.noteFullWifiLockReleased(uid);
1912 break;
1913 case WifiManager.WIFI_MODE_SCAN_ONLY:
1914 ++mScanLocksReleased;
1915 mBatteryStats.noteScanWifiLockReleased(uid);
1916 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001917 }
1918 } catch (RemoteException e) {
1919 } finally {
1920 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001921 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001922 }
1923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001925 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 }
1927}