blob: 1b590ba2190b466e48dfe1efd53baa0ab7073dab [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) {
Irfan Sheriff96b10d62011-01-11 15:40:35 -0800957 //Never sleep when plugged in as long as the user has not changed the settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
Irfan Sheriff96b10d62011-01-11 15:40:35 -0800959 Settings.System.WIFI_SLEEP_POLICY,
960 Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961
962 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
963 // Never sleep
964 return true;
965 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
966 (pluggedType != 0)) {
967 // Never sleep while plugged, and we're plugged
968 return true;
969 } else {
970 // Default
971 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
972 }
973 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 /**
976 * Determine whether the bit value corresponding to {@code pluggedType} is set in
977 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
978 * of {@code 0} isn't really a plugged type, but rather an indication that the
979 * device isn't plugged in at all, there is no bit value corresponding to a
980 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700981 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 * @param stayAwakeConditions a bit string specifying which "plugged types" should
983 * keep the device (and hence Wi-Fi) awake.
984 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
985 * being made
986 * @return {@code true} if {@code pluggedType} indicates that the device is
987 * supposed to stay awake, {@code false} otherwise.
988 */
989 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
990 return (stayAwakeConditions & pluggedType) != 0;
991 }
992 };
993
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700994 private synchronized void reportStartWorkSource() {
995 mTmpWorkSource.clear();
996 if (mDeviceIdle) {
997 for (int i=0; i<mLocks.mList.size(); i++) {
998 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700999 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001000 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001001 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001002 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 private void updateWifiState() {
1005 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001006 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001008 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1010 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001011
1012 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001014 }
1015 /* If device is not idle, lockmode cannot be scan only */
1016 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1018 }
1019
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001020 /* Disable tethering when airplane mode is enabled */
1021 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001022 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001023 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001024
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001025 if (wifiShouldBeEnabled) {
1026 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001027 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001028 mWifiStateMachine.setWifiEnabled(true);
1029 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001030 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001031 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001032 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1033 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001035 mWifiStateMachine.requestCmWakeLock();
1036 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001038 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001039 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
1041 }
1042
1043 private void registerForBroadcasts() {
1044 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1046 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1047 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1048 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001049 intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 mContext.registerReceiver(mReceiver, intentFilter);
1051 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 private boolean isAirplaneSensitive() {
1054 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1055 Settings.System.AIRPLANE_MODE_RADIOS);
1056 return airplaneModeRadios == null
1057 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1058 }
1059
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001060 private boolean isAirplaneToggleable() {
1061 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1062 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1063 return toggleableRadios != null
1064 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1065 }
1066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 /**
1068 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1069 * currently on.
1070 * @return {@code true} if airplane mode is on.
1071 */
1072 private boolean isAirplaneModeOn() {
1073 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1074 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1075 }
1076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 @Override
1078 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1079 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1080 != PackageManager.PERMISSION_GRANTED) {
1081 pw.println("Permission Denial: can't dump WifiService from from pid="
1082 + Binder.getCallingPid()
1083 + ", uid=" + Binder.getCallingUid());
1084 return;
1085 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001086 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 pw.println("Stay-awake conditions: " +
1088 Settings.System.getInt(mContext.getContentResolver(),
1089 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1090 pw.println();
1091
1092 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001093 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 pw.println();
1095 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001096 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 if (scanResults != null && scanResults.size() != 0) {
1098 pw.println(" BSSID Frequency RSSI Flags SSID");
1099 for (ScanResult r : scanResults) {
1100 pw.printf(" %17s %9d %5d %-16s %s%n",
1101 r.BSSID,
1102 r.frequency,
1103 r.level,
1104 r.capabilities,
1105 r.SSID == null ? "" : r.SSID);
1106 }
1107 }
1108 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001109 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001110 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001111 mScanLocksAcquired + " scan");
1112 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001113 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001114 mScanLocksReleased + " scan");
1115 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 pw.println("Locks held:");
1117 mLocks.dump(pw);
1118 }
1119
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001120 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001121 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1122 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 }
1124
1125 public void binderDied() {
1126 synchronized (mLocks) {
1127 releaseWifiLockLocked(mBinder);
1128 }
1129 }
1130
1131 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001132 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
1134 }
1135
1136 private class LockList {
1137 private List<WifiLock> mList;
1138
1139 private LockList() {
1140 mList = new ArrayList<WifiLock>();
1141 }
1142
1143 private synchronized boolean hasLocks() {
1144 return !mList.isEmpty();
1145 }
1146
1147 private synchronized int getStrongestLockMode() {
1148 if (mList.isEmpty()) {
1149 return WifiManager.WIFI_MODE_FULL;
1150 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001151
1152 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1153 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001155
1156 if (mFullLocksAcquired > mFullLocksReleased) {
1157 return WifiManager.WIFI_MODE_FULL;
1158 }
1159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 return WifiManager.WIFI_MODE_SCAN_ONLY;
1161 }
1162
1163 private void addLock(WifiLock lock) {
1164 if (findLockByBinder(lock.mBinder) < 0) {
1165 mList.add(lock);
1166 }
1167 }
1168
1169 private WifiLock removeLock(IBinder binder) {
1170 int index = findLockByBinder(binder);
1171 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001172 WifiLock ret = mList.remove(index);
1173 ret.unlinkDeathRecipient();
1174 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 } else {
1176 return null;
1177 }
1178 }
1179
1180 private int findLockByBinder(IBinder binder) {
1181 int size = mList.size();
1182 for (int i = size - 1; i >= 0; i--)
1183 if (mList.get(i).mBinder == binder)
1184 return i;
1185 return -1;
1186 }
1187
1188 private void dump(PrintWriter pw) {
1189 for (WifiLock l : mList) {
1190 pw.print(" ");
1191 pw.println(l);
1192 }
1193 }
1194 }
1195
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001196 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001197 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001198 return;
1199 }
1200 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1201 pid, uid, null);
1202 }
1203
1204 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001206 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1207 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1208 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1209 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1210 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 return false;
1212 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001213 if (ws != null && ws.size() == 0) {
1214 ws = null;
1215 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001216 if (ws != null) {
1217 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1218 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001219 if (ws == null) {
1220 ws = new WorkSource(Binder.getCallingUid());
1221 }
1222 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 synchronized (mLocks) {
1224 return acquireWifiLockLocked(wifiLock);
1225 }
1226 }
1227
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001228 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1229 switch(wifiLock.mMode) {
1230 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001231 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001232 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1233 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001234 case WifiManager.WIFI_MODE_SCAN_ONLY:
1235 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1236 break;
1237 }
1238 }
1239
1240 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1241 switch(wifiLock.mMode) {
1242 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001243 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001244 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1245 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001246 case WifiManager.WIFI_MODE_SCAN_ONLY:
1247 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1248 break;
1249 }
1250 }
1251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001253 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001256
The Android Open Source Project10592532009-03-18 17:39:46 -07001257 long ident = Binder.clearCallingIdentity();
1258 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001259 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001260 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001261 case WifiManager.WIFI_MODE_FULL:
1262 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001263 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001264 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1265 ++mFullHighPerfLocksAcquired;
1266 break;
1267
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001268 case WifiManager.WIFI_MODE_SCAN_ONLY:
1269 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001270 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001271 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001272
1273 // Be aggressive about adding new locks into the accounted state...
1274 // we want to over-report rather than under-report.
1275 reportStartWorkSource();
1276
1277 updateWifiState();
1278 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001279 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001280 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001281 } finally {
1282 Binder.restoreCallingIdentity(ident);
1283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 }
1285
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001286 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1287 int uid = Binder.getCallingUid();
1288 int pid = Binder.getCallingPid();
1289 if (ws != null && ws.size() == 0) {
1290 ws = null;
1291 }
1292 if (ws != null) {
1293 enforceWakeSourcePermission(uid, pid);
1294 }
1295 long ident = Binder.clearCallingIdentity();
1296 try {
1297 synchronized (mLocks) {
1298 int index = mLocks.findLockByBinder(lock);
1299 if (index < 0) {
1300 throw new IllegalArgumentException("Wifi lock not active");
1301 }
1302 WifiLock wl = mLocks.mList.get(index);
1303 noteReleaseWifiLock(wl);
1304 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1305 noteAcquireWifiLock(wl);
1306 }
1307 } catch (RemoteException e) {
1308 } finally {
1309 Binder.restoreCallingIdentity(ident);
1310 }
1311 }
1312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 public boolean releaseWifiLock(IBinder lock) {
1314 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1315 synchronized (mLocks) {
1316 return releaseWifiLockLocked(lock);
1317 }
1318 }
1319
1320 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001321 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001322
The Android Open Source Project10592532009-03-18 17:39:46 -07001323 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001324
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001325 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001326
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001327 hadLock = (wifiLock != null);
1328
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001329 long ident = Binder.clearCallingIdentity();
1330 try {
1331 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001332 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001333 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001334 case WifiManager.WIFI_MODE_FULL:
1335 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001336 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001337 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1338 ++mFullHighPerfLocksReleased;
1339 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001340 case WifiManager.WIFI_MODE_SCAN_ONLY:
1341 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001342 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001343 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001344 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001345
1346 // TODO - should this only happen if you hadLock?
1347 updateWifiState();
1348
1349 } catch (RemoteException e) {
1350 } finally {
1351 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001352 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001353
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001354 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001356
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001357 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001358 implements IBinder.DeathRecipient {
1359 String mTag;
1360 int mMode;
1361 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001362 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001363
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001364 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001365 super();
1366 mTag = tag;
1367 mMode = mode;
1368 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001369 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001370 try {
1371 mBinder.linkToDeath(this, 0);
1372 } catch (RemoteException e) {
1373 binderDied();
1374 }
1375 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001376
1377 void unlinkDeathRecipient() {
1378 mBinder.unlinkToDeath(this, 0);
1379 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001380 }
1381
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001382 private class Multicaster extends DeathRecipient {
1383 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001384 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001385 }
1386
1387 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001388 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001389 synchronized (mMulticasters) {
1390 int i = mMulticasters.indexOf(this);
1391 if (i != -1) {
1392 removeMulticasterLocked(i, mMode);
1393 }
1394 }
1395 }
1396
1397 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001398 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001399 }
1400
1401 public int getUid() {
1402 return mMode;
1403 }
1404 }
1405
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001406 public void initializeMulticastFiltering() {
1407 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001408
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001409 synchronized (mMulticasters) {
1410 // if anybody had requested filters be off, leave off
1411 if (mMulticasters.size() != 0) {
1412 return;
1413 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001414 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001415 }
1416 }
1417 }
1418
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001419 public void acquireMulticastLock(IBinder binder, String tag) {
1420 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001421
1422 synchronized (mMulticasters) {
1423 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001424 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001425 // Note that we could call stopPacketFiltering only when
1426 // our new size == 1 (first call), but this function won't
1427 // be called often and by making the stopPacket call each
1428 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001429 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001430 }
1431
1432 int uid = Binder.getCallingUid();
1433 Long ident = Binder.clearCallingIdentity();
1434 try {
1435 mBatteryStats.noteWifiMulticastEnabled(uid);
1436 } catch (RemoteException e) {
1437 } finally {
1438 Binder.restoreCallingIdentity(ident);
1439 }
1440 }
1441
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001442 public void releaseMulticastLock() {
1443 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001444
1445 int uid = Binder.getCallingUid();
1446 synchronized (mMulticasters) {
1447 mMulticastDisabled++;
1448 int size = mMulticasters.size();
1449 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001450 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001451 if ((m != null) && (m.getUid() == uid)) {
1452 removeMulticasterLocked(i, uid);
1453 }
1454 }
1455 }
1456 }
1457
1458 private void removeMulticasterLocked(int i, int uid)
1459 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001460 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001461
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001462 if (removed != null) {
1463 removed.unlinkDeathRecipient();
1464 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001465 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001466 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001467 }
1468
1469 Long ident = Binder.clearCallingIdentity();
1470 try {
1471 mBatteryStats.noteWifiMulticastDisabled(uid);
1472 } catch (RemoteException e) {
1473 } finally {
1474 Binder.restoreCallingIdentity(ident);
1475 }
1476 }
1477
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001478 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001479 enforceAccessPermission();
1480
1481 synchronized (mMulticasters) {
1482 return (mMulticasters.size() > 0);
1483 }
1484 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001485
1486 private void checkAndSetNotification() {
1487 // If we shouldn't place a notification on available networks, then
1488 // don't bother doing any of the following
1489 if (!mNotificationEnabled) return;
1490
1491 State state = mNetworkInfo.getState();
1492 if ((state == NetworkInfo.State.DISCONNECTED)
1493 || (state == NetworkInfo.State.UNKNOWN)) {
1494 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001495 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001496 if (scanResults != null) {
1497 int numOpenNetworks = 0;
1498 for (int i = scanResults.size() - 1; i >= 0; i--) {
1499 ScanResult scanResult = scanResults.get(i);
1500
1501 if (TextUtils.isEmpty(scanResult.capabilities)) {
1502 numOpenNetworks++;
1503 }
1504 }
1505
1506 if (numOpenNetworks > 0) {
1507 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1508 /*
1509 * We've scanned continuously at least
1510 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1511 * probably does not have a remembered network in range,
1512 * since otherwise supplicant would have tried to
1513 * associate and thus resetting this counter.
1514 */
1515 setNotificationVisible(true, numOpenNetworks, false, 0);
1516 }
1517 return;
1518 }
1519 }
1520 }
1521
1522 // No open networks in range, remove the notification
1523 setNotificationVisible(false, 0, false, 0);
1524 }
1525
1526 /**
1527 * Clears variables related to tracking whether a notification has been
1528 * shown recently and clears the current notification.
1529 */
1530 private void resetNotification() {
1531 mNotificationRepeatTime = 0;
1532 mNumScansSinceNetworkStateChange = 0;
1533 setNotificationVisible(false, 0, false, 0);
1534 }
1535
1536 /**
1537 * Display or don't display a notification that there are open Wi-Fi networks.
1538 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1539 * @param numNetworks the number networks seen
1540 * @param force {@code true} to force notification to be shown/not-shown,
1541 * even if it is already shown/not-shown.
1542 * @param delay time in milliseconds after which the notification should be made
1543 * visible or invisible.
1544 */
1545 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1546 int delay) {
1547
1548 // Since we use auto cancel on the notification, when the
1549 // mNetworksAvailableNotificationShown is true, the notification may
1550 // have actually been canceled. However, when it is false we know
1551 // for sure that it is not being shown (it will not be shown any other
1552 // place than here)
1553
1554 // If it should be hidden and it is already hidden, then noop
1555 if (!visible && !mNotificationShown && !force) {
1556 return;
1557 }
1558
1559 NotificationManager notificationManager = (NotificationManager) mContext
1560 .getSystemService(Context.NOTIFICATION_SERVICE);
1561
1562 Message message;
1563 if (visible) {
1564
1565 // Not enough time has passed to show the notification again
1566 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1567 return;
1568 }
1569
1570 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001571 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001572 mNotification = new Notification();
1573 mNotification.when = 0;
1574 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1575 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1576 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1577 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1578 }
1579
1580 CharSequence title = mContext.getResources().getQuantityText(
1581 com.android.internal.R.plurals.wifi_available, numNetworks);
1582 CharSequence details = mContext.getResources().getQuantityText(
1583 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1584 mNotification.tickerText = title;
1585 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1586
1587 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1588
1589 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001590 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001591 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001592 }
1593
Irfan Sheriff0d255342010-07-28 09:35:20 -07001594 mNotificationShown = visible;
1595 }
1596
1597 private class NotificationEnabledSettingObserver extends ContentObserver {
1598
1599 public NotificationEnabledSettingObserver(Handler handler) {
1600 super(handler);
1601 }
1602
1603 public void register() {
1604 ContentResolver cr = mContext.getContentResolver();
1605 cr.registerContentObserver(Settings.Secure.getUriFor(
1606 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1607 mNotificationEnabled = getValue();
1608 }
1609
1610 @Override
1611 public void onChange(boolean selfChange) {
1612 super.onChange(selfChange);
1613
1614 mNotificationEnabled = getValue();
1615 resetNotification();
1616 }
1617
1618 private boolean getValue() {
1619 return Settings.Secure.getInt(mContext.getContentResolver(),
1620 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1621 }
1622 }
1623
1624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625}