blob: 853e46d975d243f34201b4eef76bf6e0d1f0ddcc [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;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070023import android.bluetooth.BluetoothA2dp;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070024import android.bluetooth.BluetoothAdapter;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080025import android.bluetooth.BluetoothDevice;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070026import android.bluetooth.BluetoothProfile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.BroadcastReceiver;
28import android.content.ContentResolver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.net.wifi.IWifiManager;
35import android.net.wifi.WifiInfo;
36import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070037import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.net.wifi.ScanResult;
39import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070040import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080041import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080042import android.net.ConnectivityManager;
43import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070045import android.net.NetworkInfo;
46import android.net.NetworkInfo.State;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070048import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.HandlerThread;
50import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080051import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070052import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070054import android.os.ServiceManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070055import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070057import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080058import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
60import 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;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070092 private BluetoothA2dp mBluetoothA2dp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 private static final int IDLE_REQUEST = 0;
94 private boolean mScreenOff;
95 private boolean mDeviceIdle;
96 private int mPluggedType;
97
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070098 // true if the user enabled Wifi while in airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070099 private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700102 // some wifi lock statistics
Irfan Sheriff5876a422010-08-12 20:26:23 -0700103 private int mFullHighPerfLocksAcquired;
104 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700105 private int mFullLocksAcquired;
106 private int mFullLocksReleased;
107 private int mScanLocksAcquired;
108 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700109
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700110 private final List<Multicaster> mMulticasters =
111 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700112 private int mMulticastEnabled;
113 private int mMulticastDisabled;
114
The Android Open Source Project10592532009-03-18 17:39:46 -0700115 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800116
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800117 ConnectivityManager mCm;
118 private String[] mWifiRegexs;
119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800121 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
122 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 * the approximate point at which the battery drain caused by Wi-Fi
124 * being enabled but not active exceeds the battery drain caused by
125 * re-establishing a connection to the mobile data network.
126 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700127 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 private static final String ACTION_DEVICE_IDLE =
130 "com.android.server.WifiManager.action.DEVICE_IDLE";
131
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700132 private boolean mIsReceiverRegistered = false;
133
Irfan Sheriff0d255342010-07-28 09:35:20 -0700134
135 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
136
137 // Variables relating to the 'available networks' notification
138 /**
139 * The icon to show in the 'available networks' notification. This will also
140 * be the ID of the Notification given to the NotificationManager.
141 */
142 private static final int ICON_NETWORKS_AVAILABLE =
143 com.android.internal.R.drawable.stat_notify_wifi_in_range;
144 /**
145 * When a notification is shown, we wait this amount before possibly showing it again.
146 */
147 private final long NOTIFICATION_REPEAT_DELAY_MS;
148 /**
149 * Whether the user has set the setting to show the 'available networks' notification.
150 */
151 private boolean mNotificationEnabled;
152 /**
153 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
154 */
155 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
156 /**
157 * The {@link System#currentTimeMillis()} must be at least this value for us
158 * to show the notification again.
159 */
160 private long mNotificationRepeatTime;
161 /**
162 * The Notification object given to the NotificationManager.
163 */
164 private Notification mNotification;
165 /**
166 * Whether the notification is being shown, as set by us. That is, if the
167 * user cancels the notification, we will not receive the callback so this
168 * will still be true. We only guarantee if this is false, then the
169 * notification is not showing.
170 */
171 private boolean mNotificationShown;
172 /**
173 * The number of continuous scans that must occur before consider the
174 * supplicant in a scanning state. This allows supplicant to associate with
175 * remembered networks that are in the scan results.
176 */
177 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
178 /**
179 * The number of scans since the last network state change. When this
180 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
181 * supplicant to actually be scanning. When the network state changes to
182 * something other than scanning, we reset this to 0.
183 */
184 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700185
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700186 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700187 * Asynchronous channel to WifiStateMachine
188 */
189 private AsyncChannel mChannel;
190
191 /**
192 * TODO: Possibly change WifiService into an AsyncService.
193 */
194 private class WifiServiceHandler extends Handler {
195 private AsyncChannel mWshChannel;
196
197 WifiServiceHandler(android.os.Looper looper, Context context) {
198 super(looper);
199 mWshChannel = new AsyncChannel();
200 mWshChannel.connect(context, this, mWifiStateMachine.getHandler(), 0);
201 }
202
203 @Override
204 public void handleMessage(Message msg) {
205 switch (msg.what) {
206 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
207 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
208 mChannel = mWshChannel;
209 } else {
210 Slog.d(TAG, "WifiServicehandler.handleMessage could not connect error=" +
211 msg.arg1);
212 mChannel = null;
213 }
214 break;
215 }
216 default: {
217 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
218 break;
219 }
220 }
221 }
222 }
223 WifiServiceHandler mHandler;
224
225 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700226 * Temporary for computing UIDS that are responsible for starting WIFI.
227 * Protected by mWifiStateTracker lock.
228 */
229 private final WorkSource mTmpWorkSource = new WorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700230
231 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700233 mWifiStateMachine = new WifiStateMachine(mContext);
234 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700235 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
238 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
239 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
240
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700241 HandlerThread wifiThread = new HandlerThread("WifiService");
242 wifiThread.start();
Wink Saville4b7ba092010-10-20 15:37:41 -0700243 mHandler = new WifiServiceHandler(wifiThread.getLooper(), context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 mContext.registerReceiver(
246 new BroadcastReceiver() {
247 @Override
248 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700249 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700250 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700251 // on airplane disable, restore Wifi if the saved state indicates so
252 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
253 persistWifiEnabled(true);
254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 updateWifiState();
256 }
257 },
258 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
259
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800260 mContext.registerReceiver(
261 new BroadcastReceiver() {
262 @Override
263 public void onReceive(Context context, Intent intent) {
264
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700265 ArrayList<String> available = intent.getStringArrayListExtra(
266 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
267 ArrayList<String> active = intent.getStringArrayListExtra(
268 ConnectivityManager.EXTRA_ACTIVE_TETHER);
269 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800270
271 }
272 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700273
274 IntentFilter filter = new IntentFilter();
275 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
276 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
277 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
278
279 mContext.registerReceiver(
280 new BroadcastReceiver() {
281 @Override
282 public void onReceive(Context context, Intent intent) {
283 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
284 // reset & clear notification on any wifi state change
285 resetNotification();
286 } else if (intent.getAction().equals(
287 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
288 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
289 WifiManager.EXTRA_NETWORK_INFO);
290 // reset & clear notification on a network connect & disconnect
291 switch(mNetworkInfo.getDetailedState()) {
292 case CONNECTED:
293 case DISCONNECTED:
294 resetNotification();
295 break;
296 }
297 } else if (intent.getAction().equals(
298 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
299 checkAndSetNotification();
300 }
301 }
302 }, filter);
303
304 // Setting is in seconds
305 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
306 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
307 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
308 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800309 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800310
Irfan Sheriff7b009782010-03-11 16:37:45 -0800311 /**
312 * Check if Wi-Fi needs to be enabled and start
313 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700314 *
315 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800316 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700317 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700318 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700319 boolean wifiEnabled = !isAirplaneModeOn()
320 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800321 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
322 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700323 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800324 }
325
326 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
327
328 boolean wifiTethered = false;
329 boolean wifiAvailable = false;
330
331 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
332 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
333
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700334 if (mCm == null) {
335 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
336 }
337
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800338 mWifiRegexs = mCm.getTetherableWifiRegexs();
339
340 for (String intf : available) {
341 for (String regex : mWifiRegexs) {
342 if (intf.matches(regex)) {
343
344 InterfaceConfiguration ifcg = null;
345 try {
346 ifcg = service.getInterfaceConfig(intf);
347 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700348 /* IP/netmask: 192.168.43.1/255.255.255.0 */
349 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800350 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
Irfan Sheriff07bd5ae2010-10-28 14:45:56 -0700351 ifcg.interfaceFlags = "[up]";
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800352
353 service.setInterfaceConfig(intf, ifcg);
354 }
355 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800356 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700357 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800358 return;
359 }
360
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800361 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700362 Slog.e(TAG, "Error tethering on " + intf);
363 setWifiApEnabled(null, false);
364 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800365 }
366 break;
367 }
368 }
369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 }
371
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700372 private boolean testAndClearWifiSavedState() {
373 final ContentResolver cr = mContext.getContentResolver();
374 int wifiSavedState = 0;
375 try {
376 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
377 if(wifiSavedState == 1)
378 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
379 } catch (Settings.SettingNotFoundException e) {
380 ;
381 }
382 return (wifiSavedState == 1);
383 }
384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 private boolean getPersistedWifiEnabled() {
386 final ContentResolver cr = mContext.getContentResolver();
387 try {
388 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
389 } catch (Settings.SettingNotFoundException e) {
390 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
391 return false;
392 }
393 }
394
395 private void persistWifiEnabled(boolean enabled) {
396 final ContentResolver cr = mContext.getContentResolver();
397 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
398 }
399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 /**
401 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700402 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 */
404 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700405 enforceAccessPermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700406 if (mChannel != null) {
407 return mWifiStateMachine.syncPingSupplicant(mChannel);
408 } else {
409 Slog.e(TAG, "mChannel is not initialized");
410 return false;
411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 }
413
414 /**
415 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700417 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700419 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 }
421
422 private void enforceAccessPermission() {
423 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
424 "WifiService");
425 }
426
427 private void enforceChangePermission() {
428 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
429 "WifiService");
430
431 }
432
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700433 private void enforceMulticastChangePermission() {
434 mContext.enforceCallingOrSelfPermission(
435 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
436 "WifiService");
437 }
438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700440 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
441 * @param enable {@code true} to enable, {@code false} to disable.
442 * @return {@code true} if the enable/disable operation was
443 * started or is already in the queue.
444 */
445 public synchronized boolean setWifiEnabled(boolean enable) {
446 enforceChangePermission();
447
448 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700449 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700450 }
451
452 // set a flag if the user is enabling Wifi while in airplane mode
453 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
454 mAirplaneModeOverwridden.set(true);
455 }
456
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700457 if (enable) {
458 reportStartWorkSource();
459 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700460 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700461
462 /*
463 * Caller might not have WRITE_SECURE_SETTINGS,
464 * only CHANGE_WIFI_STATE is enforced
465 */
466 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700467 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700468 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700469
470 if (enable) {
471 if (!mIsReceiverRegistered) {
472 registerForBroadcasts();
473 mIsReceiverRegistered = true;
474 }
475 } else if (mIsReceiverRegistered){
476 mContext.unregisterReceiver(mReceiver);
477 mIsReceiverRegistered = false;
478 }
479
480 return true;
481 }
482
483 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 * see {@link WifiManager#getWifiState()}
485 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
486 * {@link WifiManager#WIFI_STATE_DISABLING},
487 * {@link WifiManager#WIFI_STATE_ENABLED},
488 * {@link WifiManager#WIFI_STATE_ENABLING},
489 * {@link WifiManager#WIFI_STATE_UNKNOWN}
490 */
491 public int getWifiEnabledState() {
492 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700493 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 }
495
496 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700497 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800498 * @param wifiConfig SSID, security and channel details as
499 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700500 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800501 * @return {@code true} if the start operation was
502 * started or is already in the queue.
503 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700504 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800505 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800506
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700507 if (enabled) {
508 /* Use default config if there is no existing config */
509 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
510 wifiConfig = new WifiConfiguration();
511 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
512 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
513 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700514 /*
515 * Caller might not have WRITE_SECURE_SETTINGS,
516 * only CHANGE_WIFI_STATE is enforced
517 */
518 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700519 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700520 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800521 }
522
Irfan Sheriff0d255342010-07-28 09:35:20 -0700523 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700524
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800525 return true;
526 }
527
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700528 /**
529 * see {@link WifiManager#getWifiApState()}
530 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
531 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
532 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
533 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
534 * {@link WifiManager#WIFI_AP_STATE_FAILED}
535 */
536 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700537 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700538 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700539 }
540
541 /**
542 * see {@link WifiManager#getWifiApConfiguration()}
543 * @return soft access point configuration
544 */
545 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800546 final ContentResolver cr = mContext.getContentResolver();
547 WifiConfiguration wifiConfig = new WifiConfiguration();
548 int authType;
549 try {
550 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
551 if (wifiConfig.SSID == null)
552 return null;
553 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
554 wifiConfig.allowedKeyManagement.set(authType);
555 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
556 return wifiConfig;
557 } catch (Settings.SettingNotFoundException e) {
558 Slog.e(TAG,"AP settings not found, returning");
559 return null;
560 }
561 }
562
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700563 /**
564 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
565 * @param wifiConfig WifiConfiguration details for soft access point
566 */
567 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700568 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800569 final ContentResolver cr = mContext.getContentResolver();
570 boolean isWpa;
571 if (wifiConfig == null)
572 return;
573 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
574 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
575 Settings.Secure.putInt(cr,
576 Settings.Secure.WIFI_AP_SECURITY,
577 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
578 if (isWpa)
579 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
580 }
581
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800582 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700583 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800584 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700585 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700586 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700587 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800588 }
589
590 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700591 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800592 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700593 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700594 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700595 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800596 }
597
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700598 /**
599 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700600 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700601 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700602 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700603 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800604 }
605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 /**
607 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
608 * @return the list of configured networks
609 */
610 public List<WifiConfiguration> getConfiguredNetworks() {
611 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700612 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800613 }
614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 /**
616 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
617 * @return the supplicant-assigned identifier for the new or updated
618 * network if the operation succeeds, or {@code -1} if it fails
619 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800620 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700622 if (mChannel != null) {
623 return mWifiStateMachine.syncAddOrUpdateNetwork(mChannel, config);
624 } else {
625 Slog.e(TAG, "mChannel is not initialized");
626 return -1;
627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 }
629
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700630 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
632 * @param netId the integer that identifies the network configuration
633 * to the supplicant
634 * @return {@code true} if the operation succeeded
635 */
636 public boolean removeNetwork(int netId) {
637 enforceChangePermission();
Wink Saville4b7ba092010-10-20 15:37:41 -0700638 if (mChannel != null) {
639 return mWifiStateMachine.syncRemoveNetwork(mChannel, netId);
640 } else {
641 Slog.e(TAG, "mChannel is not initialized");
642 return false;
643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
645
646 /**
647 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
648 * @param netId the integer that identifies the network configuration
649 * to the supplicant
650 * @param disableOthers if true, disable all other networks.
651 * @return {@code true} if the operation succeeded
652 */
653 public boolean enableNetwork(int netId, boolean disableOthers) {
654 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700655 if (mChannel != null) {
656 return mWifiStateMachine.syncEnableNetwork(mChannel, netId, disableOthers);
657 } else {
658 Slog.e(TAG, "mChannel is not initialized");
659 return false;
660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 }
662
663 /**
664 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
665 * @param netId the integer that identifies the network configuration
666 * to the supplicant
667 * @return {@code true} if the operation succeeded
668 */
669 public boolean disableNetwork(int netId) {
670 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700671 if (mChannel != null) {
672 return mWifiStateMachine.syncDisableNetwork(mChannel, netId);
673 } else {
674 Slog.e(TAG, "mChannel is not initialized");
675 return false;
676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 }
678
679 /**
680 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
681 * @return the Wi-Fi information, contained in {@link WifiInfo}.
682 */
683 public WifiInfo getConnectionInfo() {
684 enforceAccessPermission();
685 /*
686 * Make sure we have the latest information, by sending
687 * a status request to the supplicant.
688 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700689 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 }
691
692 /**
693 * Return the results of the most recent access point scan, in the form of
694 * a list of {@link ScanResult} objects.
695 * @return the list of results
696 */
697 public List<ScanResult> getScanResults() {
698 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700699 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 }
701
702 /**
703 * Tell the supplicant to persist the current list of configured networks.
704 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700705 *
706 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 */
708 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700709 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700711 if (mChannel != null) {
712 return mWifiStateMachine.syncSaveConfig(mChannel);
713 } else {
714 Slog.e(TAG, "mChannel is not initialized");
715 return false;
716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 }
718
719 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700720 * Set the country code
721 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700722 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700723 *
724 * The persist behavior exists so that wifi can fall back to the last
725 * persisted country code on a restart, when the locale information is
726 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700728 public void setCountryCode(String countryCode, boolean persist) {
729 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
730 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700732 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
734
735 /**
736 * Return the DHCP-assigned addresses from the last successful DHCP request,
737 * if any.
738 * @return the DHCP information
739 */
740 public DhcpInfo getDhcpInfo() {
741 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700742 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 }
744
Irfan Sheriff0d255342010-07-28 09:35:20 -0700745 /**
746 * see {@link android.net.wifi.WifiManager#startWifi}
747 *
748 */
749 public void startWifi() {
750 enforceChangePermission();
751 /* TODO: may be add permissions for access only to connectivity service
752 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
753 * of WifiLock & device idle status unless wifi enabled status is toggled
754 */
755
756 mWifiStateMachine.setDriverStart(true);
757 mWifiStateMachine.reconnectCommand();
758 }
759
760 /**
761 * see {@link android.net.wifi.WifiManager#stopWifi}
762 *
763 */
764 public void stopWifi() {
765 enforceChangePermission();
766 /* TODO: may be add permissions for access only to connectivity service
767 * TODO: if a stop is issued, wifi is brought up only by startWifi
768 * unless wifi enabled status is toggled
769 */
770 mWifiStateMachine.setDriverStart(false);
771 }
772
773
774 /**
775 * see {@link android.net.wifi.WifiManager#addToBlacklist}
776 *
777 */
778 public void addToBlacklist(String bssid) {
779 enforceChangePermission();
780
781 mWifiStateMachine.addToBlacklist(bssid);
782 }
783
784 /**
785 * see {@link android.net.wifi.WifiManager#clearBlacklist}
786 *
787 */
788 public void clearBlacklist() {
789 enforceChangePermission();
790
791 mWifiStateMachine.clearBlacklist();
792 }
793
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700794 public void connectNetworkWithId(int networkId) {
795 enforceChangePermission();
796 mWifiStateMachine.connectNetwork(networkId);
797 }
798
799 public void connectNetworkWithConfig(WifiConfiguration config) {
800 enforceChangePermission();
801 mWifiStateMachine.connectNetwork(config);
802 }
803
804 public void saveNetwork(WifiConfiguration config) {
805 enforceChangePermission();
806 mWifiStateMachine.saveNetwork(config);
807 }
808
809 public void forgetNetwork(int netId) {
810 enforceChangePermission();
811 mWifiStateMachine.forgetNetwork(netId);
812 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700813
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700814 public void startWpsPbc(String bssid) {
815 enforceChangePermission();
816 mWifiStateMachine.startWpsPbc(bssid);
817 }
818
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700819 public void startWpsWithPinFromAccessPoint(String bssid, int apPin) {
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700820 enforceChangePermission();
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700821 mWifiStateMachine.startWpsWithPinFromAccessPoint(bssid, apPin);
822 }
823
824 public int startWpsWithPinFromDevice(String bssid) {
825 enforceChangePermission();
826 if (mChannel != null) {
827 return mWifiStateMachine.syncStartWpsWithPinFromDevice(mChannel, bssid);
828 } else {
829 Slog.e(TAG, "mChannel is not initialized");
830 return -1;
831 }
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700832 }
833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
835 @Override
836 public void onReceive(Context context, Intent intent) {
837 String action = intent.getAction();
838
Doug Zongker43866e02010-01-07 12:09:54 -0800839 long idleMillis =
840 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700841 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800843 Settings.System.getInt(mContext.getContentResolver(),
844 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400846 if (DBG) {
847 Slog.d(TAG, "ACTION_SCREEN_ON");
848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 mAlarmManager.cancel(mIdleIntent);
850 mDeviceIdle = false;
851 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700852 // Once the screen is on, we are not keeping WIFI running
853 // because of any locks so clear that tracking immediately.
854 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700855 mWifiStateMachine.enableRssiPolling(true);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700856 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400858 if (DBG) {
859 Slog.d(TAG, "ACTION_SCREEN_OFF");
860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700862 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 /*
864 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
865 * AND the "stay on while plugged in" setting doesn't match the
866 * current power conditions (i.e, not plugged in, plugged in to USB,
867 * or plugged in to AC).
868 */
869 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700870 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700871 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700872 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700873 // we don't have time to track down for this release. Delay instead,
874 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700875 // TODO - fix the race conditions and switch back to the immediate turn-off
876 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400877 if (DBG) {
878 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
879 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700880 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
881 // // do not keep Wifi awake when screen is off if Wifi is not associated
882 // mDeviceIdle = true;
883 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400884 } else {
885 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400886 if (DBG) {
887 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
888 + "ms");
889 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400890 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400894 if (DBG) {
895 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700898 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700899 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
901 /*
902 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
903 * AND we are transitioning from a state in which the device was supposed
904 * to stay awake to a state in which it is not supposed to stay awake.
905 * If "stay awake" state is not changing, we do nothing, to avoid resetting
906 * the already-set timer.
907 */
908 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400909 if (DBG) {
910 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
913 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
914 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400915 if (DBG) {
916 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
920 mPluggedType = pluggedType;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700921 } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
922 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
923 BluetoothA2dp.STATE_NOT_PLAYING);
924 mWifiStateMachine.setBluetoothScanMode(state == BluetoothA2dp.STATE_PLAYING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 }
927
928 /**
929 * Determines whether the Wi-Fi chipset should stay awake or be put to
930 * sleep. Looks at the setting for the sleep policy and the current
931 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800932 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 * @see #shouldDeviceStayAwake(int, int)
934 */
935 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
936 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
937 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
938
939 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
940 // Never sleep
941 return true;
942 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
943 (pluggedType != 0)) {
944 // Never sleep while plugged, and we're plugged
945 return true;
946 } else {
947 // Default
948 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
949 }
950 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 /**
953 * Determine whether the bit value corresponding to {@code pluggedType} is set in
954 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
955 * of {@code 0} isn't really a plugged type, but rather an indication that the
956 * device isn't plugged in at all, there is no bit value corresponding to a
957 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700958 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 * @param stayAwakeConditions a bit string specifying which "plugged types" should
960 * keep the device (and hence Wi-Fi) awake.
961 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
962 * being made
963 * @return {@code true} if {@code pluggedType} indicates that the device is
964 * supposed to stay awake, {@code false} otherwise.
965 */
966 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
967 return (stayAwakeConditions & pluggedType) != 0;
968 }
969 };
970
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700971 private synchronized void reportStartWorkSource() {
972 mTmpWorkSource.clear();
973 if (mDeviceIdle) {
974 for (int i=0; i<mLocks.mList.size(); i++) {
975 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700976 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700977 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700978 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700979 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 private void updateWifiState() {
982 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700983 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -0700985 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
987 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff5876a422010-08-12 20:26:23 -0700988
989 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -0700991 }
992 /* If device is not idle, lockmode cannot be scan only */
993 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 strongestLockMode = WifiManager.WIFI_MODE_FULL;
995 }
996
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700997 /* Disable tethering when airplane mode is enabled */
998 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700999 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001000 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001001
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001002 if (wifiShouldBeEnabled) {
1003 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001004 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001005 mWifiStateMachine.setWifiEnabled(true);
1006 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001007 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001008 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001009 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1010 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001012 mWifiStateMachine.requestCmWakeLock();
1013 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001015 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001016 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 }
1018 }
1019
1020 private void registerForBroadcasts() {
1021 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1023 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1024 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1025 intentFilter.addAction(ACTION_DEVICE_IDLE);
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001026 intentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 mContext.registerReceiver(mReceiver, intentFilter);
1028 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 private boolean isAirplaneSensitive() {
1031 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1032 Settings.System.AIRPLANE_MODE_RADIOS);
1033 return airplaneModeRadios == null
1034 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1035 }
1036
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001037 private boolean isAirplaneToggleable() {
1038 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1039 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1040 return toggleableRadios != null
1041 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1042 }
1043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 /**
1045 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1046 * currently on.
1047 * @return {@code true} if airplane mode is on.
1048 */
1049 private boolean isAirplaneModeOn() {
1050 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1051 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1052 }
1053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 @Override
1055 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1056 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1057 != PackageManager.PERMISSION_GRANTED) {
1058 pw.println("Permission Denial: can't dump WifiService from from pid="
1059 + Binder.getCallingPid()
1060 + ", uid=" + Binder.getCallingUid());
1061 return;
1062 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001063 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 pw.println("Stay-awake conditions: " +
1065 Settings.System.getInt(mContext.getContentResolver(),
1066 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1067 pw.println();
1068
1069 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001070 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 pw.println();
1072 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001073 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 if (scanResults != null && scanResults.size() != 0) {
1075 pw.println(" BSSID Frequency RSSI Flags SSID");
1076 for (ScanResult r : scanResults) {
1077 pw.printf(" %17s %9d %5d %-16s %s%n",
1078 r.BSSID,
1079 r.frequency,
1080 r.level,
1081 r.capabilities,
1082 r.SSID == null ? "" : r.SSID);
1083 }
1084 }
1085 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001086 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001087 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001088 mScanLocksAcquired + " scan");
1089 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001090 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001091 mScanLocksReleased + " scan");
1092 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 pw.println("Locks held:");
1094 mLocks.dump(pw);
1095 }
1096
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001097 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001098 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1099 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 }
1101
1102 public void binderDied() {
1103 synchronized (mLocks) {
1104 releaseWifiLockLocked(mBinder);
1105 }
1106 }
1107
1108 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001109 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 }
1111 }
1112
1113 private class LockList {
1114 private List<WifiLock> mList;
1115
1116 private LockList() {
1117 mList = new ArrayList<WifiLock>();
1118 }
1119
1120 private synchronized boolean hasLocks() {
1121 return !mList.isEmpty();
1122 }
1123
1124 private synchronized int getStrongestLockMode() {
1125 if (mList.isEmpty()) {
1126 return WifiManager.WIFI_MODE_FULL;
1127 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001128
1129 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1130 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001132
1133 if (mFullLocksAcquired > mFullLocksReleased) {
1134 return WifiManager.WIFI_MODE_FULL;
1135 }
1136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 return WifiManager.WIFI_MODE_SCAN_ONLY;
1138 }
1139
1140 private void addLock(WifiLock lock) {
1141 if (findLockByBinder(lock.mBinder) < 0) {
1142 mList.add(lock);
1143 }
1144 }
1145
1146 private WifiLock removeLock(IBinder binder) {
1147 int index = findLockByBinder(binder);
1148 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001149 WifiLock ret = mList.remove(index);
1150 ret.unlinkDeathRecipient();
1151 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 } else {
1153 return null;
1154 }
1155 }
1156
1157 private int findLockByBinder(IBinder binder) {
1158 int size = mList.size();
1159 for (int i = size - 1; i >= 0; i--)
1160 if (mList.get(i).mBinder == binder)
1161 return i;
1162 return -1;
1163 }
1164
1165 private void dump(PrintWriter pw) {
1166 for (WifiLock l : mList) {
1167 pw.print(" ");
1168 pw.println(l);
1169 }
1170 }
1171 }
1172
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001173 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001174 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001175 return;
1176 }
1177 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1178 pid, uid, null);
1179 }
1180
1181 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001183 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1184 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1185 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1186 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1187 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 return false;
1189 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001190 if (ws != null && ws.size() == 0) {
1191 ws = null;
1192 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001193 if (ws != null) {
1194 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1195 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001196 if (ws == null) {
1197 ws = new WorkSource(Binder.getCallingUid());
1198 }
1199 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 synchronized (mLocks) {
1201 return acquireWifiLockLocked(wifiLock);
1202 }
1203 }
1204
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001205 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1206 switch(wifiLock.mMode) {
1207 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001208 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001209 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1210 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001211 case WifiManager.WIFI_MODE_SCAN_ONLY:
1212 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1213 break;
1214 }
1215 }
1216
1217 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1218 switch(wifiLock.mMode) {
1219 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001220 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001221 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1222 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001223 case WifiManager.WIFI_MODE_SCAN_ONLY:
1224 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1225 break;
1226 }
1227 }
1228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001230 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001233
The Android Open Source Project10592532009-03-18 17:39:46 -07001234 long ident = Binder.clearCallingIdentity();
1235 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001236 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001237 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001238 case WifiManager.WIFI_MODE_FULL:
1239 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001240 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001241 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1242 ++mFullHighPerfLocksAcquired;
1243 break;
1244
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001245 case WifiManager.WIFI_MODE_SCAN_ONLY:
1246 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001247 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001248 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001249
1250 // Be aggressive about adding new locks into the accounted state...
1251 // we want to over-report rather than under-report.
1252 reportStartWorkSource();
1253
1254 updateWifiState();
1255 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001256 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001257 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001258 } finally {
1259 Binder.restoreCallingIdentity(ident);
1260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
1262
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001263 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1264 int uid = Binder.getCallingUid();
1265 int pid = Binder.getCallingPid();
1266 if (ws != null && ws.size() == 0) {
1267 ws = null;
1268 }
1269 if (ws != null) {
1270 enforceWakeSourcePermission(uid, pid);
1271 }
1272 long ident = Binder.clearCallingIdentity();
1273 try {
1274 synchronized (mLocks) {
1275 int index = mLocks.findLockByBinder(lock);
1276 if (index < 0) {
1277 throw new IllegalArgumentException("Wifi lock not active");
1278 }
1279 WifiLock wl = mLocks.mList.get(index);
1280 noteReleaseWifiLock(wl);
1281 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1282 noteAcquireWifiLock(wl);
1283 }
1284 } catch (RemoteException e) {
1285 } finally {
1286 Binder.restoreCallingIdentity(ident);
1287 }
1288 }
1289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 public boolean releaseWifiLock(IBinder lock) {
1291 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1292 synchronized (mLocks) {
1293 return releaseWifiLockLocked(lock);
1294 }
1295 }
1296
1297 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001298 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001299
The Android Open Source Project10592532009-03-18 17:39:46 -07001300 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001301
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001302 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001303
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001304 hadLock = (wifiLock != null);
1305
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001306 long ident = Binder.clearCallingIdentity();
1307 try {
1308 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001309 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001310 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001311 case WifiManager.WIFI_MODE_FULL:
1312 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001313 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001314 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1315 ++mFullHighPerfLocksReleased;
1316 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001317 case WifiManager.WIFI_MODE_SCAN_ONLY:
1318 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001319 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001320 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001321 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001322
1323 // TODO - should this only happen if you hadLock?
1324 updateWifiState();
1325
1326 } catch (RemoteException e) {
1327 } finally {
1328 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001329 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001330
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001331 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001333
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001334 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001335 implements IBinder.DeathRecipient {
1336 String mTag;
1337 int mMode;
1338 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001339 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001340
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001341 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001342 super();
1343 mTag = tag;
1344 mMode = mode;
1345 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001346 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001347 try {
1348 mBinder.linkToDeath(this, 0);
1349 } catch (RemoteException e) {
1350 binderDied();
1351 }
1352 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001353
1354 void unlinkDeathRecipient() {
1355 mBinder.unlinkToDeath(this, 0);
1356 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001357 }
1358
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001359 private class Multicaster extends DeathRecipient {
1360 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001361 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001362 }
1363
1364 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001365 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001366 synchronized (mMulticasters) {
1367 int i = mMulticasters.indexOf(this);
1368 if (i != -1) {
1369 removeMulticasterLocked(i, mMode);
1370 }
1371 }
1372 }
1373
1374 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001375 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001376 }
1377
1378 public int getUid() {
1379 return mMode;
1380 }
1381 }
1382
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001383 public void initializeMulticastFiltering() {
1384 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001385
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001386 synchronized (mMulticasters) {
1387 // if anybody had requested filters be off, leave off
1388 if (mMulticasters.size() != 0) {
1389 return;
1390 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001391 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001392 }
1393 }
1394 }
1395
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001396 public void acquireMulticastLock(IBinder binder, String tag) {
1397 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001398
1399 synchronized (mMulticasters) {
1400 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001401 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001402 // Note that we could call stopPacketFiltering only when
1403 // our new size == 1 (first call), but this function won't
1404 // be called often and by making the stopPacket call each
1405 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001406 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001407 }
1408
1409 int uid = Binder.getCallingUid();
1410 Long ident = Binder.clearCallingIdentity();
1411 try {
1412 mBatteryStats.noteWifiMulticastEnabled(uid);
1413 } catch (RemoteException e) {
1414 } finally {
1415 Binder.restoreCallingIdentity(ident);
1416 }
1417 }
1418
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001419 public void releaseMulticastLock() {
1420 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001421
1422 int uid = Binder.getCallingUid();
1423 synchronized (mMulticasters) {
1424 mMulticastDisabled++;
1425 int size = mMulticasters.size();
1426 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001427 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001428 if ((m != null) && (m.getUid() == uid)) {
1429 removeMulticasterLocked(i, uid);
1430 }
1431 }
1432 }
1433 }
1434
1435 private void removeMulticasterLocked(int i, int uid)
1436 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001437 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001438
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001439 if (removed != null) {
1440 removed.unlinkDeathRecipient();
1441 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001442 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001443 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001444 }
1445
1446 Long ident = Binder.clearCallingIdentity();
1447 try {
1448 mBatteryStats.noteWifiMulticastDisabled(uid);
1449 } catch (RemoteException e) {
1450 } finally {
1451 Binder.restoreCallingIdentity(ident);
1452 }
1453 }
1454
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001455 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001456 enforceAccessPermission();
1457
1458 synchronized (mMulticasters) {
1459 return (mMulticasters.size() > 0);
1460 }
1461 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001462
1463 private void checkAndSetNotification() {
1464 // If we shouldn't place a notification on available networks, then
1465 // don't bother doing any of the following
1466 if (!mNotificationEnabled) return;
1467
1468 State state = mNetworkInfo.getState();
1469 if ((state == NetworkInfo.State.DISCONNECTED)
1470 || (state == NetworkInfo.State.UNKNOWN)) {
1471 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001472 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001473 if (scanResults != null) {
1474 int numOpenNetworks = 0;
1475 for (int i = scanResults.size() - 1; i >= 0; i--) {
1476 ScanResult scanResult = scanResults.get(i);
1477
1478 if (TextUtils.isEmpty(scanResult.capabilities)) {
1479 numOpenNetworks++;
1480 }
1481 }
1482
1483 if (numOpenNetworks > 0) {
1484 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1485 /*
1486 * We've scanned continuously at least
1487 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1488 * probably does not have a remembered network in range,
1489 * since otherwise supplicant would have tried to
1490 * associate and thus resetting this counter.
1491 */
1492 setNotificationVisible(true, numOpenNetworks, false, 0);
1493 }
1494 return;
1495 }
1496 }
1497 }
1498
1499 // No open networks in range, remove the notification
1500 setNotificationVisible(false, 0, false, 0);
1501 }
1502
1503 /**
1504 * Clears variables related to tracking whether a notification has been
1505 * shown recently and clears the current notification.
1506 */
1507 private void resetNotification() {
1508 mNotificationRepeatTime = 0;
1509 mNumScansSinceNetworkStateChange = 0;
1510 setNotificationVisible(false, 0, false, 0);
1511 }
1512
1513 /**
1514 * Display or don't display a notification that there are open Wi-Fi networks.
1515 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1516 * @param numNetworks the number networks seen
1517 * @param force {@code true} to force notification to be shown/not-shown,
1518 * even if it is already shown/not-shown.
1519 * @param delay time in milliseconds after which the notification should be made
1520 * visible or invisible.
1521 */
1522 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1523 int delay) {
1524
1525 // Since we use auto cancel on the notification, when the
1526 // mNetworksAvailableNotificationShown is true, the notification may
1527 // have actually been canceled. However, when it is false we know
1528 // for sure that it is not being shown (it will not be shown any other
1529 // place than here)
1530
1531 // If it should be hidden and it is already hidden, then noop
1532 if (!visible && !mNotificationShown && !force) {
1533 return;
1534 }
1535
1536 NotificationManager notificationManager = (NotificationManager) mContext
1537 .getSystemService(Context.NOTIFICATION_SERVICE);
1538
1539 Message message;
1540 if (visible) {
1541
1542 // Not enough time has passed to show the notification again
1543 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1544 return;
1545 }
1546
1547 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001548 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001549 mNotification = new Notification();
1550 mNotification.when = 0;
1551 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1552 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1553 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1554 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1555 }
1556
1557 CharSequence title = mContext.getResources().getQuantityText(
1558 com.android.internal.R.plurals.wifi_available, numNetworks);
1559 CharSequence details = mContext.getResources().getQuantityText(
1560 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1561 mNotification.tickerText = title;
1562 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1563
1564 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1565
1566 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001567 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001568 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001569 }
1570
Irfan Sheriff0d255342010-07-28 09:35:20 -07001571 mNotificationShown = visible;
1572 }
1573
1574 private class NotificationEnabledSettingObserver extends ContentObserver {
1575
1576 public NotificationEnabledSettingObserver(Handler handler) {
1577 super(handler);
1578 }
1579
1580 public void register() {
1581 ContentResolver cr = mContext.getContentResolver();
1582 cr.registerContentObserver(Settings.Secure.getUriFor(
1583 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1584 mNotificationEnabled = getValue();
1585 }
1586
1587 @Override
1588 public void onChange(boolean selfChange) {
1589 super.onChange(selfChange);
1590
1591 mNotificationEnabled = getValue();
1592 resetNotification();
1593 }
1594
1595 private boolean getValue() {
1596 return Settings.Secure.getInt(mContext.getContentResolver(),
1597 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1598 }
1599 }
1600
1601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602}