blob: d2f2ec70191078315b26c062b42551b32e992d18 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07002 * Copyright (C) 2010 The Android Open Source Project
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003 *
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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080019import android.app.AlarmManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070020import android.app.Notification;
21import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.app.PendingIntent;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070023import android.bluetooth.BluetoothAdapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.BroadcastReceiver;
25import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070030import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.net.wifi.IWifiManager;
32import android.net.wifi.WifiInfo;
33import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070034import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.wifi.ScanResult;
36import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070037import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080038import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff02fb46a2010-12-08 11:27:37 -080039import android.net.wifi.WpsConfiguration;
Irfan Sheriffe4c56c92011-01-12 16:33:58 -080040import android.net.wifi.WpsResult;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080041import android.net.ConnectivityManager;
42import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070044import android.net.NetworkInfo;
45import android.net.NetworkInfo.State;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070047import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.HandlerThread;
49import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080050import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070051import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070053import android.os.ServiceManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070054import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070056import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080057import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058
Robert Greenwalt04808c22010-12-13 17:01:41 -080059import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080062import java.util.Set;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070063import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.io.FileDescriptor;
65import java.io.PrintWriter;
66
The Android Open Source Project10592532009-03-18 17:39:46 -070067import com.android.internal.app.IBatteryStats;
Wink Saville4b7ba092010-10-20 15:37:41 -070068import com.android.internal.util.AsyncChannel;
The Android Open Source Project10592532009-03-18 17:39:46 -070069import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080070import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072/**
73 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070074 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 *
76 * @hide
77 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070078//TODO: Clean up multiple locks and implement WifiService
79// as a SM to track soft AP/client/adhoc bring up based
80// on device idle state, airplane mode and boot.
81
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082public class WifiService extends IWifiManager.Stub {
83 private static final String TAG = "WifiService";
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070084 private static final boolean DBG = true;
85
Irfan Sheriff0d255342010-07-28 09:35:20 -070086 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087
88 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
90 private AlarmManager mAlarmManager;
91 private PendingIntent mIdleIntent;
92 private static final int IDLE_REQUEST = 0;
93 private boolean mScreenOff;
94 private boolean mDeviceIdle;
95 private int mPluggedType;
96
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070097 // true if the user enabled Wifi while in airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070098 private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700101 // some wifi lock statistics
Irfan Sheriff5876a422010-08-12 20:26:23 -0700102 private int mFullHighPerfLocksAcquired;
103 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700104 private int mFullLocksAcquired;
105 private int mFullLocksReleased;
106 private int mScanLocksAcquired;
107 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700108
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700109 private final List<Multicaster> mMulticasters =
110 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700111 private int mMulticastEnabled;
112 private int mMulticastDisabled;
113
The Android Open Source Project10592532009-03-18 17:39:46 -0700114 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800115
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800116 ConnectivityManager mCm;
117 private String[] mWifiRegexs;
118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800120 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
121 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 * the approximate point at which the battery drain caused by Wi-Fi
123 * being enabled but not active exceeds the battery drain caused by
124 * re-establishing a connection to the mobile data network.
125 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700126 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private static final String ACTION_DEVICE_IDLE =
129 "com.android.server.WifiManager.action.DEVICE_IDLE";
130
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700131 private boolean mIsReceiverRegistered = false;
132
Irfan Sheriff0d255342010-07-28 09:35:20 -0700133
134 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
135
136 // Variables relating to the 'available networks' notification
137 /**
138 * The icon to show in the 'available networks' notification. This will also
139 * be the ID of the Notification given to the NotificationManager.
140 */
141 private static final int ICON_NETWORKS_AVAILABLE =
142 com.android.internal.R.drawable.stat_notify_wifi_in_range;
143 /**
144 * When a notification is shown, we wait this amount before possibly showing it again.
145 */
146 private final long NOTIFICATION_REPEAT_DELAY_MS;
147 /**
148 * Whether the user has set the setting to show the 'available networks' notification.
149 */
150 private boolean mNotificationEnabled;
151 /**
152 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
153 */
154 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
155 /**
156 * The {@link System#currentTimeMillis()} must be at least this value for us
157 * to show the notification again.
158 */
159 private long mNotificationRepeatTime;
160 /**
161 * The Notification object given to the NotificationManager.
162 */
163 private Notification mNotification;
164 /**
165 * Whether the notification is being shown, as set by us. That is, if the
166 * user cancels the notification, we will not receive the callback so this
167 * will still be true. We only guarantee if this is false, then the
168 * notification is not showing.
169 */
170 private boolean mNotificationShown;
171 /**
172 * The number of continuous scans that must occur before consider the
173 * supplicant in a scanning state. This allows supplicant to associate with
174 * remembered networks that are in the scan results.
175 */
176 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
177 /**
178 * The number of scans since the last network state change. When this
179 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
180 * supplicant to actually be scanning. When the network state changes to
181 * something other than scanning, we reset this to 0.
182 */
183 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700184
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700185 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700186 * Asynchronous channel to WifiStateMachine
187 */
188 private AsyncChannel mChannel;
189
190 /**
191 * TODO: Possibly change WifiService into an AsyncService.
192 */
193 private class WifiServiceHandler extends Handler {
194 private AsyncChannel mWshChannel;
195
196 WifiServiceHandler(android.os.Looper looper, Context context) {
197 super(looper);
198 mWshChannel = new AsyncChannel();
Wink Savillecfce3032010-12-01 23:20:25 -0800199 mWshChannel.connect(context, this, mWifiStateMachine.getHandler());
Wink Saville4b7ba092010-10-20 15:37:41 -0700200 }
201
202 @Override
203 public void handleMessage(Message msg) {
204 switch (msg.what) {
205 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
206 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
207 mChannel = mWshChannel;
208 } else {
209 Slog.d(TAG, "WifiServicehandler.handleMessage could not connect error=" +
210 msg.arg1);
211 mChannel = null;
212 }
213 break;
214 }
215 default: {
216 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
217 break;
218 }
219 }
220 }
221 }
222 WifiServiceHandler mHandler;
223
224 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700225 * Temporary for computing UIDS that are responsible for starting WIFI.
226 * Protected by mWifiStateTracker lock.
227 */
228 private final WorkSource mTmpWorkSource = new WorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700229
230 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700232 mWifiStateMachine = new WifiStateMachine(mContext);
233 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700234 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
237 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
238 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
239
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700240 HandlerThread wifiThread = new HandlerThread("WifiService");
241 wifiThread.start();
Wink Saville4b7ba092010-10-20 15:37:41 -0700242 mHandler = new WifiServiceHandler(wifiThread.getLooper(), context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 mContext.registerReceiver(
245 new BroadcastReceiver() {
246 @Override
247 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700248 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700249 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700250 // on airplane disable, restore Wifi if the saved state indicates so
251 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
252 persistWifiEnabled(true);
253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 updateWifiState();
255 }
256 },
257 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
258
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800259 mContext.registerReceiver(
260 new BroadcastReceiver() {
261 @Override
262 public void onReceive(Context context, Intent intent) {
263
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700264 ArrayList<String> available = intent.getStringArrayListExtra(
265 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
266 ArrayList<String> active = intent.getStringArrayListExtra(
267 ConnectivityManager.EXTRA_ACTIVE_TETHER);
268 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800269
270 }
271 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700272
273 IntentFilter filter = new IntentFilter();
274 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
275 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
276 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
277
278 mContext.registerReceiver(
279 new BroadcastReceiver() {
280 @Override
281 public void onReceive(Context context, Intent intent) {
282 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
283 // reset & clear notification on any wifi state change
284 resetNotification();
285 } else if (intent.getAction().equals(
286 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
287 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
288 WifiManager.EXTRA_NETWORK_INFO);
289 // reset & clear notification on a network connect & disconnect
290 switch(mNetworkInfo.getDetailedState()) {
291 case CONNECTED:
292 case DISCONNECTED:
293 resetNotification();
294 break;
295 }
296 } else if (intent.getAction().equals(
297 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
298 checkAndSetNotification();
299 }
300 }
301 }, filter);
302
303 // Setting is in seconds
304 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
305 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
306 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
307 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800308 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800309
Irfan Sheriff7b009782010-03-11 16:37:45 -0800310 /**
311 * Check if Wi-Fi needs to be enabled and start
312 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700313 *
314 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800315 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700316 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700317 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700318 boolean wifiEnabled = !isAirplaneModeOn()
319 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800320 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
321 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700322 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800323 }
324
325 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
326
327 boolean wifiTethered = false;
328 boolean wifiAvailable = false;
329
330 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
331 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
332
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700333 if (mCm == null) {
334 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
335 }
336
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800337 mWifiRegexs = mCm.getTetherableWifiRegexs();
338
339 for (String intf : available) {
340 for (String regex : mWifiRegexs) {
341 if (intf.matches(regex)) {
342
343 InterfaceConfiguration ifcg = null;
344 try {
345 ifcg = service.getInterfaceConfig(intf);
346 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700347 /* IP/netmask: 192.168.43.1/255.255.255.0 */
Robert Greenwalt04808c22010-12-13 17:01:41 -0800348 ifcg.addr = InetAddress.getByName("192.168.43.1");
349 ifcg.mask = InetAddress.getByName("255.255.255.0");
Irfan Sheriff07bd5ae2010-10-28 14:45:56 -0700350 ifcg.interfaceFlags = "[up]";
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800351
352 service.setInterfaceConfig(intf, ifcg);
353 }
354 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800355 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700356 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800357 return;
358 }
359
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800360 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700361 Slog.e(TAG, "Error tethering on " + intf);
362 setWifiApEnabled(null, false);
363 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800364 }
365 break;
366 }
367 }
368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 }
370
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700371 private boolean testAndClearWifiSavedState() {
372 final ContentResolver cr = mContext.getContentResolver();
373 int wifiSavedState = 0;
374 try {
375 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
376 if(wifiSavedState == 1)
377 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
378 } catch (Settings.SettingNotFoundException e) {
379 ;
380 }
381 return (wifiSavedState == 1);
382 }
383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 private boolean getPersistedWifiEnabled() {
385 final ContentResolver cr = mContext.getContentResolver();
386 try {
387 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
388 } catch (Settings.SettingNotFoundException e) {
389 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
390 return false;
391 }
392 }
393
394 private void persistWifiEnabled(boolean enabled) {
395 final ContentResolver cr = mContext.getContentResolver();
396 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
397 }
398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 /**
400 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700401 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 */
403 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700404 enforceAccessPermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700405 if (mChannel != null) {
406 return mWifiStateMachine.syncPingSupplicant(mChannel);
407 } else {
408 Slog.e(TAG, "mChannel is not initialized");
409 return false;
410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 }
412
413 /**
414 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700416 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700418 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 }
420
421 private void enforceAccessPermission() {
422 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
423 "WifiService");
424 }
425
426 private void enforceChangePermission() {
427 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
428 "WifiService");
429
430 }
431
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700432 private void enforceMulticastChangePermission() {
433 mContext.enforceCallingOrSelfPermission(
434 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
435 "WifiService");
436 }
437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700439 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
440 * @param enable {@code true} to enable, {@code false} to disable.
441 * @return {@code true} if the enable/disable operation was
442 * started or is already in the queue.
443 */
444 public synchronized boolean setWifiEnabled(boolean enable) {
445 enforceChangePermission();
446
447 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700448 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700449 }
450
451 // set a flag if the user is enabling Wifi while in airplane mode
452 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
453 mAirplaneModeOverwridden.set(true);
454 }
455
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700456 if (enable) {
457 reportStartWorkSource();
458 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700459 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700460
461 /*
462 * Caller might not have WRITE_SECURE_SETTINGS,
463 * only CHANGE_WIFI_STATE is enforced
464 */
465 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700466 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700467 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700468
469 if (enable) {
470 if (!mIsReceiverRegistered) {
471 registerForBroadcasts();
472 mIsReceiverRegistered = true;
473 }
474 } else if (mIsReceiverRegistered){
475 mContext.unregisterReceiver(mReceiver);
476 mIsReceiverRegistered = false;
477 }
478
479 return true;
480 }
481
482 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 * see {@link WifiManager#getWifiState()}
484 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
485 * {@link WifiManager#WIFI_STATE_DISABLING},
486 * {@link WifiManager#WIFI_STATE_ENABLED},
487 * {@link WifiManager#WIFI_STATE_ENABLING},
488 * {@link WifiManager#WIFI_STATE_UNKNOWN}
489 */
490 public int getWifiEnabledState() {
491 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700492 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 }
494
495 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700496 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800497 * @param wifiConfig SSID, security and channel details as
498 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700499 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800500 * @return {@code true} if the start operation was
501 * started or is already in the queue.
502 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700503 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800504 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800505
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700506 if (enabled) {
507 /* Use default config if there is no existing config */
508 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
509 wifiConfig = new WifiConfiguration();
510 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
511 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
512 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700513 /*
514 * Caller might not have WRITE_SECURE_SETTINGS,
515 * only CHANGE_WIFI_STATE is enforced
516 */
517 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700518 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700519 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800520 }
521
Irfan Sheriff0d255342010-07-28 09:35:20 -0700522 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700523
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800524 return true;
525 }
526
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700527 /**
528 * see {@link WifiManager#getWifiApState()}
529 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
530 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
531 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
532 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
533 * {@link WifiManager#WIFI_AP_STATE_FAILED}
534 */
535 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700536 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700537 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700538 }
539
540 /**
541 * see {@link WifiManager#getWifiApConfiguration()}
542 * @return soft access point configuration
543 */
544 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800545 final ContentResolver cr = mContext.getContentResolver();
546 WifiConfiguration wifiConfig = new WifiConfiguration();
547 int authType;
548 try {
549 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
550 if (wifiConfig.SSID == null)
551 return null;
552 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
553 wifiConfig.allowedKeyManagement.set(authType);
554 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
555 return wifiConfig;
556 } catch (Settings.SettingNotFoundException e) {
557 Slog.e(TAG,"AP settings not found, returning");
558 return null;
559 }
560 }
561
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700562 /**
563 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
564 * @param wifiConfig WifiConfiguration details for soft access point
565 */
566 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700567 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800568 final ContentResolver cr = mContext.getContentResolver();
569 boolean isWpa;
570 if (wifiConfig == null)
571 return;
572 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
573 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
574 Settings.Secure.putInt(cr,
575 Settings.Secure.WIFI_AP_SECURITY,
576 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
577 if (isWpa)
578 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
579 }
580
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800581 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700582 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800583 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700584 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700585 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700586 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800587 }
588
589 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700590 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800591 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700592 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700593 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700594 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800595 }
596
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700597 /**
598 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700599 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700600 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700601 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700602 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800603 }
604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 /**
606 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
607 * @return the list of configured networks
608 */
609 public List<WifiConfiguration> getConfiguredNetworks() {
610 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700611 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800612 }
613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 /**
615 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
616 * @return the supplicant-assigned identifier for the new or updated
617 * network if the operation succeeds, or {@code -1} if it fails
618 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800619 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700621 if (mChannel != null) {
622 return mWifiStateMachine.syncAddOrUpdateNetwork(mChannel, config);
623 } else {
624 Slog.e(TAG, "mChannel is not initialized");
625 return -1;
626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 }
628
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700629 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
631 * @param netId the integer that identifies the network configuration
632 * to the supplicant
633 * @return {@code true} if the operation succeeded
634 */
635 public boolean removeNetwork(int netId) {
636 enforceChangePermission();
Wink Saville4b7ba092010-10-20 15:37:41 -0700637 if (mChannel != null) {
638 return mWifiStateMachine.syncRemoveNetwork(mChannel, netId);
639 } else {
640 Slog.e(TAG, "mChannel is not initialized");
641 return false;
642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 }
644
645 /**
646 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
647 * @param netId the integer that identifies the network configuration
648 * to the supplicant
649 * @param disableOthers if true, disable all other networks.
650 * @return {@code true} if the operation succeeded
651 */
652 public boolean enableNetwork(int netId, boolean disableOthers) {
653 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700654 if (mChannel != null) {
655 return mWifiStateMachine.syncEnableNetwork(mChannel, netId, disableOthers);
656 } else {
657 Slog.e(TAG, "mChannel is not initialized");
658 return false;
659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 }
661
662 /**
663 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
664 * @param netId the integer that identifies the network configuration
665 * to the supplicant
666 * @return {@code true} if the operation succeeded
667 */
668 public boolean disableNetwork(int netId) {
669 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700670 if (mChannel != null) {
671 return mWifiStateMachine.syncDisableNetwork(mChannel, netId);
672 } else {
673 Slog.e(TAG, "mChannel is not initialized");
674 return false;
675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 }
677
678 /**
679 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
680 * @return the Wi-Fi information, contained in {@link WifiInfo}.
681 */
682 public WifiInfo getConnectionInfo() {
683 enforceAccessPermission();
684 /*
685 * Make sure we have the latest information, by sending
686 * a status request to the supplicant.
687 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700688 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 }
690
691 /**
692 * Return the results of the most recent access point scan, in the form of
693 * a list of {@link ScanResult} objects.
694 * @return the list of results
695 */
696 public List<ScanResult> getScanResults() {
697 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700698 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 }
700
701 /**
702 * Tell the supplicant to persist the current list of configured networks.
703 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700704 *
705 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 */
707 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700708 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700710 if (mChannel != null) {
711 return mWifiStateMachine.syncSaveConfig(mChannel);
712 } else {
713 Slog.e(TAG, "mChannel is not initialized");
714 return false;
715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 }
717
718 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700719 * Set the country code
720 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700721 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700722 *
723 * The persist behavior exists so that wifi can fall back to the last
724 * persisted country code on a restart, when the locale information is
725 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700727 public void setCountryCode(String countryCode, boolean persist) {
728 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
729 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700731 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 }
733
734 /**
Irfan Sheriff36f74132010-11-04 16:57:37 -0700735 * Set the operational frequency band
736 * @param band One of
737 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
738 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
739 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
740 * @param persist {@code true} if the setting should be remembered.
741 *
742 */
743 public void setFrequencyBand(int band, boolean persist) {
744 enforceChangePermission();
745 if (!isDualBandSupported()) return;
746 Slog.i(TAG, "WifiService trying to set frequency band to " + band +
747 " with persist set to " + persist);
748 mWifiStateMachine.setFrequencyBand(band, persist);
749 }
750
751
752 /**
753 * Get the operational frequency band
754 */
755 public int getFrequencyBand() {
756 enforceAccessPermission();
757 return mWifiStateMachine.getFrequencyBand();
758 }
759
760 public boolean isDualBandSupported() {
761 //TODO: Should move towards adding a driver API that checks at runtime
762 return mContext.getResources().getBoolean(
763 com.android.internal.R.bool.config_wifi_dual_band_support);
764 }
765
766 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 * Return the DHCP-assigned addresses from the last successful DHCP request,
768 * if any.
769 * @return the DHCP information
770 */
771 public DhcpInfo getDhcpInfo() {
772 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700773 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 }
775
Irfan Sheriff0d255342010-07-28 09:35:20 -0700776 /**
777 * see {@link android.net.wifi.WifiManager#startWifi}
778 *
779 */
780 public void startWifi() {
781 enforceChangePermission();
782 /* TODO: may be add permissions for access only to connectivity service
783 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
784 * of WifiLock & device idle status unless wifi enabled status is toggled
785 */
786
787 mWifiStateMachine.setDriverStart(true);
788 mWifiStateMachine.reconnectCommand();
789 }
790
791 /**
792 * see {@link android.net.wifi.WifiManager#stopWifi}
793 *
794 */
795 public void stopWifi() {
796 enforceChangePermission();
797 /* TODO: may be add permissions for access only to connectivity service
798 * TODO: if a stop is issued, wifi is brought up only by startWifi
799 * unless wifi enabled status is toggled
800 */
801 mWifiStateMachine.setDriverStart(false);
802 }
803
804
805 /**
806 * see {@link android.net.wifi.WifiManager#addToBlacklist}
807 *
808 */
809 public void addToBlacklist(String bssid) {
810 enforceChangePermission();
811
812 mWifiStateMachine.addToBlacklist(bssid);
813 }
814
815 /**
816 * see {@link android.net.wifi.WifiManager#clearBlacklist}
817 *
818 */
819 public void clearBlacklist() {
820 enforceChangePermission();
821
822 mWifiStateMachine.clearBlacklist();
823 }
824
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700825 public void connectNetworkWithId(int networkId) {
826 enforceChangePermission();
827 mWifiStateMachine.connectNetwork(networkId);
828 }
829
830 public void connectNetworkWithConfig(WifiConfiguration config) {
831 enforceChangePermission();
832 mWifiStateMachine.connectNetwork(config);
833 }
834
835 public void saveNetwork(WifiConfiguration config) {
836 enforceChangePermission();
837 mWifiStateMachine.saveNetwork(config);
838 }
839
840 public void forgetNetwork(int netId) {
841 enforceChangePermission();
842 mWifiStateMachine.forgetNetwork(netId);
843 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700844
Irfan Sheriffe4c56c92011-01-12 16:33:58 -0800845 public WpsResult startWps(WpsConfiguration config) {
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700846 enforceChangePermission();
847 if (mChannel != null) {
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800848 return mWifiStateMachine.startWps(mChannel, config);
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700849 } else {
850 Slog.e(TAG, "mChannel is not initialized");
Irfan Sheriffe4c56c92011-01-12 16:33:58 -0800851 return new WpsResult(WpsResult.Status.FAILURE);
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700852 }
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700853 }
854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
856 @Override
857 public void onReceive(Context context, Intent intent) {
858 String action = intent.getAction();
859
Doug Zongker43866e02010-01-07 12:09:54 -0800860 long idleMillis =
861 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700862 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800864 Settings.System.getInt(mContext.getContentResolver(),
865 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400867 if (DBG) {
868 Slog.d(TAG, "ACTION_SCREEN_ON");
869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 mAlarmManager.cancel(mIdleIntent);
871 mDeviceIdle = false;
872 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700873 // Once the screen is on, we are not keeping WIFI running
874 // because of any locks so clear that tracking immediately.
875 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700876 mWifiStateMachine.enableRssiPolling(true);
Irfan Sheriff8e86b892010-12-22 11:02:20 -0800877 mWifiStateMachine.enableAllNetworks();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700878 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400880 if (DBG) {
881 Slog.d(TAG, "ACTION_SCREEN_OFF");
882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700884 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 /*
886 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
887 * AND the "stay on while plugged in" setting doesn't match the
888 * current power conditions (i.e, not plugged in, plugged in to USB,
889 * or plugged in to AC).
890 */
891 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700892 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700893 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700894 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700895 // we don't have time to track down for this release. Delay instead,
896 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700897 // TODO - fix the race conditions and switch back to the immediate turn-off
898 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400899 if (DBG) {
900 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
901 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700902 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
903 // // do not keep Wifi awake when screen is off if Wifi is not associated
904 // mDeviceIdle = true;
905 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400906 } else {
907 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400908 if (DBG) {
909 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
910 + "ms");
911 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400912 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400916 if (DBG) {
917 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700920 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700921 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
923 /*
924 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
925 * AND we are transitioning from a state in which the device was supposed
926 * to stay awake to a state in which it is not supposed to stay awake.
927 * If "stay awake" state is not changing, we do nothing, to avoid resetting
928 * the already-set timer.
929 */
930 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400931 if (DBG) {
932 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
935 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
936 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400937 if (DBG) {
938 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 }
942 mPluggedType = pluggedType;
Irfan Sheriff65eaec82011-01-05 22:00:16 -0800943 } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
944 int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
945 BluetoothAdapter.STATE_DISCONNECTED);
946 mWifiStateMachine.sendBluetoothAdapterStateChange(state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
949
950 /**
951 * Determines whether the Wi-Fi chipset should stay awake or be put to
952 * sleep. Looks at the setting for the sleep policy and the current
953 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800954 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 * @see #shouldDeviceStayAwake(int, int)
956 */
957 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
Irfan Sheriff739f6bc2011-01-28 16:43:12 -0800958 //Never sleep as long as the user has not changed the settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
Irfan Sheriff96b10d62011-01-11 15:40:35 -0800960 Settings.System.WIFI_SLEEP_POLICY,
Irfan Sheriff739f6bc2011-01-28 16:43:12 -0800961 Settings.System.WIFI_SLEEP_POLICY_NEVER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962
963 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
964 // Never sleep
965 return true;
966 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
967 (pluggedType != 0)) {
968 // Never sleep while plugged, and we're plugged
969 return true;
970 } else {
971 // Default
972 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
973 }
974 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 /**
977 * Determine whether the bit value corresponding to {@code pluggedType} is set in
978 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
979 * of {@code 0} isn't really a plugged type, but rather an indication that the
980 * device isn't plugged in at all, there is no bit value corresponding to a
981 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700982 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 * @param stayAwakeConditions a bit string specifying which "plugged types" should
984 * keep the device (and hence Wi-Fi) awake.
985 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
986 * being made
987 * @return {@code true} if {@code pluggedType} indicates that the device is
988 * supposed to stay awake, {@code false} otherwise.
989 */
990 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
991 return (stayAwakeConditions & pluggedType) != 0;
992 }
993 };
994
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700995 private synchronized void reportStartWorkSource() {
996 mTmpWorkSource.clear();
997 if (mDeviceIdle) {
998 for (int i=0; i<mLocks.mList.size(); i++) {
999 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001000 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001001 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001002 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001003 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 private void updateWifiState() {
1006 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001007 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001009 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1011 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001012
1013 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001015 }
1016 /* If device is not idle, lockmode cannot be scan only */
1017 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1019 }
1020
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001021 /* Disable tethering when airplane mode is enabled */
1022 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001023 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001024 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001025
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001026 if (wifiShouldBeEnabled) {
1027 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001028 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001029 mWifiStateMachine.setWifiEnabled(true);
1030 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001031 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001032 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001033 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1034 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001036 mWifiStateMachine.requestCmWakeLock();
1037 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001039 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001040 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
1042 }
1043
1044 private void registerForBroadcasts() {
1045 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1047 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1048 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1049 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001050 intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 mContext.registerReceiver(mReceiver, intentFilter);
1052 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 private boolean isAirplaneSensitive() {
1055 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1056 Settings.System.AIRPLANE_MODE_RADIOS);
1057 return airplaneModeRadios == null
1058 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1059 }
1060
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001061 private boolean isAirplaneToggleable() {
1062 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1063 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1064 return toggleableRadios != null
1065 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1066 }
1067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 /**
1069 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1070 * currently on.
1071 * @return {@code true} if airplane mode is on.
1072 */
1073 private boolean isAirplaneModeOn() {
1074 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1075 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1076 }
1077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 @Override
1079 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1080 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1081 != PackageManager.PERMISSION_GRANTED) {
1082 pw.println("Permission Denial: can't dump WifiService from from pid="
1083 + Binder.getCallingPid()
1084 + ", uid=" + Binder.getCallingUid());
1085 return;
1086 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001087 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 pw.println("Stay-awake conditions: " +
1089 Settings.System.getInt(mContext.getContentResolver(),
1090 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1091 pw.println();
1092
1093 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001094 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 pw.println();
1096 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001097 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 if (scanResults != null && scanResults.size() != 0) {
1099 pw.println(" BSSID Frequency RSSI Flags SSID");
1100 for (ScanResult r : scanResults) {
1101 pw.printf(" %17s %9d %5d %-16s %s%n",
1102 r.BSSID,
1103 r.frequency,
1104 r.level,
1105 r.capabilities,
1106 r.SSID == null ? "" : r.SSID);
1107 }
1108 }
1109 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001110 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001111 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001112 mScanLocksAcquired + " scan");
1113 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001114 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001115 mScanLocksReleased + " scan");
1116 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 pw.println("Locks held:");
1118 mLocks.dump(pw);
1119 }
1120
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001121 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001122 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1123 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
1125
1126 public void binderDied() {
1127 synchronized (mLocks) {
1128 releaseWifiLockLocked(mBinder);
1129 }
1130 }
1131
1132 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001133 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
1135 }
1136
1137 private class LockList {
1138 private List<WifiLock> mList;
1139
1140 private LockList() {
1141 mList = new ArrayList<WifiLock>();
1142 }
1143
1144 private synchronized boolean hasLocks() {
1145 return !mList.isEmpty();
1146 }
1147
1148 private synchronized int getStrongestLockMode() {
1149 if (mList.isEmpty()) {
1150 return WifiManager.WIFI_MODE_FULL;
1151 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001152
1153 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1154 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001156
1157 if (mFullLocksAcquired > mFullLocksReleased) {
1158 return WifiManager.WIFI_MODE_FULL;
1159 }
1160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 return WifiManager.WIFI_MODE_SCAN_ONLY;
1162 }
1163
1164 private void addLock(WifiLock lock) {
1165 if (findLockByBinder(lock.mBinder) < 0) {
1166 mList.add(lock);
1167 }
1168 }
1169
1170 private WifiLock removeLock(IBinder binder) {
1171 int index = findLockByBinder(binder);
1172 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001173 WifiLock ret = mList.remove(index);
1174 ret.unlinkDeathRecipient();
1175 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 } else {
1177 return null;
1178 }
1179 }
1180
1181 private int findLockByBinder(IBinder binder) {
1182 int size = mList.size();
1183 for (int i = size - 1; i >= 0; i--)
1184 if (mList.get(i).mBinder == binder)
1185 return i;
1186 return -1;
1187 }
1188
1189 private void dump(PrintWriter pw) {
1190 for (WifiLock l : mList) {
1191 pw.print(" ");
1192 pw.println(l);
1193 }
1194 }
1195 }
1196
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001197 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001198 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001199 return;
1200 }
1201 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1202 pid, uid, null);
1203 }
1204
1205 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001207 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1208 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1209 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1210 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1211 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 return false;
1213 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001214 if (ws != null && ws.size() == 0) {
1215 ws = null;
1216 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001217 if (ws != null) {
1218 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1219 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001220 if (ws == null) {
1221 ws = new WorkSource(Binder.getCallingUid());
1222 }
1223 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 synchronized (mLocks) {
1225 return acquireWifiLockLocked(wifiLock);
1226 }
1227 }
1228
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001229 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1230 switch(wifiLock.mMode) {
1231 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001232 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001233 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1234 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001235 case WifiManager.WIFI_MODE_SCAN_ONLY:
1236 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1237 break;
1238 }
1239 }
1240
1241 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1242 switch(wifiLock.mMode) {
1243 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001244 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001245 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1246 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001247 case WifiManager.WIFI_MODE_SCAN_ONLY:
1248 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1249 break;
1250 }
1251 }
1252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001254 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001257
The Android Open Source Project10592532009-03-18 17:39:46 -07001258 long ident = Binder.clearCallingIdentity();
1259 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001260 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001261 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001262 case WifiManager.WIFI_MODE_FULL:
1263 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001264 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001265 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1266 ++mFullHighPerfLocksAcquired;
1267 break;
1268
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001269 case WifiManager.WIFI_MODE_SCAN_ONLY:
1270 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001271 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001272 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001273
1274 // Be aggressive about adding new locks into the accounted state...
1275 // we want to over-report rather than under-report.
1276 reportStartWorkSource();
1277
1278 updateWifiState();
1279 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001280 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001281 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001282 } finally {
1283 Binder.restoreCallingIdentity(ident);
1284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 }
1286
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001287 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1288 int uid = Binder.getCallingUid();
1289 int pid = Binder.getCallingPid();
1290 if (ws != null && ws.size() == 0) {
1291 ws = null;
1292 }
1293 if (ws != null) {
1294 enforceWakeSourcePermission(uid, pid);
1295 }
1296 long ident = Binder.clearCallingIdentity();
1297 try {
1298 synchronized (mLocks) {
1299 int index = mLocks.findLockByBinder(lock);
1300 if (index < 0) {
1301 throw new IllegalArgumentException("Wifi lock not active");
1302 }
1303 WifiLock wl = mLocks.mList.get(index);
1304 noteReleaseWifiLock(wl);
1305 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1306 noteAcquireWifiLock(wl);
1307 }
1308 } catch (RemoteException e) {
1309 } finally {
1310 Binder.restoreCallingIdentity(ident);
1311 }
1312 }
1313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 public boolean releaseWifiLock(IBinder lock) {
1315 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1316 synchronized (mLocks) {
1317 return releaseWifiLockLocked(lock);
1318 }
1319 }
1320
1321 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001322 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001323
The Android Open Source Project10592532009-03-18 17:39:46 -07001324 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001325
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001326 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001327
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001328 hadLock = (wifiLock != null);
1329
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001330 long ident = Binder.clearCallingIdentity();
1331 try {
1332 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001333 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001334 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001335 case WifiManager.WIFI_MODE_FULL:
1336 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001337 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001338 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1339 ++mFullHighPerfLocksReleased;
1340 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001341 case WifiManager.WIFI_MODE_SCAN_ONLY:
1342 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001343 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001344 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001345 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001346
1347 // TODO - should this only happen if you hadLock?
1348 updateWifiState();
1349
1350 } catch (RemoteException e) {
1351 } finally {
1352 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001353 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001354
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001355 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001357
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001358 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001359 implements IBinder.DeathRecipient {
1360 String mTag;
1361 int mMode;
1362 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001363 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001364
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001365 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001366 super();
1367 mTag = tag;
1368 mMode = mode;
1369 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001370 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001371 try {
1372 mBinder.linkToDeath(this, 0);
1373 } catch (RemoteException e) {
1374 binderDied();
1375 }
1376 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001377
1378 void unlinkDeathRecipient() {
1379 mBinder.unlinkToDeath(this, 0);
1380 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001381 }
1382
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001383 private class Multicaster extends DeathRecipient {
1384 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001385 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001386 }
1387
1388 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001389 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001390 synchronized (mMulticasters) {
1391 int i = mMulticasters.indexOf(this);
1392 if (i != -1) {
1393 removeMulticasterLocked(i, mMode);
1394 }
1395 }
1396 }
1397
1398 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001399 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001400 }
1401
1402 public int getUid() {
1403 return mMode;
1404 }
1405 }
1406
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001407 public void initializeMulticastFiltering() {
1408 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001409
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001410 synchronized (mMulticasters) {
1411 // if anybody had requested filters be off, leave off
1412 if (mMulticasters.size() != 0) {
1413 return;
1414 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001415 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001416 }
1417 }
1418 }
1419
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001420 public void acquireMulticastLock(IBinder binder, String tag) {
1421 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001422
1423 synchronized (mMulticasters) {
1424 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001425 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001426 // Note that we could call stopPacketFiltering only when
1427 // our new size == 1 (first call), but this function won't
1428 // be called often and by making the stopPacket call each
1429 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001430 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001431 }
1432
1433 int uid = Binder.getCallingUid();
1434 Long ident = Binder.clearCallingIdentity();
1435 try {
1436 mBatteryStats.noteWifiMulticastEnabled(uid);
1437 } catch (RemoteException e) {
1438 } finally {
1439 Binder.restoreCallingIdentity(ident);
1440 }
1441 }
1442
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001443 public void releaseMulticastLock() {
1444 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001445
1446 int uid = Binder.getCallingUid();
1447 synchronized (mMulticasters) {
1448 mMulticastDisabled++;
1449 int size = mMulticasters.size();
1450 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001451 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001452 if ((m != null) && (m.getUid() == uid)) {
1453 removeMulticasterLocked(i, uid);
1454 }
1455 }
1456 }
1457 }
1458
1459 private void removeMulticasterLocked(int i, int uid)
1460 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001461 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001462
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001463 if (removed != null) {
1464 removed.unlinkDeathRecipient();
1465 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001466 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001467 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001468 }
1469
1470 Long ident = Binder.clearCallingIdentity();
1471 try {
1472 mBatteryStats.noteWifiMulticastDisabled(uid);
1473 } catch (RemoteException e) {
1474 } finally {
1475 Binder.restoreCallingIdentity(ident);
1476 }
1477 }
1478
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001479 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001480 enforceAccessPermission();
1481
1482 synchronized (mMulticasters) {
1483 return (mMulticasters.size() > 0);
1484 }
1485 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001486
1487 private void checkAndSetNotification() {
1488 // If we shouldn't place a notification on available networks, then
1489 // don't bother doing any of the following
1490 if (!mNotificationEnabled) return;
1491
1492 State state = mNetworkInfo.getState();
1493 if ((state == NetworkInfo.State.DISCONNECTED)
1494 || (state == NetworkInfo.State.UNKNOWN)) {
1495 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001496 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001497 if (scanResults != null) {
1498 int numOpenNetworks = 0;
1499 for (int i = scanResults.size() - 1; i >= 0; i--) {
1500 ScanResult scanResult = scanResults.get(i);
1501
1502 if (TextUtils.isEmpty(scanResult.capabilities)) {
1503 numOpenNetworks++;
1504 }
1505 }
1506
1507 if (numOpenNetworks > 0) {
1508 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1509 /*
1510 * We've scanned continuously at least
1511 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1512 * probably does not have a remembered network in range,
1513 * since otherwise supplicant would have tried to
1514 * associate and thus resetting this counter.
1515 */
1516 setNotificationVisible(true, numOpenNetworks, false, 0);
1517 }
1518 return;
1519 }
1520 }
1521 }
1522
1523 // No open networks in range, remove the notification
1524 setNotificationVisible(false, 0, false, 0);
1525 }
1526
1527 /**
1528 * Clears variables related to tracking whether a notification has been
1529 * shown recently and clears the current notification.
1530 */
1531 private void resetNotification() {
1532 mNotificationRepeatTime = 0;
1533 mNumScansSinceNetworkStateChange = 0;
1534 setNotificationVisible(false, 0, false, 0);
1535 }
1536
1537 /**
1538 * Display or don't display a notification that there are open Wi-Fi networks.
1539 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1540 * @param numNetworks the number networks seen
1541 * @param force {@code true} to force notification to be shown/not-shown,
1542 * even if it is already shown/not-shown.
1543 * @param delay time in milliseconds after which the notification should be made
1544 * visible or invisible.
1545 */
1546 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1547 int delay) {
1548
1549 // Since we use auto cancel on the notification, when the
1550 // mNetworksAvailableNotificationShown is true, the notification may
1551 // have actually been canceled. However, when it is false we know
1552 // for sure that it is not being shown (it will not be shown any other
1553 // place than here)
1554
1555 // If it should be hidden and it is already hidden, then noop
1556 if (!visible && !mNotificationShown && !force) {
1557 return;
1558 }
1559
1560 NotificationManager notificationManager = (NotificationManager) mContext
1561 .getSystemService(Context.NOTIFICATION_SERVICE);
1562
1563 Message message;
1564 if (visible) {
1565
1566 // Not enough time has passed to show the notification again
1567 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1568 return;
1569 }
1570
1571 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001572 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001573 mNotification = new Notification();
1574 mNotification.when = 0;
1575 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1576 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1577 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1578 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1579 }
1580
1581 CharSequence title = mContext.getResources().getQuantityText(
1582 com.android.internal.R.plurals.wifi_available, numNetworks);
1583 CharSequence details = mContext.getResources().getQuantityText(
1584 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1585 mNotification.tickerText = title;
1586 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1587
1588 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1589
1590 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001591 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001592 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001593 }
1594
Irfan Sheriff0d255342010-07-28 09:35:20 -07001595 mNotificationShown = visible;
1596 }
1597
1598 private class NotificationEnabledSettingObserver extends ContentObserver {
1599
1600 public NotificationEnabledSettingObserver(Handler handler) {
1601 super(handler);
1602 }
1603
1604 public void register() {
1605 ContentResolver cr = mContext.getContentResolver();
1606 cr.registerContentObserver(Settings.Secure.getUriFor(
1607 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1608 mNotificationEnabled = getValue();
1609 }
1610
1611 @Override
1612 public void onChange(boolean selfChange) {
1613 super.onChange(selfChange);
1614
1615 mNotificationEnabled = getValue();
1616 resetNotification();
1617 }
1618
1619 private boolean getValue() {
1620 return Settings.Secure.getInt(mContext.getContentResolver(),
1621 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1622 }
1623 }
1624
1625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626}