blob: cff98928660017eb3acff7dfd2a70d104edcf0ab [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 Sheriff5321aef2010-02-12 12:35:59 -080040import android.net.ConnectivityManager;
41import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070043import android.net.NetworkInfo;
44import android.net.NetworkInfo.State;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070046import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.HandlerThread;
48import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080049import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070050import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070052import android.os.ServiceManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070053import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070055import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080056import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057
Robert Greenwalt04808c22010-12-13 17:01:41 -080058import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080061import java.util.Set;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070062import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.io.FileDescriptor;
64import java.io.PrintWriter;
65
The Android Open Source Project10592532009-03-18 17:39:46 -070066import com.android.internal.app.IBatteryStats;
Wink Saville4b7ba092010-10-20 15:37:41 -070067import com.android.internal.util.AsyncChannel;
The Android Open Source Project10592532009-03-18 17:39:46 -070068import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080069import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071/**
72 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070073 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 *
75 * @hide
76 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070077//TODO: Clean up multiple locks and implement WifiService
78// as a SM to track soft AP/client/adhoc bring up based
79// on device idle state, airplane mode and boot.
80
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081public class WifiService extends IWifiManager.Stub {
82 private static final String TAG = "WifiService";
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070083 private static final boolean DBG = true;
84
Irfan Sheriff0d255342010-07-28 09:35:20 -070085 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
87 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
89 private AlarmManager mAlarmManager;
90 private PendingIntent mIdleIntent;
91 private static final int IDLE_REQUEST = 0;
92 private boolean mScreenOff;
93 private boolean mDeviceIdle;
94 private int mPluggedType;
95
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070096 // true if the user enabled Wifi while in airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070097 private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700100 // some wifi lock statistics
Irfan Sheriff5876a422010-08-12 20:26:23 -0700101 private int mFullHighPerfLocksAcquired;
102 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700103 private int mFullLocksAcquired;
104 private int mFullLocksReleased;
105 private int mScanLocksAcquired;
106 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700107
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700108 private final List<Multicaster> mMulticasters =
109 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700110 private int mMulticastEnabled;
111 private int mMulticastDisabled;
112
The Android Open Source Project10592532009-03-18 17:39:46 -0700113 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800114
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800115 ConnectivityManager mCm;
116 private String[] mWifiRegexs;
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800119 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
120 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * the approximate point at which the battery drain caused by Wi-Fi
122 * being enabled but not active exceeds the battery drain caused by
123 * re-establishing a connection to the mobile data network.
124 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700125 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private static final String ACTION_DEVICE_IDLE =
128 "com.android.server.WifiManager.action.DEVICE_IDLE";
129
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700130 private boolean mIsReceiverRegistered = false;
131
Irfan Sheriff0d255342010-07-28 09:35:20 -0700132
133 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
134
135 // Variables relating to the 'available networks' notification
136 /**
137 * The icon to show in the 'available networks' notification. This will also
138 * be the ID of the Notification given to the NotificationManager.
139 */
140 private static final int ICON_NETWORKS_AVAILABLE =
141 com.android.internal.R.drawable.stat_notify_wifi_in_range;
142 /**
143 * When a notification is shown, we wait this amount before possibly showing it again.
144 */
145 private final long NOTIFICATION_REPEAT_DELAY_MS;
146 /**
147 * Whether the user has set the setting to show the 'available networks' notification.
148 */
149 private boolean mNotificationEnabled;
150 /**
151 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
152 */
153 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
154 /**
155 * The {@link System#currentTimeMillis()} must be at least this value for us
156 * to show the notification again.
157 */
158 private long mNotificationRepeatTime;
159 /**
160 * The Notification object given to the NotificationManager.
161 */
162 private Notification mNotification;
163 /**
164 * Whether the notification is being shown, as set by us. That is, if the
165 * user cancels the notification, we will not receive the callback so this
166 * will still be true. We only guarantee if this is false, then the
167 * notification is not showing.
168 */
169 private boolean mNotificationShown;
170 /**
171 * The number of continuous scans that must occur before consider the
172 * supplicant in a scanning state. This allows supplicant to associate with
173 * remembered networks that are in the scan results.
174 */
175 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
176 /**
177 * The number of scans since the last network state change. When this
178 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
179 * supplicant to actually be scanning. When the network state changes to
180 * something other than scanning, we reset this to 0.
181 */
182 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700183
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700184 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700185 * Asynchronous channel to WifiStateMachine
186 */
187 private AsyncChannel mChannel;
188
189 /**
190 * TODO: Possibly change WifiService into an AsyncService.
191 */
192 private class WifiServiceHandler extends Handler {
193 private AsyncChannel mWshChannel;
194
195 WifiServiceHandler(android.os.Looper looper, Context context) {
196 super(looper);
197 mWshChannel = new AsyncChannel();
Wink Savillecfce3032010-12-01 23:20:25 -0800198 mWshChannel.connect(context, this, mWifiStateMachine.getHandler());
Wink Saville4b7ba092010-10-20 15:37:41 -0700199 }
200
201 @Override
202 public void handleMessage(Message msg) {
203 switch (msg.what) {
204 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
205 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
206 mChannel = mWshChannel;
207 } else {
208 Slog.d(TAG, "WifiServicehandler.handleMessage could not connect error=" +
209 msg.arg1);
210 mChannel = null;
211 }
212 break;
213 }
214 default: {
215 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
216 break;
217 }
218 }
219 }
220 }
221 WifiServiceHandler mHandler;
222
223 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700224 * Temporary for computing UIDS that are responsible for starting WIFI.
225 * Protected by mWifiStateTracker lock.
226 */
227 private final WorkSource mTmpWorkSource = new WorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700228
229 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700231 mWifiStateMachine = new WifiStateMachine(mContext);
232 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700233 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
236 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
237 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
238
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700239 HandlerThread wifiThread = new HandlerThread("WifiService");
240 wifiThread.start();
Wink Saville4b7ba092010-10-20 15:37:41 -0700241 mHandler = new WifiServiceHandler(wifiThread.getLooper(), context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 mContext.registerReceiver(
244 new BroadcastReceiver() {
245 @Override
246 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700247 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700248 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700249 // on airplane disable, restore Wifi if the saved state indicates so
250 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
251 persistWifiEnabled(true);
252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 updateWifiState();
254 }
255 },
256 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
257
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800258 mContext.registerReceiver(
259 new BroadcastReceiver() {
260 @Override
261 public void onReceive(Context context, Intent intent) {
262
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700263 ArrayList<String> available = intent.getStringArrayListExtra(
264 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
265 ArrayList<String> active = intent.getStringArrayListExtra(
266 ConnectivityManager.EXTRA_ACTIVE_TETHER);
267 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800268
269 }
270 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700271
272 IntentFilter filter = new IntentFilter();
273 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
274 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
275 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
276
277 mContext.registerReceiver(
278 new BroadcastReceiver() {
279 @Override
280 public void onReceive(Context context, Intent intent) {
281 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
282 // reset & clear notification on any wifi state change
283 resetNotification();
284 } else if (intent.getAction().equals(
285 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
286 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
287 WifiManager.EXTRA_NETWORK_INFO);
288 // reset & clear notification on a network connect & disconnect
289 switch(mNetworkInfo.getDetailedState()) {
290 case CONNECTED:
291 case DISCONNECTED:
292 resetNotification();
293 break;
294 }
295 } else if (intent.getAction().equals(
296 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
297 checkAndSetNotification();
298 }
299 }
300 }, filter);
301
302 // Setting is in seconds
303 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
304 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
305 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
306 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800307 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800308
Irfan Sheriff7b009782010-03-11 16:37:45 -0800309 /**
310 * Check if Wi-Fi needs to be enabled and start
311 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700312 *
313 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800314 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700315 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700316 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700317 boolean wifiEnabled = !isAirplaneModeOn()
318 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800319 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
320 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700321 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800322 }
323
324 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
325
326 boolean wifiTethered = false;
327 boolean wifiAvailable = false;
328
329 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
330 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
331
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700332 if (mCm == null) {
333 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
334 }
335
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800336 mWifiRegexs = mCm.getTetherableWifiRegexs();
337
338 for (String intf : available) {
339 for (String regex : mWifiRegexs) {
340 if (intf.matches(regex)) {
341
342 InterfaceConfiguration ifcg = null;
343 try {
344 ifcg = service.getInterfaceConfig(intf);
345 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700346 /* IP/netmask: 192.168.43.1/255.255.255.0 */
Robert Greenwalt04808c22010-12-13 17:01:41 -0800347 ifcg.addr = InetAddress.getByName("192.168.43.1");
348 ifcg.mask = InetAddress.getByName("255.255.255.0");
Irfan Sheriff07bd5ae2010-10-28 14:45:56 -0700349 ifcg.interfaceFlags = "[up]";
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800350
351 service.setInterfaceConfig(intf, ifcg);
352 }
353 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800354 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700355 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800356 return;
357 }
358
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800359 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700360 Slog.e(TAG, "Error tethering on " + intf);
361 setWifiApEnabled(null, false);
362 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800363 }
364 break;
365 }
366 }
367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 }
369
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700370 private boolean testAndClearWifiSavedState() {
371 final ContentResolver cr = mContext.getContentResolver();
372 int wifiSavedState = 0;
373 try {
374 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
375 if(wifiSavedState == 1)
376 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
377 } catch (Settings.SettingNotFoundException e) {
378 ;
379 }
380 return (wifiSavedState == 1);
381 }
382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 private boolean getPersistedWifiEnabled() {
384 final ContentResolver cr = mContext.getContentResolver();
385 try {
386 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
387 } catch (Settings.SettingNotFoundException e) {
388 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
389 return false;
390 }
391 }
392
393 private void persistWifiEnabled(boolean enabled) {
394 final ContentResolver cr = mContext.getContentResolver();
395 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
396 }
397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 /**
399 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700400 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 */
402 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700403 enforceAccessPermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700404 if (mChannel != null) {
405 return mWifiStateMachine.syncPingSupplicant(mChannel);
406 } else {
407 Slog.e(TAG, "mChannel is not initialized");
408 return false;
409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 }
411
412 /**
413 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700415 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700417 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 }
419
420 private void enforceAccessPermission() {
421 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
422 "WifiService");
423 }
424
425 private void enforceChangePermission() {
426 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
427 "WifiService");
428
429 }
430
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700431 private void enforceMulticastChangePermission() {
432 mContext.enforceCallingOrSelfPermission(
433 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
434 "WifiService");
435 }
436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700438 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
439 * @param enable {@code true} to enable, {@code false} to disable.
440 * @return {@code true} if the enable/disable operation was
441 * started or is already in the queue.
442 */
443 public synchronized boolean setWifiEnabled(boolean enable) {
444 enforceChangePermission();
445
446 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700447 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700448 }
449
450 // set a flag if the user is enabling Wifi while in airplane mode
451 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
452 mAirplaneModeOverwridden.set(true);
453 }
454
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700455 if (enable) {
456 reportStartWorkSource();
457 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700458 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700459
460 /*
461 * Caller might not have WRITE_SECURE_SETTINGS,
462 * only CHANGE_WIFI_STATE is enforced
463 */
464 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700465 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700466 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700467
468 if (enable) {
469 if (!mIsReceiverRegistered) {
470 registerForBroadcasts();
471 mIsReceiverRegistered = true;
472 }
473 } else if (mIsReceiverRegistered){
474 mContext.unregisterReceiver(mReceiver);
475 mIsReceiverRegistered = false;
476 }
477
478 return true;
479 }
480
481 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 * see {@link WifiManager#getWifiState()}
483 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
484 * {@link WifiManager#WIFI_STATE_DISABLING},
485 * {@link WifiManager#WIFI_STATE_ENABLED},
486 * {@link WifiManager#WIFI_STATE_ENABLING},
487 * {@link WifiManager#WIFI_STATE_UNKNOWN}
488 */
489 public int getWifiEnabledState() {
490 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700491 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
493
494 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700495 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800496 * @param wifiConfig SSID, security and channel details as
497 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700498 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800499 * @return {@code true} if the start operation was
500 * started or is already in the queue.
501 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700502 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800503 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800504
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700505 if (enabled) {
506 /* Use default config if there is no existing config */
507 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
508 wifiConfig = new WifiConfiguration();
509 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
510 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
511 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700512 /*
513 * Caller might not have WRITE_SECURE_SETTINGS,
514 * only CHANGE_WIFI_STATE is enforced
515 */
516 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700517 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700518 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800519 }
520
Irfan Sheriff0d255342010-07-28 09:35:20 -0700521 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700522
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800523 return true;
524 }
525
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700526 /**
527 * see {@link WifiManager#getWifiApState()}
528 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
529 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
530 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
531 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
532 * {@link WifiManager#WIFI_AP_STATE_FAILED}
533 */
534 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700535 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700536 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700537 }
538
539 /**
540 * see {@link WifiManager#getWifiApConfiguration()}
541 * @return soft access point configuration
542 */
543 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800544 final ContentResolver cr = mContext.getContentResolver();
545 WifiConfiguration wifiConfig = new WifiConfiguration();
546 int authType;
547 try {
548 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
549 if (wifiConfig.SSID == null)
550 return null;
551 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
552 wifiConfig.allowedKeyManagement.set(authType);
553 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
554 return wifiConfig;
555 } catch (Settings.SettingNotFoundException e) {
556 Slog.e(TAG,"AP settings not found, returning");
557 return null;
558 }
559 }
560
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700561 /**
562 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
563 * @param wifiConfig WifiConfiguration details for soft access point
564 */
565 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700566 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800567 final ContentResolver cr = mContext.getContentResolver();
568 boolean isWpa;
569 if (wifiConfig == null)
570 return;
571 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
572 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
573 Settings.Secure.putInt(cr,
574 Settings.Secure.WIFI_AP_SECURITY,
575 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
576 if (isWpa)
577 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
578 }
579
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800580 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700581 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800582 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700583 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700584 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700585 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800586 }
587
588 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700589 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800590 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700591 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700592 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700593 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800594 }
595
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700596 /**
597 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700598 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700599 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700600 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700601 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800602 }
603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 /**
605 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
606 * @return the list of configured networks
607 */
608 public List<WifiConfiguration> getConfiguredNetworks() {
609 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700610 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800611 }
612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 /**
614 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
615 * @return the supplicant-assigned identifier for the new or updated
616 * network if the operation succeeds, or {@code -1} if it fails
617 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800618 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700620 if (mChannel != null) {
621 return mWifiStateMachine.syncAddOrUpdateNetwork(mChannel, config);
622 } else {
623 Slog.e(TAG, "mChannel is not initialized");
624 return -1;
625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 }
627
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700628 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
630 * @param netId the integer that identifies the network configuration
631 * to the supplicant
632 * @return {@code true} if the operation succeeded
633 */
634 public boolean removeNetwork(int netId) {
635 enforceChangePermission();
Wink Saville4b7ba092010-10-20 15:37:41 -0700636 if (mChannel != null) {
637 return mWifiStateMachine.syncRemoveNetwork(mChannel, netId);
638 } else {
639 Slog.e(TAG, "mChannel is not initialized");
640 return false;
641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 }
643
644 /**
645 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
646 * @param netId the integer that identifies the network configuration
647 * to the supplicant
648 * @param disableOthers if true, disable all other networks.
649 * @return {@code true} if the operation succeeded
650 */
651 public boolean enableNetwork(int netId, boolean disableOthers) {
652 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700653 if (mChannel != null) {
654 return mWifiStateMachine.syncEnableNetwork(mChannel, netId, disableOthers);
655 } else {
656 Slog.e(TAG, "mChannel is not initialized");
657 return false;
658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 }
660
661 /**
662 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
663 * @param netId the integer that identifies the network configuration
664 * to the supplicant
665 * @return {@code true} if the operation succeeded
666 */
667 public boolean disableNetwork(int netId) {
668 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700669 if (mChannel != null) {
670 return mWifiStateMachine.syncDisableNetwork(mChannel, netId);
671 } else {
672 Slog.e(TAG, "mChannel is not initialized");
673 return false;
674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 }
676
677 /**
678 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
679 * @return the Wi-Fi information, contained in {@link WifiInfo}.
680 */
681 public WifiInfo getConnectionInfo() {
682 enforceAccessPermission();
683 /*
684 * Make sure we have the latest information, by sending
685 * a status request to the supplicant.
686 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700687 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 }
689
690 /**
691 * Return the results of the most recent access point scan, in the form of
692 * a list of {@link ScanResult} objects.
693 * @return the list of results
694 */
695 public List<ScanResult> getScanResults() {
696 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700697 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 }
699
700 /**
701 * Tell the supplicant to persist the current list of configured networks.
702 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700703 *
704 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 */
706 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700707 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700709 if (mChannel != null) {
710 return mWifiStateMachine.syncSaveConfig(mChannel);
711 } else {
712 Slog.e(TAG, "mChannel is not initialized");
713 return false;
714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 }
716
717 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700718 * Set the country code
719 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700720 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700721 *
722 * The persist behavior exists so that wifi can fall back to the last
723 * persisted country code on a restart, when the locale information is
724 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700726 public void setCountryCode(String countryCode, boolean persist) {
727 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
728 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700730 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 }
732
733 /**
Irfan Sheriff36f74132010-11-04 16:57:37 -0700734 * Set the operational frequency band
735 * @param band One of
736 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
737 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
738 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
739 * @param persist {@code true} if the setting should be remembered.
740 *
741 */
742 public void setFrequencyBand(int band, boolean persist) {
743 enforceChangePermission();
744 if (!isDualBandSupported()) return;
745 Slog.i(TAG, "WifiService trying to set frequency band to " + band +
746 " with persist set to " + persist);
747 mWifiStateMachine.setFrequencyBand(band, persist);
748 }
749
750
751 /**
752 * Get the operational frequency band
753 */
754 public int getFrequencyBand() {
755 enforceAccessPermission();
756 return mWifiStateMachine.getFrequencyBand();
757 }
758
759 public boolean isDualBandSupported() {
760 //TODO: Should move towards adding a driver API that checks at runtime
761 return mContext.getResources().getBoolean(
762 com.android.internal.R.bool.config_wifi_dual_band_support);
763 }
764
765 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 * Return the DHCP-assigned addresses from the last successful DHCP request,
767 * if any.
768 * @return the DHCP information
769 */
770 public DhcpInfo getDhcpInfo() {
771 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700772 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 }
774
Irfan Sheriff0d255342010-07-28 09:35:20 -0700775 /**
776 * see {@link android.net.wifi.WifiManager#startWifi}
777 *
778 */
779 public void startWifi() {
780 enforceChangePermission();
781 /* TODO: may be add permissions for access only to connectivity service
782 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
783 * of WifiLock & device idle status unless wifi enabled status is toggled
784 */
785
786 mWifiStateMachine.setDriverStart(true);
787 mWifiStateMachine.reconnectCommand();
788 }
789
790 /**
791 * see {@link android.net.wifi.WifiManager#stopWifi}
792 *
793 */
794 public void stopWifi() {
795 enforceChangePermission();
796 /* TODO: may be add permissions for access only to connectivity service
797 * TODO: if a stop is issued, wifi is brought up only by startWifi
798 * unless wifi enabled status is toggled
799 */
800 mWifiStateMachine.setDriverStart(false);
801 }
802
803
804 /**
805 * see {@link android.net.wifi.WifiManager#addToBlacklist}
806 *
807 */
808 public void addToBlacklist(String bssid) {
809 enforceChangePermission();
810
811 mWifiStateMachine.addToBlacklist(bssid);
812 }
813
814 /**
815 * see {@link android.net.wifi.WifiManager#clearBlacklist}
816 *
817 */
818 public void clearBlacklist() {
819 enforceChangePermission();
820
821 mWifiStateMachine.clearBlacklist();
822 }
823
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700824 public void connectNetworkWithId(int networkId) {
825 enforceChangePermission();
826 mWifiStateMachine.connectNetwork(networkId);
827 }
828
829 public void connectNetworkWithConfig(WifiConfiguration config) {
830 enforceChangePermission();
831 mWifiStateMachine.connectNetwork(config);
832 }
833
834 public void saveNetwork(WifiConfiguration config) {
835 enforceChangePermission();
836 mWifiStateMachine.saveNetwork(config);
837 }
838
839 public void forgetNetwork(int netId) {
840 enforceChangePermission();
841 mWifiStateMachine.forgetNetwork(netId);
842 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700843
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800844 public String startWps(WpsConfiguration config) {
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700845 enforceChangePermission();
846 if (mChannel != null) {
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800847 return mWifiStateMachine.startWps(mChannel, config);
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700848 } else {
849 Slog.e(TAG, "mChannel is not initialized");
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800850 return "";
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700851 }
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700852 }
853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
855 @Override
856 public void onReceive(Context context, Intent intent) {
857 String action = intent.getAction();
858
Doug Zongker43866e02010-01-07 12:09:54 -0800859 long idleMillis =
860 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700861 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800863 Settings.System.getInt(mContext.getContentResolver(),
864 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400866 if (DBG) {
867 Slog.d(TAG, "ACTION_SCREEN_ON");
868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 mAlarmManager.cancel(mIdleIntent);
870 mDeviceIdle = false;
871 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700872 // Once the screen is on, we are not keeping WIFI running
873 // because of any locks so clear that tracking immediately.
874 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700875 mWifiStateMachine.enableRssiPolling(true);
Irfan Sheriff8e86b892010-12-22 11:02:20 -0800876 mWifiStateMachine.enableAllNetworks();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700877 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400879 if (DBG) {
880 Slog.d(TAG, "ACTION_SCREEN_OFF");
881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700883 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 /*
885 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
886 * AND the "stay on while plugged in" setting doesn't match the
887 * current power conditions (i.e, not plugged in, plugged in to USB,
888 * or plugged in to AC).
889 */
890 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700891 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700892 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700893 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700894 // we don't have time to track down for this release. Delay instead,
895 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700896 // TODO - fix the race conditions and switch back to the immediate turn-off
897 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400898 if (DBG) {
899 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
900 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700901 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
902 // // do not keep Wifi awake when screen is off if Wifi is not associated
903 // mDeviceIdle = true;
904 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400905 } else {
906 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400907 if (DBG) {
908 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
909 + "ms");
910 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400911 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400915 if (DBG) {
916 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700919 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700920 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
922 /*
923 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
924 * AND we are transitioning from a state in which the device was supposed
925 * to stay awake to a state in which it is not supposed to stay awake.
926 * If "stay awake" state is not changing, we do nothing, to avoid resetting
927 * the already-set timer.
928 */
929 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400930 if (DBG) {
931 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
934 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
935 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400936 if (DBG) {
937 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 }
941 mPluggedType = pluggedType;
Irfan Sheriff65eaec82011-01-05 22:00:16 -0800942 } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
943 int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
944 BluetoothAdapter.STATE_DISCONNECTED);
945 mWifiStateMachine.sendBluetoothAdapterStateChange(state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 }
948
949 /**
950 * Determines whether the Wi-Fi chipset should stay awake or be put to
951 * sleep. Looks at the setting for the sleep policy and the current
952 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800953 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 * @see #shouldDeviceStayAwake(int, int)
955 */
956 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
957 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
958 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
959
960 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
961 // Never sleep
962 return true;
963 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
964 (pluggedType != 0)) {
965 // Never sleep while plugged, and we're plugged
966 return true;
967 } else {
968 // Default
969 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
970 }
971 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 /**
974 * Determine whether the bit value corresponding to {@code pluggedType} is set in
975 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
976 * of {@code 0} isn't really a plugged type, but rather an indication that the
977 * device isn't plugged in at all, there is no bit value corresponding to a
978 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700979 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 * @param stayAwakeConditions a bit string specifying which "plugged types" should
981 * keep the device (and hence Wi-Fi) awake.
982 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
983 * being made
984 * @return {@code true} if {@code pluggedType} indicates that the device is
985 * supposed to stay awake, {@code false} otherwise.
986 */
987 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
988 return (stayAwakeConditions & pluggedType) != 0;
989 }
990 };
991
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700992 private synchronized void reportStartWorkSource() {
993 mTmpWorkSource.clear();
994 if (mDeviceIdle) {
995 for (int i=0; i<mLocks.mList.size(); i++) {
996 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700997 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700998 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700999 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001000 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 private void updateWifiState() {
1003 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001004 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001006 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1008 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001009
1010 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001012 }
1013 /* If device is not idle, lockmode cannot be scan only */
1014 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1016 }
1017
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001018 /* Disable tethering when airplane mode is enabled */
1019 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001020 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001021 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001022
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001023 if (wifiShouldBeEnabled) {
1024 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001025 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001026 mWifiStateMachine.setWifiEnabled(true);
1027 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001028 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001029 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001030 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1031 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001033 mWifiStateMachine.requestCmWakeLock();
1034 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001036 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001037 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039 }
1040
1041 private void registerForBroadcasts() {
1042 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1044 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1045 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1046 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001047 intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 mContext.registerReceiver(mReceiver, intentFilter);
1049 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 private boolean isAirplaneSensitive() {
1052 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1053 Settings.System.AIRPLANE_MODE_RADIOS);
1054 return airplaneModeRadios == null
1055 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1056 }
1057
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001058 private boolean isAirplaneToggleable() {
1059 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1060 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1061 return toggleableRadios != null
1062 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1063 }
1064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 /**
1066 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1067 * currently on.
1068 * @return {@code true} if airplane mode is on.
1069 */
1070 private boolean isAirplaneModeOn() {
1071 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1072 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1073 }
1074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 @Override
1076 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1077 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1078 != PackageManager.PERMISSION_GRANTED) {
1079 pw.println("Permission Denial: can't dump WifiService from from pid="
1080 + Binder.getCallingPid()
1081 + ", uid=" + Binder.getCallingUid());
1082 return;
1083 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001084 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 pw.println("Stay-awake conditions: " +
1086 Settings.System.getInt(mContext.getContentResolver(),
1087 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1088 pw.println();
1089
1090 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001091 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 pw.println();
1093 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001094 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 if (scanResults != null && scanResults.size() != 0) {
1096 pw.println(" BSSID Frequency RSSI Flags SSID");
1097 for (ScanResult r : scanResults) {
1098 pw.printf(" %17s %9d %5d %-16s %s%n",
1099 r.BSSID,
1100 r.frequency,
1101 r.level,
1102 r.capabilities,
1103 r.SSID == null ? "" : r.SSID);
1104 }
1105 }
1106 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001107 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001108 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001109 mScanLocksAcquired + " scan");
1110 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001111 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001112 mScanLocksReleased + " scan");
1113 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 pw.println("Locks held:");
1115 mLocks.dump(pw);
1116 }
1117
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001118 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001119 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1120 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
1122
1123 public void binderDied() {
1124 synchronized (mLocks) {
1125 releaseWifiLockLocked(mBinder);
1126 }
1127 }
1128
1129 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001130 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 }
1132 }
1133
1134 private class LockList {
1135 private List<WifiLock> mList;
1136
1137 private LockList() {
1138 mList = new ArrayList<WifiLock>();
1139 }
1140
1141 private synchronized boolean hasLocks() {
1142 return !mList.isEmpty();
1143 }
1144
1145 private synchronized int getStrongestLockMode() {
1146 if (mList.isEmpty()) {
1147 return WifiManager.WIFI_MODE_FULL;
1148 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001149
1150 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1151 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001153
1154 if (mFullLocksAcquired > mFullLocksReleased) {
1155 return WifiManager.WIFI_MODE_FULL;
1156 }
1157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 return WifiManager.WIFI_MODE_SCAN_ONLY;
1159 }
1160
1161 private void addLock(WifiLock lock) {
1162 if (findLockByBinder(lock.mBinder) < 0) {
1163 mList.add(lock);
1164 }
1165 }
1166
1167 private WifiLock removeLock(IBinder binder) {
1168 int index = findLockByBinder(binder);
1169 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001170 WifiLock ret = mList.remove(index);
1171 ret.unlinkDeathRecipient();
1172 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 } else {
1174 return null;
1175 }
1176 }
1177
1178 private int findLockByBinder(IBinder binder) {
1179 int size = mList.size();
1180 for (int i = size - 1; i >= 0; i--)
1181 if (mList.get(i).mBinder == binder)
1182 return i;
1183 return -1;
1184 }
1185
1186 private void dump(PrintWriter pw) {
1187 for (WifiLock l : mList) {
1188 pw.print(" ");
1189 pw.println(l);
1190 }
1191 }
1192 }
1193
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001194 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001195 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001196 return;
1197 }
1198 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1199 pid, uid, null);
1200 }
1201
1202 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001204 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1205 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1206 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1207 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1208 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 return false;
1210 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001211 if (ws != null && ws.size() == 0) {
1212 ws = null;
1213 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001214 if (ws != null) {
1215 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1216 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001217 if (ws == null) {
1218 ws = new WorkSource(Binder.getCallingUid());
1219 }
1220 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 synchronized (mLocks) {
1222 return acquireWifiLockLocked(wifiLock);
1223 }
1224 }
1225
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001226 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1227 switch(wifiLock.mMode) {
1228 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001229 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001230 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1231 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001232 case WifiManager.WIFI_MODE_SCAN_ONLY:
1233 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1234 break;
1235 }
1236 }
1237
1238 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1239 switch(wifiLock.mMode) {
1240 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001241 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001242 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1243 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001244 case WifiManager.WIFI_MODE_SCAN_ONLY:
1245 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1246 break;
1247 }
1248 }
1249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001251 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001254
The Android Open Source Project10592532009-03-18 17:39:46 -07001255 long ident = Binder.clearCallingIdentity();
1256 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001257 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001258 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001259 case WifiManager.WIFI_MODE_FULL:
1260 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001261 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001262 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1263 ++mFullHighPerfLocksAcquired;
1264 break;
1265
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001266 case WifiManager.WIFI_MODE_SCAN_ONLY:
1267 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001268 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001269 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001270
1271 // Be aggressive about adding new locks into the accounted state...
1272 // we want to over-report rather than under-report.
1273 reportStartWorkSource();
1274
1275 updateWifiState();
1276 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001277 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001278 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001279 } finally {
1280 Binder.restoreCallingIdentity(ident);
1281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 }
1283
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001284 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1285 int uid = Binder.getCallingUid();
1286 int pid = Binder.getCallingPid();
1287 if (ws != null && ws.size() == 0) {
1288 ws = null;
1289 }
1290 if (ws != null) {
1291 enforceWakeSourcePermission(uid, pid);
1292 }
1293 long ident = Binder.clearCallingIdentity();
1294 try {
1295 synchronized (mLocks) {
1296 int index = mLocks.findLockByBinder(lock);
1297 if (index < 0) {
1298 throw new IllegalArgumentException("Wifi lock not active");
1299 }
1300 WifiLock wl = mLocks.mList.get(index);
1301 noteReleaseWifiLock(wl);
1302 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1303 noteAcquireWifiLock(wl);
1304 }
1305 } catch (RemoteException e) {
1306 } finally {
1307 Binder.restoreCallingIdentity(ident);
1308 }
1309 }
1310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 public boolean releaseWifiLock(IBinder lock) {
1312 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1313 synchronized (mLocks) {
1314 return releaseWifiLockLocked(lock);
1315 }
1316 }
1317
1318 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001319 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001320
The Android Open Source Project10592532009-03-18 17:39:46 -07001321 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001322
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001323 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001324
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001325 hadLock = (wifiLock != null);
1326
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001327 long ident = Binder.clearCallingIdentity();
1328 try {
1329 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001330 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001331 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001332 case WifiManager.WIFI_MODE_FULL:
1333 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001334 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001335 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1336 ++mFullHighPerfLocksReleased;
1337 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001338 case WifiManager.WIFI_MODE_SCAN_ONLY:
1339 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001340 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001341 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001342 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001343
1344 // TODO - should this only happen if you hadLock?
1345 updateWifiState();
1346
1347 } catch (RemoteException e) {
1348 } finally {
1349 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001350 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001351
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001352 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001354
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001355 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001356 implements IBinder.DeathRecipient {
1357 String mTag;
1358 int mMode;
1359 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001360 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001361
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001362 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001363 super();
1364 mTag = tag;
1365 mMode = mode;
1366 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001367 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001368 try {
1369 mBinder.linkToDeath(this, 0);
1370 } catch (RemoteException e) {
1371 binderDied();
1372 }
1373 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001374
1375 void unlinkDeathRecipient() {
1376 mBinder.unlinkToDeath(this, 0);
1377 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001378 }
1379
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001380 private class Multicaster extends DeathRecipient {
1381 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001382 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001383 }
1384
1385 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001386 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001387 synchronized (mMulticasters) {
1388 int i = mMulticasters.indexOf(this);
1389 if (i != -1) {
1390 removeMulticasterLocked(i, mMode);
1391 }
1392 }
1393 }
1394
1395 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001396 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001397 }
1398
1399 public int getUid() {
1400 return mMode;
1401 }
1402 }
1403
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001404 public void initializeMulticastFiltering() {
1405 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001406
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001407 synchronized (mMulticasters) {
1408 // if anybody had requested filters be off, leave off
1409 if (mMulticasters.size() != 0) {
1410 return;
1411 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001412 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001413 }
1414 }
1415 }
1416
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001417 public void acquireMulticastLock(IBinder binder, String tag) {
1418 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001419
1420 synchronized (mMulticasters) {
1421 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001422 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001423 // Note that we could call stopPacketFiltering only when
1424 // our new size == 1 (first call), but this function won't
1425 // be called often and by making the stopPacket call each
1426 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001427 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001428 }
1429
1430 int uid = Binder.getCallingUid();
1431 Long ident = Binder.clearCallingIdentity();
1432 try {
1433 mBatteryStats.noteWifiMulticastEnabled(uid);
1434 } catch (RemoteException e) {
1435 } finally {
1436 Binder.restoreCallingIdentity(ident);
1437 }
1438 }
1439
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001440 public void releaseMulticastLock() {
1441 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001442
1443 int uid = Binder.getCallingUid();
1444 synchronized (mMulticasters) {
1445 mMulticastDisabled++;
1446 int size = mMulticasters.size();
1447 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001448 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001449 if ((m != null) && (m.getUid() == uid)) {
1450 removeMulticasterLocked(i, uid);
1451 }
1452 }
1453 }
1454 }
1455
1456 private void removeMulticasterLocked(int i, int uid)
1457 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001458 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001459
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001460 if (removed != null) {
1461 removed.unlinkDeathRecipient();
1462 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001463 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001464 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001465 }
1466
1467 Long ident = Binder.clearCallingIdentity();
1468 try {
1469 mBatteryStats.noteWifiMulticastDisabled(uid);
1470 } catch (RemoteException e) {
1471 } finally {
1472 Binder.restoreCallingIdentity(ident);
1473 }
1474 }
1475
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001476 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001477 enforceAccessPermission();
1478
1479 synchronized (mMulticasters) {
1480 return (mMulticasters.size() > 0);
1481 }
1482 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001483
1484 private void checkAndSetNotification() {
1485 // If we shouldn't place a notification on available networks, then
1486 // don't bother doing any of the following
1487 if (!mNotificationEnabled) return;
1488
1489 State state = mNetworkInfo.getState();
1490 if ((state == NetworkInfo.State.DISCONNECTED)
1491 || (state == NetworkInfo.State.UNKNOWN)) {
1492 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001493 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001494 if (scanResults != null) {
1495 int numOpenNetworks = 0;
1496 for (int i = scanResults.size() - 1; i >= 0; i--) {
1497 ScanResult scanResult = scanResults.get(i);
1498
1499 if (TextUtils.isEmpty(scanResult.capabilities)) {
1500 numOpenNetworks++;
1501 }
1502 }
1503
1504 if (numOpenNetworks > 0) {
1505 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1506 /*
1507 * We've scanned continuously at least
1508 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1509 * probably does not have a remembered network in range,
1510 * since otherwise supplicant would have tried to
1511 * associate and thus resetting this counter.
1512 */
1513 setNotificationVisible(true, numOpenNetworks, false, 0);
1514 }
1515 return;
1516 }
1517 }
1518 }
1519
1520 // No open networks in range, remove the notification
1521 setNotificationVisible(false, 0, false, 0);
1522 }
1523
1524 /**
1525 * Clears variables related to tracking whether a notification has been
1526 * shown recently and clears the current notification.
1527 */
1528 private void resetNotification() {
1529 mNotificationRepeatTime = 0;
1530 mNumScansSinceNetworkStateChange = 0;
1531 setNotificationVisible(false, 0, false, 0);
1532 }
1533
1534 /**
1535 * Display or don't display a notification that there are open Wi-Fi networks.
1536 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1537 * @param numNetworks the number networks seen
1538 * @param force {@code true} to force notification to be shown/not-shown,
1539 * even if it is already shown/not-shown.
1540 * @param delay time in milliseconds after which the notification should be made
1541 * visible or invisible.
1542 */
1543 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1544 int delay) {
1545
1546 // Since we use auto cancel on the notification, when the
1547 // mNetworksAvailableNotificationShown is true, the notification may
1548 // have actually been canceled. However, when it is false we know
1549 // for sure that it is not being shown (it will not be shown any other
1550 // place than here)
1551
1552 // If it should be hidden and it is already hidden, then noop
1553 if (!visible && !mNotificationShown && !force) {
1554 return;
1555 }
1556
1557 NotificationManager notificationManager = (NotificationManager) mContext
1558 .getSystemService(Context.NOTIFICATION_SERVICE);
1559
1560 Message message;
1561 if (visible) {
1562
1563 // Not enough time has passed to show the notification again
1564 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1565 return;
1566 }
1567
1568 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001569 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001570 mNotification = new Notification();
1571 mNotification.when = 0;
1572 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1573 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1574 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1575 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1576 }
1577
1578 CharSequence title = mContext.getResources().getQuantityText(
1579 com.android.internal.R.plurals.wifi_available, numNetworks);
1580 CharSequence details = mContext.getResources().getQuantityText(
1581 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1582 mNotification.tickerText = title;
1583 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1584
1585 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1586
1587 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001588 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001589 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001590 }
1591
Irfan Sheriff0d255342010-07-28 09:35:20 -07001592 mNotificationShown = visible;
1593 }
1594
1595 private class NotificationEnabledSettingObserver extends ContentObserver {
1596
1597 public NotificationEnabledSettingObserver(Handler handler) {
1598 super(handler);
1599 }
1600
1601 public void register() {
1602 ContentResolver cr = mContext.getContentResolver();
1603 cr.registerContentObserver(Settings.Secure.getUriFor(
1604 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1605 mNotificationEnabled = getValue();
1606 }
1607
1608 @Override
1609 public void onChange(boolean selfChange) {
1610 super.onChange(selfChange);
1611
1612 mNotificationEnabled = getValue();
1613 resetNotification();
1614 }
1615
1616 private boolean getValue() {
1617 return Settings.Secure.getInt(mContext.getContentResolver(),
1618 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1619 }
1620 }
1621
1622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623}