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