blob: 07813b0f045a3aabca0eede3b8131702541ba02c [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 Sheriff02fb46a2010-12-08 11:27:37 -080042import android.net.wifi.WpsConfiguration;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080043import android.net.ConnectivityManager;
44import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070046import android.net.NetworkInfo;
47import android.net.NetworkInfo.State;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070049import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.HandlerThread;
51import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080052import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070053import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070055import android.os.ServiceManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070056import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070058import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080059import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
61import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080063import java.util.Set;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070064import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import java.io.FileDescriptor;
66import java.io.PrintWriter;
67
The Android Open Source Project10592532009-03-18 17:39:46 -070068import com.android.internal.app.IBatteryStats;
Wink Saville4b7ba092010-10-20 15:37:41 -070069import com.android.internal.util.AsyncChannel;
The Android Open Source Project10592532009-03-18 17:39:46 -070070import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080071import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073/**
74 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070075 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 *
77 * @hide
78 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070079//TODO: Clean up multiple locks and implement WifiService
80// as a SM to track soft AP/client/adhoc bring up based
81// on device idle state, airplane mode and boot.
82
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083public class WifiService extends IWifiManager.Stub {
84 private static final String TAG = "WifiService";
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070085 private static final boolean DBG = true;
86
Irfan Sheriff0d255342010-07-28 09:35:20 -070087 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
89 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
91 private AlarmManager mAlarmManager;
92 private PendingIntent mIdleIntent;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070093 private BluetoothA2dp mBluetoothA2dp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 private static final int IDLE_REQUEST = 0;
95 private boolean mScreenOff;
96 private boolean mDeviceIdle;
97 private int mPluggedType;
98
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070099 // true if the user enabled Wifi while in airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700100 private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700103 // some wifi lock statistics
Irfan Sheriff5876a422010-08-12 20:26:23 -0700104 private int mFullHighPerfLocksAcquired;
105 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700106 private int mFullLocksAcquired;
107 private int mFullLocksReleased;
108 private int mScanLocksAcquired;
109 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700110
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700111 private final List<Multicaster> mMulticasters =
112 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700113 private int mMulticastEnabled;
114 private int mMulticastDisabled;
115
The Android Open Source Project10592532009-03-18 17:39:46 -0700116 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800117
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800118 ConnectivityManager mCm;
119 private String[] mWifiRegexs;
120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800122 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
123 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 * the approximate point at which the battery drain caused by Wi-Fi
125 * being enabled but not active exceeds the battery drain caused by
126 * re-establishing a connection to the mobile data network.
127 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700128 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private static final String ACTION_DEVICE_IDLE =
131 "com.android.server.WifiManager.action.DEVICE_IDLE";
132
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700133 private boolean mIsReceiverRegistered = false;
134
Irfan Sheriff0d255342010-07-28 09:35:20 -0700135
136 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
137
138 // Variables relating to the 'available networks' notification
139 /**
140 * The icon to show in the 'available networks' notification. This will also
141 * be the ID of the Notification given to the NotificationManager.
142 */
143 private static final int ICON_NETWORKS_AVAILABLE =
144 com.android.internal.R.drawable.stat_notify_wifi_in_range;
145 /**
146 * When a notification is shown, we wait this amount before possibly showing it again.
147 */
148 private final long NOTIFICATION_REPEAT_DELAY_MS;
149 /**
150 * Whether the user has set the setting to show the 'available networks' notification.
151 */
152 private boolean mNotificationEnabled;
153 /**
154 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
155 */
156 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
157 /**
158 * The {@link System#currentTimeMillis()} must be at least this value for us
159 * to show the notification again.
160 */
161 private long mNotificationRepeatTime;
162 /**
163 * The Notification object given to the NotificationManager.
164 */
165 private Notification mNotification;
166 /**
167 * Whether the notification is being shown, as set by us. That is, if the
168 * user cancels the notification, we will not receive the callback so this
169 * will still be true. We only guarantee if this is false, then the
170 * notification is not showing.
171 */
172 private boolean mNotificationShown;
173 /**
174 * The number of continuous scans that must occur before consider the
175 * supplicant in a scanning state. This allows supplicant to associate with
176 * remembered networks that are in the scan results.
177 */
178 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
179 /**
180 * The number of scans since the last network state change. When this
181 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
182 * supplicant to actually be scanning. When the network state changes to
183 * something other than scanning, we reset this to 0.
184 */
185 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700186
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700187 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700188 * Asynchronous channel to WifiStateMachine
189 */
190 private AsyncChannel mChannel;
191
192 /**
193 * TODO: Possibly change WifiService into an AsyncService.
194 */
195 private class WifiServiceHandler extends Handler {
196 private AsyncChannel mWshChannel;
197
198 WifiServiceHandler(android.os.Looper looper, Context context) {
199 super(looper);
200 mWshChannel = new AsyncChannel();
Wink Savillecfce3032010-12-01 23:20:25 -0800201 mWshChannel.connect(context, this, mWifiStateMachine.getHandler());
Wink Saville4b7ba092010-10-20 15:37:41 -0700202 }
203
204 @Override
205 public void handleMessage(Message msg) {
206 switch (msg.what) {
207 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
208 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
209 mChannel = mWshChannel;
210 } else {
211 Slog.d(TAG, "WifiServicehandler.handleMessage could not connect error=" +
212 msg.arg1);
213 mChannel = null;
214 }
215 break;
216 }
217 default: {
218 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
219 break;
220 }
221 }
222 }
223 }
224 WifiServiceHandler mHandler;
225
226 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700227 * Temporary for computing UIDS that are responsible for starting WIFI.
228 * Protected by mWifiStateTracker lock.
229 */
230 private final WorkSource mTmpWorkSource = new WorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700231
232 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700234 mWifiStateMachine = new WifiStateMachine(mContext);
235 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700236 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
239 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
240 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
241
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700242 HandlerThread wifiThread = new HandlerThread("WifiService");
243 wifiThread.start();
Wink Saville4b7ba092010-10-20 15:37:41 -0700244 mHandler = new WifiServiceHandler(wifiThread.getLooper(), context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 mContext.registerReceiver(
247 new BroadcastReceiver() {
248 @Override
249 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700250 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700251 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700252 // on airplane disable, restore Wifi if the saved state indicates so
253 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
254 persistWifiEnabled(true);
255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 updateWifiState();
257 }
258 },
259 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
260
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800261 mContext.registerReceiver(
262 new BroadcastReceiver() {
263 @Override
264 public void onReceive(Context context, Intent intent) {
265
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700266 ArrayList<String> available = intent.getStringArrayListExtra(
267 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
268 ArrayList<String> active = intent.getStringArrayListExtra(
269 ConnectivityManager.EXTRA_ACTIVE_TETHER);
270 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800271
272 }
273 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700274
275 IntentFilter filter = new IntentFilter();
276 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
277 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
278 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
279
280 mContext.registerReceiver(
281 new BroadcastReceiver() {
282 @Override
283 public void onReceive(Context context, Intent intent) {
284 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
285 // reset & clear notification on any wifi state change
286 resetNotification();
287 } else if (intent.getAction().equals(
288 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
289 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
290 WifiManager.EXTRA_NETWORK_INFO);
291 // reset & clear notification on a network connect & disconnect
292 switch(mNetworkInfo.getDetailedState()) {
293 case CONNECTED:
294 case DISCONNECTED:
295 resetNotification();
296 break;
297 }
298 } else if (intent.getAction().equals(
299 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
300 checkAndSetNotification();
301 }
302 }
303 }, filter);
304
305 // Setting is in seconds
306 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
307 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
308 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
309 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800310 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800311
Irfan Sheriff7b009782010-03-11 16:37:45 -0800312 /**
313 * Check if Wi-Fi needs to be enabled and start
314 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700315 *
316 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800317 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700318 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700319 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700320 boolean wifiEnabled = !isAirplaneModeOn()
321 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800322 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
323 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700324 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800325 }
326
327 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
328
329 boolean wifiTethered = false;
330 boolean wifiAvailable = false;
331
332 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
333 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
334
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700335 if (mCm == null) {
336 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
337 }
338
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800339 mWifiRegexs = mCm.getTetherableWifiRegexs();
340
341 for (String intf : available) {
342 for (String regex : mWifiRegexs) {
343 if (intf.matches(regex)) {
344
345 InterfaceConfiguration ifcg = null;
346 try {
347 ifcg = service.getInterfaceConfig(intf);
348 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700349 /* IP/netmask: 192.168.43.1/255.255.255.0 */
350 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800351 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
Irfan Sheriff07bd5ae2010-10-28 14:45:56 -0700352 ifcg.interfaceFlags = "[up]";
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800353
354 service.setInterfaceConfig(intf, ifcg);
355 }
356 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800357 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700358 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800359 return;
360 }
361
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800362 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700363 Slog.e(TAG, "Error tethering on " + intf);
364 setWifiApEnabled(null, false);
365 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800366 }
367 break;
368 }
369 }
370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 }
372
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700373 private boolean testAndClearWifiSavedState() {
374 final ContentResolver cr = mContext.getContentResolver();
375 int wifiSavedState = 0;
376 try {
377 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
378 if(wifiSavedState == 1)
379 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
380 } catch (Settings.SettingNotFoundException e) {
381 ;
382 }
383 return (wifiSavedState == 1);
384 }
385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 private boolean getPersistedWifiEnabled() {
387 final ContentResolver cr = mContext.getContentResolver();
388 try {
389 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
390 } catch (Settings.SettingNotFoundException e) {
391 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
392 return false;
393 }
394 }
395
396 private void persistWifiEnabled(boolean enabled) {
397 final ContentResolver cr = mContext.getContentResolver();
398 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
399 }
400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 /**
402 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700403 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 */
405 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700406 enforceAccessPermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700407 if (mChannel != null) {
408 return mWifiStateMachine.syncPingSupplicant(mChannel);
409 } else {
410 Slog.e(TAG, "mChannel is not initialized");
411 return false;
412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 }
414
415 /**
416 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700418 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700420 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 }
422
423 private void enforceAccessPermission() {
424 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
425 "WifiService");
426 }
427
428 private void enforceChangePermission() {
429 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
430 "WifiService");
431
432 }
433
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700434 private void enforceMulticastChangePermission() {
435 mContext.enforceCallingOrSelfPermission(
436 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
437 "WifiService");
438 }
439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700441 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
442 * @param enable {@code true} to enable, {@code false} to disable.
443 * @return {@code true} if the enable/disable operation was
444 * started or is already in the queue.
445 */
446 public synchronized boolean setWifiEnabled(boolean enable) {
447 enforceChangePermission();
448
449 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700450 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700451 }
452
453 // set a flag if the user is enabling Wifi while in airplane mode
454 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
455 mAirplaneModeOverwridden.set(true);
456 }
457
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700458 if (enable) {
459 reportStartWorkSource();
460 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700461 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700462
463 /*
464 * Caller might not have WRITE_SECURE_SETTINGS,
465 * only CHANGE_WIFI_STATE is enforced
466 */
467 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700468 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700469 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700470
471 if (enable) {
472 if (!mIsReceiverRegistered) {
473 registerForBroadcasts();
474 mIsReceiverRegistered = true;
475 }
476 } else if (mIsReceiverRegistered){
477 mContext.unregisterReceiver(mReceiver);
478 mIsReceiverRegistered = false;
479 }
480
481 return true;
482 }
483
484 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 * see {@link WifiManager#getWifiState()}
486 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
487 * {@link WifiManager#WIFI_STATE_DISABLING},
488 * {@link WifiManager#WIFI_STATE_ENABLED},
489 * {@link WifiManager#WIFI_STATE_ENABLING},
490 * {@link WifiManager#WIFI_STATE_UNKNOWN}
491 */
492 public int getWifiEnabledState() {
493 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700494 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 }
496
497 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700498 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800499 * @param wifiConfig SSID, security and channel details as
500 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700501 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800502 * @return {@code true} if the start operation was
503 * started or is already in the queue.
504 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700505 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800506 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800507
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700508 if (enabled) {
509 /* Use default config if there is no existing config */
510 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
511 wifiConfig = new WifiConfiguration();
512 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
513 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
514 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700515 /*
516 * Caller might not have WRITE_SECURE_SETTINGS,
517 * only CHANGE_WIFI_STATE is enforced
518 */
519 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700520 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700521 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800522 }
523
Irfan Sheriff0d255342010-07-28 09:35:20 -0700524 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700525
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800526 return true;
527 }
528
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700529 /**
530 * see {@link WifiManager#getWifiApState()}
531 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
532 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
533 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
534 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
535 * {@link WifiManager#WIFI_AP_STATE_FAILED}
536 */
537 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700538 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700539 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700540 }
541
542 /**
543 * see {@link WifiManager#getWifiApConfiguration()}
544 * @return soft access point configuration
545 */
546 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800547 final ContentResolver cr = mContext.getContentResolver();
548 WifiConfiguration wifiConfig = new WifiConfiguration();
549 int authType;
550 try {
551 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
552 if (wifiConfig.SSID == null)
553 return null;
554 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
555 wifiConfig.allowedKeyManagement.set(authType);
556 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
557 return wifiConfig;
558 } catch (Settings.SettingNotFoundException e) {
559 Slog.e(TAG,"AP settings not found, returning");
560 return null;
561 }
562 }
563
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700564 /**
565 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
566 * @param wifiConfig WifiConfiguration details for soft access point
567 */
568 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700569 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800570 final ContentResolver cr = mContext.getContentResolver();
571 boolean isWpa;
572 if (wifiConfig == null)
573 return;
574 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
575 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
576 Settings.Secure.putInt(cr,
577 Settings.Secure.WIFI_AP_SECURITY,
578 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
579 if (isWpa)
580 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
581 }
582
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800583 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700584 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800585 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700586 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700587 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700588 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800589 }
590
591 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700592 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800593 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700594 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700595 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700596 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800597 }
598
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700599 /**
600 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700601 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700602 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700603 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700604 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800605 }
606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 /**
608 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
609 * @return the list of configured networks
610 */
611 public List<WifiConfiguration> getConfiguredNetworks() {
612 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700613 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800614 }
615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 /**
617 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
618 * @return the supplicant-assigned identifier for the new or updated
619 * network if the operation succeeds, or {@code -1} if it fails
620 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800621 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700623 if (mChannel != null) {
624 return mWifiStateMachine.syncAddOrUpdateNetwork(mChannel, config);
625 } else {
626 Slog.e(TAG, "mChannel is not initialized");
627 return -1;
628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 }
630
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700631 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
633 * @param netId the integer that identifies the network configuration
634 * to the supplicant
635 * @return {@code true} if the operation succeeded
636 */
637 public boolean removeNetwork(int netId) {
638 enforceChangePermission();
Wink Saville4b7ba092010-10-20 15:37:41 -0700639 if (mChannel != null) {
640 return mWifiStateMachine.syncRemoveNetwork(mChannel, netId);
641 } else {
642 Slog.e(TAG, "mChannel is not initialized");
643 return false;
644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 }
646
647 /**
648 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
649 * @param netId the integer that identifies the network configuration
650 * to the supplicant
651 * @param disableOthers if true, disable all other networks.
652 * @return {@code true} if the operation succeeded
653 */
654 public boolean enableNetwork(int netId, boolean disableOthers) {
655 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700656 if (mChannel != null) {
657 return mWifiStateMachine.syncEnableNetwork(mChannel, netId, disableOthers);
658 } else {
659 Slog.e(TAG, "mChannel is not initialized");
660 return false;
661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 }
663
664 /**
665 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
666 * @param netId the integer that identifies the network configuration
667 * to the supplicant
668 * @return {@code true} if the operation succeeded
669 */
670 public boolean disableNetwork(int netId) {
671 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700672 if (mChannel != null) {
673 return mWifiStateMachine.syncDisableNetwork(mChannel, netId);
674 } else {
675 Slog.e(TAG, "mChannel is not initialized");
676 return false;
677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 }
679
680 /**
681 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
682 * @return the Wi-Fi information, contained in {@link WifiInfo}.
683 */
684 public WifiInfo getConnectionInfo() {
685 enforceAccessPermission();
686 /*
687 * Make sure we have the latest information, by sending
688 * a status request to the supplicant.
689 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700690 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 }
692
693 /**
694 * Return the results of the most recent access point scan, in the form of
695 * a list of {@link ScanResult} objects.
696 * @return the list of results
697 */
698 public List<ScanResult> getScanResults() {
699 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700700 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 }
702
703 /**
704 * Tell the supplicant to persist the current list of configured networks.
705 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700706 *
707 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 */
709 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700710 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700712 if (mChannel != null) {
713 return mWifiStateMachine.syncSaveConfig(mChannel);
714 } else {
715 Slog.e(TAG, "mChannel is not initialized");
716 return false;
717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 }
719
720 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700721 * Set the country code
722 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700723 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700724 *
725 * The persist behavior exists so that wifi can fall back to the last
726 * persisted country code on a restart, when the locale information is
727 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700729 public void setCountryCode(String countryCode, boolean persist) {
730 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
731 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700733 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 }
735
736 /**
Irfan Sheriff36f74132010-11-04 16:57:37 -0700737 * Set the operational frequency band
738 * @param band One of
739 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
740 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
741 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
742 * @param persist {@code true} if the setting should be remembered.
743 *
744 */
745 public void setFrequencyBand(int band, boolean persist) {
746 enforceChangePermission();
747 if (!isDualBandSupported()) return;
748 Slog.i(TAG, "WifiService trying to set frequency band to " + band +
749 " with persist set to " + persist);
750 mWifiStateMachine.setFrequencyBand(band, persist);
751 }
752
753
754 /**
755 * Get the operational frequency band
756 */
757 public int getFrequencyBand() {
758 enforceAccessPermission();
759 return mWifiStateMachine.getFrequencyBand();
760 }
761
762 public boolean isDualBandSupported() {
763 //TODO: Should move towards adding a driver API that checks at runtime
764 return mContext.getResources().getBoolean(
765 com.android.internal.R.bool.config_wifi_dual_band_support);
766 }
767
768 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 * Return the DHCP-assigned addresses from the last successful DHCP request,
770 * if any.
771 * @return the DHCP information
772 */
773 public DhcpInfo getDhcpInfo() {
774 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700775 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 }
777
Irfan Sheriff0d255342010-07-28 09:35:20 -0700778 /**
779 * see {@link android.net.wifi.WifiManager#startWifi}
780 *
781 */
782 public void startWifi() {
783 enforceChangePermission();
784 /* TODO: may be add permissions for access only to connectivity service
785 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
786 * of WifiLock & device idle status unless wifi enabled status is toggled
787 */
788
789 mWifiStateMachine.setDriverStart(true);
790 mWifiStateMachine.reconnectCommand();
791 }
792
793 /**
794 * see {@link android.net.wifi.WifiManager#stopWifi}
795 *
796 */
797 public void stopWifi() {
798 enforceChangePermission();
799 /* TODO: may be add permissions for access only to connectivity service
800 * TODO: if a stop is issued, wifi is brought up only by startWifi
801 * unless wifi enabled status is toggled
802 */
803 mWifiStateMachine.setDriverStart(false);
804 }
805
806
807 /**
808 * see {@link android.net.wifi.WifiManager#addToBlacklist}
809 *
810 */
811 public void addToBlacklist(String bssid) {
812 enforceChangePermission();
813
814 mWifiStateMachine.addToBlacklist(bssid);
815 }
816
817 /**
818 * see {@link android.net.wifi.WifiManager#clearBlacklist}
819 *
820 */
821 public void clearBlacklist() {
822 enforceChangePermission();
823
824 mWifiStateMachine.clearBlacklist();
825 }
826
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700827 public void connectNetworkWithId(int networkId) {
828 enforceChangePermission();
829 mWifiStateMachine.connectNetwork(networkId);
830 }
831
832 public void connectNetworkWithConfig(WifiConfiguration config) {
833 enforceChangePermission();
834 mWifiStateMachine.connectNetwork(config);
835 }
836
837 public void saveNetwork(WifiConfiguration config) {
838 enforceChangePermission();
839 mWifiStateMachine.saveNetwork(config);
840 }
841
842 public void forgetNetwork(int netId) {
843 enforceChangePermission();
844 mWifiStateMachine.forgetNetwork(netId);
845 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700846
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800847 public String startWps(WpsConfiguration config) {
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700848 enforceChangePermission();
849 if (mChannel != null) {
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800850 return mWifiStateMachine.startWps(mChannel, config);
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700851 } else {
852 Slog.e(TAG, "mChannel is not initialized");
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800853 return "";
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700854 }
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700855 }
856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
858 @Override
859 public void onReceive(Context context, Intent intent) {
860 String action = intent.getAction();
861
Doug Zongker43866e02010-01-07 12:09:54 -0800862 long idleMillis =
863 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700864 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800866 Settings.System.getInt(mContext.getContentResolver(),
867 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400869 if (DBG) {
870 Slog.d(TAG, "ACTION_SCREEN_ON");
871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 mAlarmManager.cancel(mIdleIntent);
873 mDeviceIdle = false;
874 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700875 // Once the screen is on, we are not keeping WIFI running
876 // because of any locks so clear that tracking immediately.
877 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700878 mWifiStateMachine.enableRssiPolling(true);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700879 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400881 if (DBG) {
882 Slog.d(TAG, "ACTION_SCREEN_OFF");
883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700885 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 /*
887 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
888 * AND the "stay on while plugged in" setting doesn't match the
889 * current power conditions (i.e, not plugged in, plugged in to USB,
890 * or plugged in to AC).
891 */
892 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700893 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700894 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700895 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700896 // we don't have time to track down for this release. Delay instead,
897 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700898 // TODO - fix the race conditions and switch back to the immediate turn-off
899 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400900 if (DBG) {
901 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
902 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700903 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
904 // // do not keep Wifi awake when screen is off if Wifi is not associated
905 // mDeviceIdle = true;
906 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400907 } else {
908 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400909 if (DBG) {
910 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
911 + "ms");
912 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400913 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400917 if (DBG) {
918 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700921 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700922 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
924 /*
925 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
926 * AND we are transitioning from a state in which the device was supposed
927 * to stay awake to a state in which it is not supposed to stay awake.
928 * If "stay awake" state is not changing, we do nothing, to avoid resetting
929 * the already-set timer.
930 */
931 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400932 if (DBG) {
933 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
936 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
937 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400938 if (DBG) {
939 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 }
943 mPluggedType = pluggedType;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700944 } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
945 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
946 BluetoothA2dp.STATE_NOT_PLAYING);
947 mWifiStateMachine.setBluetoothScanMode(state == BluetoothA2dp.STATE_PLAYING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 }
950
951 /**
952 * Determines whether the Wi-Fi chipset should stay awake or be put to
953 * sleep. Looks at the setting for the sleep policy and the current
954 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800955 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 * @see #shouldDeviceStayAwake(int, int)
957 */
958 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
959 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
960 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
961
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);
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001049 intentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_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}