blob: 92588fc878b08a4a9831f88c7ff9d5ec00c2be76 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07002 * Copyright (C) 2010 The Android Open Source Project
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080019import android.app.AlarmManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070020import android.app.Notification;
21import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070023import android.bluetooth.BluetoothA2dp;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070024import android.bluetooth.BluetoothAdapter;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080025import android.bluetooth.BluetoothDevice;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070026import android.bluetooth.BluetoothProfile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.BroadcastReceiver;
28import android.content.ContentResolver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.net.wifi.IWifiManager;
35import android.net.wifi.WifiInfo;
36import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070037import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.net.wifi.ScanResult;
39import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070040import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080041import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080042import android.net.ConnectivityManager;
43import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070045import android.net.NetworkInfo;
46import android.net.NetworkInfo.State;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070048import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.HandlerThread;
50import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080051import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070052import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070054import android.os.ServiceManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070055import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070057import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080058import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
60import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080062import java.util.Set;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070063import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.io.FileDescriptor;
65import java.io.PrintWriter;
66
The Android Open Source Project10592532009-03-18 17:39:46 -070067import com.android.internal.app.IBatteryStats;
Wink Saville4b7ba092010-10-20 15:37:41 -070068import com.android.internal.util.AsyncChannel;
The Android Open Source Project10592532009-03-18 17:39:46 -070069import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080070import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072/**
73 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070074 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 *
76 * @hide
77 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070078//TODO: Clean up multiple locks and implement WifiService
79// as a SM to track soft AP/client/adhoc bring up based
80// on device idle state, airplane mode and boot.
81
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082public class WifiService extends IWifiManager.Stub {
83 private static final String TAG = "WifiService";
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070084 private static final boolean DBG = true;
85
Irfan Sheriff0d255342010-07-28 09:35:20 -070086 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087
88 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
90 private AlarmManager mAlarmManager;
91 private PendingIntent mIdleIntent;
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -070092 private PendingIntent mScanIntent;
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;
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -070095 private static final int SCAN_REQUEST = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private boolean mScreenOff;
97 private boolean mDeviceIdle;
98 private int mPluggedType;
99
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700100 // true if the user enabled Wifi while in airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700101 private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700104 // some wifi lock statistics
105 private int mFullLocksAcquired;
106 private int mFullLocksReleased;
107 private int mScanLocksAcquired;
108 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700109
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700110 private final List<Multicaster> mMulticasters =
111 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700112 private int mMulticastEnabled;
113 private int mMulticastDisabled;
114
The Android Open Source Project10592532009-03-18 17:39:46 -0700115 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800116
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800117 ConnectivityManager mCm;
118 private String[] mWifiRegexs;
119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800121 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
122 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 * the approximate point at which the battery drain caused by Wi-Fi
124 * being enabled but not active exceeds the battery drain caused by
125 * re-establishing a connection to the mobile data network.
126 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700127 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
128
129 /**
130 * See {@link Settings.Secure#WIFI_SCAN_INTERVAL_MS}. This is the default value if a
131 * Settings.Secure value is not present.
132 */
133 private static final long DEFAULT_SCAN_INTERVAL_MS = 60 * 1000; /* 1 minute */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 /**
136 * Number of allowed radio frequency channels in various regulatory domains.
137 * This list is sufficient for 802.11b/g networks (2.4GHz range).
138 */
139 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
140
141 private static final String ACTION_DEVICE_IDLE =
142 "com.android.server.WifiManager.action.DEVICE_IDLE";
143
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700144 private static final String ACTION_START_SCAN =
145 "com.android.server.WifiManager.action.START_SCAN";
146
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700147 private boolean mIsReceiverRegistered = false;
148
Irfan Sheriff0d255342010-07-28 09:35:20 -0700149
150 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
151
152 // Variables relating to the 'available networks' notification
153 /**
154 * The icon to show in the 'available networks' notification. This will also
155 * be the ID of the Notification given to the NotificationManager.
156 */
157 private static final int ICON_NETWORKS_AVAILABLE =
158 com.android.internal.R.drawable.stat_notify_wifi_in_range;
159 /**
160 * When a notification is shown, we wait this amount before possibly showing it again.
161 */
162 private final long NOTIFICATION_REPEAT_DELAY_MS;
163 /**
164 * Whether the user has set the setting to show the 'available networks' notification.
165 */
166 private boolean mNotificationEnabled;
167 /**
168 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
169 */
170 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
171 /**
172 * The {@link System#currentTimeMillis()} must be at least this value for us
173 * to show the notification again.
174 */
175 private long mNotificationRepeatTime;
176 /**
177 * The Notification object given to the NotificationManager.
178 */
179 private Notification mNotification;
180 /**
181 * Whether the notification is being shown, as set by us. That is, if the
182 * user cancels the notification, we will not receive the callback so this
183 * will still be true. We only guarantee if this is false, then the
184 * notification is not showing.
185 */
186 private boolean mNotificationShown;
187 /**
188 * The number of continuous scans that must occur before consider the
189 * supplicant in a scanning state. This allows supplicant to associate with
190 * remembered networks that are in the scan results.
191 */
192 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
193 /**
194 * The number of scans since the last network state change. When this
195 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
196 * supplicant to actually be scanning. When the network state changes to
197 * something other than scanning, we reset this to 0.
198 */
199 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700200
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700201 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700202 * Asynchronous channel to WifiStateMachine
203 */
204 private AsyncChannel mChannel;
205
206 /**
207 * TODO: Possibly change WifiService into an AsyncService.
208 */
209 private class WifiServiceHandler extends Handler {
210 private AsyncChannel mWshChannel;
211
212 WifiServiceHandler(android.os.Looper looper, Context context) {
213 super(looper);
214 mWshChannel = new AsyncChannel();
215 mWshChannel.connect(context, this, mWifiStateMachine.getHandler(), 0);
216 }
217
218 @Override
219 public void handleMessage(Message msg) {
220 switch (msg.what) {
221 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
222 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
223 mChannel = mWshChannel;
224 } else {
225 Slog.d(TAG, "WifiServicehandler.handleMessage could not connect error=" +
226 msg.arg1);
227 mChannel = null;
228 }
229 break;
230 }
231 default: {
232 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
233 break;
234 }
235 }
236 }
237 }
238 WifiServiceHandler mHandler;
239
240 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700241 * Temporary for computing UIDS that are responsible for starting WIFI.
242 * Protected by mWifiStateTracker lock.
243 */
244 private final WorkSource mTmpWorkSource = new WorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700245
246 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700248 mWifiStateMachine = new WifiStateMachine(mContext);
249 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700250 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
253 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
254 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
255
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700256 Intent scanIntent = new Intent(ACTION_START_SCAN, null);
257 mScanIntent = PendingIntent.getBroadcast(mContext, SCAN_REQUEST, scanIntent, 0);
258
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700259 HandlerThread wifiThread = new HandlerThread("WifiService");
260 wifiThread.start();
Wink Saville4b7ba092010-10-20 15:37:41 -0700261 mHandler = new WifiServiceHandler(wifiThread.getLooper(), context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 mContext.registerReceiver(
264 new BroadcastReceiver() {
265 @Override
266 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700267 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700268 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700269 // on airplane disable, restore Wifi if the saved state indicates so
270 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
271 persistWifiEnabled(true);
272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 updateWifiState();
274 }
275 },
276 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
277
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800278 mContext.registerReceiver(
279 new BroadcastReceiver() {
280 @Override
281 public void onReceive(Context context, Intent intent) {
282
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700283 ArrayList<String> available = intent.getStringArrayListExtra(
284 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
285 ArrayList<String> active = intent.getStringArrayListExtra(
286 ConnectivityManager.EXTRA_ACTIVE_TETHER);
287 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800288
289 }
290 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700291
292 IntentFilter filter = new IntentFilter();
293 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
294 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
295 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
296
297 mContext.registerReceiver(
298 new BroadcastReceiver() {
299 @Override
300 public void onReceive(Context context, Intent intent) {
301 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
302 // reset & clear notification on any wifi state change
303 resetNotification();
304 } else if (intent.getAction().equals(
305 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
306 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
307 WifiManager.EXTRA_NETWORK_INFO);
308 // reset & clear notification on a network connect & disconnect
309 switch(mNetworkInfo.getDetailedState()) {
310 case CONNECTED:
311 case DISCONNECTED:
312 resetNotification();
313 break;
314 }
315 } else if (intent.getAction().equals(
316 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
317 checkAndSetNotification();
318 }
319 }
320 }, filter);
321
322 // Setting is in seconds
323 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
324 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
325 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
326 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800327 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800328
Irfan Sheriff7b009782010-03-11 16:37:45 -0800329 /**
330 * Check if Wi-Fi needs to be enabled and start
331 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700332 *
333 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800334 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700335 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700336 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700337 boolean wifiEnabled = !isAirplaneModeOn()
338 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800339 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
340 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700341 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800342 }
343
344 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
345
346 boolean wifiTethered = false;
347 boolean wifiAvailable = false;
348
349 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
350 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
351
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700352 if (mCm == null) {
353 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
354 }
355
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800356 mWifiRegexs = mCm.getTetherableWifiRegexs();
357
358 for (String intf : available) {
359 for (String regex : mWifiRegexs) {
360 if (intf.matches(regex)) {
361
362 InterfaceConfiguration ifcg = null;
363 try {
364 ifcg = service.getInterfaceConfig(intf);
365 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700366 /* IP/netmask: 192.168.43.1/255.255.255.0 */
367 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800368 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
369 ifcg.interfaceFlags = "up";
370
371 service.setInterfaceConfig(intf, ifcg);
372 }
373 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800374 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700375 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800376 return;
377 }
378
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800379 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700380 Slog.e(TAG, "Error tethering on " + intf);
381 setWifiApEnabled(null, false);
382 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800383 }
384 break;
385 }
386 }
387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 }
389
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700390 private boolean testAndClearWifiSavedState() {
391 final ContentResolver cr = mContext.getContentResolver();
392 int wifiSavedState = 0;
393 try {
394 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
395 if(wifiSavedState == 1)
396 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
397 } catch (Settings.SettingNotFoundException e) {
398 ;
399 }
400 return (wifiSavedState == 1);
401 }
402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 private boolean getPersistedWifiEnabled() {
404 final ContentResolver cr = mContext.getContentResolver();
405 try {
406 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
407 } catch (Settings.SettingNotFoundException e) {
408 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
409 return false;
410 }
411 }
412
413 private void persistWifiEnabled(boolean enabled) {
414 final ContentResolver cr = mContext.getContentResolver();
415 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
416 }
417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 /**
419 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700420 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 */
422 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700423 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700424 return mWifiStateMachine.syncPingSupplicant();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 }
426
427 /**
428 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700430 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700432 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 }
434
435 private void enforceAccessPermission() {
436 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
437 "WifiService");
438 }
439
440 private void enforceChangePermission() {
441 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
442 "WifiService");
443
444 }
445
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700446 private void enforceMulticastChangePermission() {
447 mContext.enforceCallingOrSelfPermission(
448 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
449 "WifiService");
450 }
451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700453 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
454 * @param enable {@code true} to enable, {@code false} to disable.
455 * @return {@code true} if the enable/disable operation was
456 * started or is already in the queue.
457 */
458 public synchronized boolean setWifiEnabled(boolean enable) {
459 enforceChangePermission();
460
461 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700462 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700463 }
464
465 // set a flag if the user is enabling Wifi while in airplane mode
466 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
467 mAirplaneModeOverwridden.set(true);
468 }
469
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700470 if (enable) {
471 reportStartWorkSource();
472 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700473 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700474
475 /*
476 * Caller might not have WRITE_SECURE_SETTINGS,
477 * only CHANGE_WIFI_STATE is enforced
478 */
479 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700480 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700481 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700482
483 if (enable) {
484 if (!mIsReceiverRegistered) {
485 registerForBroadcasts();
486 mIsReceiverRegistered = true;
487 }
488 } else if (mIsReceiverRegistered){
489 mContext.unregisterReceiver(mReceiver);
490 mIsReceiverRegistered = false;
491 }
492
493 return true;
494 }
495
496 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 * see {@link WifiManager#getWifiState()}
498 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
499 * {@link WifiManager#WIFI_STATE_DISABLING},
500 * {@link WifiManager#WIFI_STATE_ENABLED},
501 * {@link WifiManager#WIFI_STATE_ENABLING},
502 * {@link WifiManager#WIFI_STATE_UNKNOWN}
503 */
504 public int getWifiEnabledState() {
505 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700506 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 }
508
509 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700510 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800511 * @param wifiConfig SSID, security and channel details as
512 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700513 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800514 * @return {@code true} if the start operation was
515 * started or is already in the queue.
516 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700517 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800518 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800519
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700520 if (enabled) {
521 /* Use default config if there is no existing config */
522 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
523 wifiConfig = new WifiConfiguration();
524 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
525 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
526 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700527 /*
528 * Caller might not have WRITE_SECURE_SETTINGS,
529 * only CHANGE_WIFI_STATE is enforced
530 */
531 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700532 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700533 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800534 }
535
Irfan Sheriff0d255342010-07-28 09:35:20 -0700536 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700537
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800538 return true;
539 }
540
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700541 /**
542 * see {@link WifiManager#getWifiApState()}
543 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
544 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
545 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
546 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
547 * {@link WifiManager#WIFI_AP_STATE_FAILED}
548 */
549 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700550 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700551 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700552 }
553
554 /**
555 * see {@link WifiManager#getWifiApConfiguration()}
556 * @return soft access point configuration
557 */
558 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800559 final ContentResolver cr = mContext.getContentResolver();
560 WifiConfiguration wifiConfig = new WifiConfiguration();
561 int authType;
562 try {
563 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
564 if (wifiConfig.SSID == null)
565 return null;
566 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
567 wifiConfig.allowedKeyManagement.set(authType);
568 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
569 return wifiConfig;
570 } catch (Settings.SettingNotFoundException e) {
571 Slog.e(TAG,"AP settings not found, returning");
572 return null;
573 }
574 }
575
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700576 /**
577 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
578 * @param wifiConfig WifiConfiguration details for soft access point
579 */
580 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700581 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800582 final ContentResolver cr = mContext.getContentResolver();
583 boolean isWpa;
584 if (wifiConfig == null)
585 return;
586 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
587 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
588 Settings.Secure.putInt(cr,
589 Settings.Secure.WIFI_AP_SECURITY,
590 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
591 if (isWpa)
592 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
593 }
594
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800595 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700596 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800597 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700598 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700599 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700600 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800601 }
602
603 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700604 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800605 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700606 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700607 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700608 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800609 }
610
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700611 /**
612 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700613 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700614 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700615 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700616 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800617 }
618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 /**
620 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
621 * @return the list of configured networks
622 */
623 public List<WifiConfiguration> getConfiguredNetworks() {
624 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700625 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800626 }
627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 /**
629 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
630 * @return the supplicant-assigned identifier for the new or updated
631 * network if the operation succeeds, or {@code -1} if it fails
632 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800633 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700635 return mWifiStateMachine.syncAddOrUpdateNetwork(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 }
637
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700638 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
640 * @param netId the integer that identifies the network configuration
641 * to the supplicant
642 * @return {@code true} if the operation succeeded
643 */
644 public boolean removeNetwork(int netId) {
645 enforceChangePermission();
Wink Saville4b7ba092010-10-20 15:37:41 -0700646 if (mChannel != null) {
647 return mWifiStateMachine.syncRemoveNetwork(mChannel, netId);
648 } else {
649 Slog.e(TAG, "mChannel is not initialized");
650 return false;
651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 }
653
654 /**
655 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
656 * @param netId the integer that identifies the network configuration
657 * to the supplicant
658 * @param disableOthers if true, disable all other networks.
659 * @return {@code true} if the operation succeeded
660 */
661 public boolean enableNetwork(int netId, boolean disableOthers) {
662 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700663 return mWifiStateMachine.syncEnableNetwork(netId, disableOthers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 }
665
666 /**
667 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
668 * @param netId the integer that identifies the network configuration
669 * to the supplicant
670 * @return {@code true} if the operation succeeded
671 */
672 public boolean disableNetwork(int netId) {
673 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700674 return mWifiStateMachine.syncDisableNetwork(netId);
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 Sheriffd8134ff2010-08-22 17:06:34 -0700709 return mWifiStateMachine.syncSaveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 }
711
712 /**
713 * Set the number of radio frequency channels that are allowed to be used
714 * in the current regulatory domain. This method should be used only
715 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700716 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 * persisted as a Secure setting.
718 * @param numChannels the number of allowed channels. Must be greater than 0
719 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700720 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
722 * {@code numChannels} is outside the valid range.
723 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700724 public synchronized boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800725 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700726 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -0700728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 /*
730 * Validate the argument. We'd like to let the Wi-Fi driver do this,
731 * but if Wi-Fi isn't currently enabled, that's not possible, and
732 * we want to persist the setting anyway,so that it will take
733 * effect when Wi-Fi does become enabled.
734 */
735 boolean found = false;
736 for (int validChan : sValidRegulatoryChannelCounts) {
737 if (validChan == numChannels) {
738 found = true;
739 break;
740 }
741 }
742 if (!found) {
743 return false;
744 }
745
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700746 if (persist) {
747 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -0700748 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
749 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700750 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700751
Irfan Sheriff0d255342010-07-28 09:35:20 -0700752 mWifiStateMachine.setNumAllowedChannels(numChannels);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700753
754 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 }
756
757 /**
758 * Return the number of frequency channels that are allowed
759 * to be used in the current regulatory domain.
760 * @return the number of allowed channels, or {@code -1} if an error occurs
761 */
762 public int getNumAllowedChannels() {
763 int numChannels;
764
765 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800766
767 /*
768 * If we can't get the value from the driver (e.g., because
769 * Wi-Fi is not currently enabled), get the value from
770 * Settings.
771 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700772 numChannels = mWifiStateMachine.getNumAllowedChannels();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800773 if (numChannels < 0) {
774 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
775 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
776 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
778 return numChannels;
779 }
780
781 /**
782 * Return the list of valid values for the number of allowed radio channels
783 * for various regulatory domains.
784 * @return the list of channel counts
785 */
786 public int[] getValidChannelCounts() {
787 enforceAccessPermission();
788 return sValidRegulatoryChannelCounts;
789 }
790
791 /**
792 * Return the DHCP-assigned addresses from the last successful DHCP request,
793 * if any.
794 * @return the DHCP information
795 */
796 public DhcpInfo getDhcpInfo() {
797 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700798 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 }
800
Irfan Sheriff0d255342010-07-28 09:35:20 -0700801 /**
802 * see {@link android.net.wifi.WifiManager#startWifi}
803 *
804 */
805 public void startWifi() {
806 enforceChangePermission();
807 /* TODO: may be add permissions for access only to connectivity service
808 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
809 * of WifiLock & device idle status unless wifi enabled status is toggled
810 */
811
812 mWifiStateMachine.setDriverStart(true);
813 mWifiStateMachine.reconnectCommand();
814 }
815
816 /**
817 * see {@link android.net.wifi.WifiManager#stopWifi}
818 *
819 */
820 public void stopWifi() {
821 enforceChangePermission();
822 /* TODO: may be add permissions for access only to connectivity service
823 * TODO: if a stop is issued, wifi is brought up only by startWifi
824 * unless wifi enabled status is toggled
825 */
826 mWifiStateMachine.setDriverStart(false);
827 }
828
829
830 /**
831 * see {@link android.net.wifi.WifiManager#addToBlacklist}
832 *
833 */
834 public void addToBlacklist(String bssid) {
835 enforceChangePermission();
836
837 mWifiStateMachine.addToBlacklist(bssid);
838 }
839
840 /**
841 * see {@link android.net.wifi.WifiManager#clearBlacklist}
842 *
843 */
844 public void clearBlacklist() {
845 enforceChangePermission();
846
847 mWifiStateMachine.clearBlacklist();
848 }
849
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700850 public void connectNetworkWithId(int networkId) {
851 enforceChangePermission();
852 mWifiStateMachine.connectNetwork(networkId);
853 }
854
855 public void connectNetworkWithConfig(WifiConfiguration config) {
856 enforceChangePermission();
857 mWifiStateMachine.connectNetwork(config);
858 }
859
860 public void saveNetwork(WifiConfiguration config) {
861 enforceChangePermission();
862 mWifiStateMachine.saveNetwork(config);
863 }
864
865 public void forgetNetwork(int netId) {
866 enforceChangePermission();
867 mWifiStateMachine.forgetNetwork(netId);
868 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700869
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700870 public void startWpsPbc(String bssid) {
871 enforceChangePermission();
872 mWifiStateMachine.startWpsPbc(bssid);
873 }
874
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700875 public void startWpsWithPinFromAccessPoint(String bssid, int apPin) {
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700876 enforceChangePermission();
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700877 mWifiStateMachine.startWpsWithPinFromAccessPoint(bssid, apPin);
878 }
879
880 public int startWpsWithPinFromDevice(String bssid) {
881 enforceChangePermission();
882 if (mChannel != null) {
883 return mWifiStateMachine.syncStartWpsWithPinFromDevice(mChannel, bssid);
884 } else {
885 Slog.e(TAG, "mChannel is not initialized");
886 return -1;
887 }
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700888 }
889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
891 @Override
892 public void onReceive(Context context, Intent intent) {
893 String action = intent.getAction();
894
Doug Zongker43866e02010-01-07 12:09:54 -0800895 long idleMillis =
896 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700897 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800899 Settings.System.getInt(mContext.getContentResolver(),
900 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400902 if (DBG) {
903 Slog.d(TAG, "ACTION_SCREEN_ON");
904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 mAlarmManager.cancel(mIdleIntent);
906 mDeviceIdle = false;
907 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700908 // Once the screen is on, we are not keeping WIFI running
909 // because of any locks so clear that tracking immediately.
910 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700911 mWifiStateMachine.enableRssiPolling(true);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700912 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400914 if (DBG) {
915 Slog.d(TAG, "ACTION_SCREEN_OFF");
916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700918 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 /*
920 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
921 * AND the "stay on while plugged in" setting doesn't match the
922 * current power conditions (i.e, not plugged in, plugged in to USB,
923 * or plugged in to AC).
924 */
925 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700926 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700927 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700928 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700929 // we don't have time to track down for this release. Delay instead,
930 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700931 // TODO - fix the race conditions and switch back to the immediate turn-off
932 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400933 if (DBG) {
934 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
935 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700936 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
937 // // do not keep Wifi awake when screen is off if Wifi is not associated
938 // mDeviceIdle = true;
939 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400940 } else {
941 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400942 if (DBG) {
943 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
944 + "ms");
945 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400946 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400950 if (DBG) {
951 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700954 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700955 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
957 /*
958 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
959 * AND we are transitioning from a state in which the device was supposed
960 * to stay awake to a state in which it is not supposed to stay awake.
961 * If "stay awake" state is not changing, we do nothing, to avoid resetting
962 * the already-set timer.
963 */
964 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400965 if (DBG) {
966 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
969 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
970 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400971 if (DBG) {
972 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976 mPluggedType = pluggedType;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700977 } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
978 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
979 BluetoothA2dp.STATE_NOT_PLAYING);
980 mWifiStateMachine.setBluetoothScanMode(state == BluetoothA2dp.STATE_PLAYING);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700981 } else if (action.equals(ACTION_START_SCAN)) {
982 mWifiStateMachine.startScan(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 }
985
986 /**
987 * Determines whether the Wi-Fi chipset should stay awake or be put to
988 * sleep. Looks at the setting for the sleep policy and the current
989 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800990 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 * @see #shouldDeviceStayAwake(int, int)
992 */
993 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
994 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
995 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
996
997 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
998 // Never sleep
999 return true;
1000 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1001 (pluggedType != 0)) {
1002 // Never sleep while plugged, and we're plugged
1003 return true;
1004 } else {
1005 // Default
1006 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1007 }
1008 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 /**
1011 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1012 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1013 * of {@code 0} isn't really a plugged type, but rather an indication that the
1014 * device isn't plugged in at all, there is no bit value corresponding to a
1015 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -07001016 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1018 * keep the device (and hence Wi-Fi) awake.
1019 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1020 * being made
1021 * @return {@code true} if {@code pluggedType} indicates that the device is
1022 * supposed to stay awake, {@code false} otherwise.
1023 */
1024 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1025 return (stayAwakeConditions & pluggedType) != 0;
1026 }
1027 };
1028
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001029 private synchronized void reportStartWorkSource() {
1030 mTmpWorkSource.clear();
1031 if (mDeviceIdle) {
1032 for (int i=0; i<mLocks.mList.size(); i++) {
1033 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001034 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001035 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001036 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001037 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 private void updateWifiState() {
1040 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001041 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 boolean lockHeld = mLocks.hasLocks();
1043 int strongestLockMode;
1044 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1045 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1046 if (mDeviceIdle && lockHeld) {
1047 strongestLockMode = mLocks.getStrongestLockMode();
1048 } else {
1049 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1050 }
1051
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001052 /* Scan interval when driver is started */
1053 long scanMs = Settings.Secure.getLong(mContext.getContentResolver(),
1054 Settings.Secure.WIFI_SCAN_INTERVAL_MS, DEFAULT_SCAN_INTERVAL_MS);
1055
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001056 /* Disable tethering when airplane mode is enabled */
1057 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001058 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001059 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001060
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001061 if (wifiShouldBeEnabled) {
1062 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001063 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001064 mWifiStateMachine.setWifiEnabled(true);
1065 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001066 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001067 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001068 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
1069 System.currentTimeMillis() + scanMs, scanMs, mScanIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001071 mWifiStateMachine.requestCmWakeLock();
1072 mWifiStateMachine.setDriverStart(false);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001073 mAlarmManager.cancel(mScanIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001075 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001076 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
1078 }
1079
1080 private void registerForBroadcasts() {
1081 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1083 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1084 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1085 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001086 intentFilter.addAction(ACTION_START_SCAN);
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001087 intentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 mContext.registerReceiver(mReceiver, intentFilter);
1089 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 private boolean isAirplaneSensitive() {
1092 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1093 Settings.System.AIRPLANE_MODE_RADIOS);
1094 return airplaneModeRadios == null
1095 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1096 }
1097
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001098 private boolean isAirplaneToggleable() {
1099 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1100 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1101 return toggleableRadios != null
1102 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1103 }
1104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 /**
1106 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1107 * currently on.
1108 * @return {@code true} if airplane mode is on.
1109 */
1110 private boolean isAirplaneModeOn() {
1111 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1112 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1113 }
1114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 @Override
1116 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1117 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1118 != PackageManager.PERMISSION_GRANTED) {
1119 pw.println("Permission Denial: can't dump WifiService from from pid="
1120 + Binder.getCallingPid()
1121 + ", uid=" + Binder.getCallingUid());
1122 return;
1123 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001124 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 pw.println("Stay-awake conditions: " +
1126 Settings.System.getInt(mContext.getContentResolver(),
1127 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1128 pw.println();
1129
1130 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001131 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 pw.println();
1133 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001134 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 if (scanResults != null && scanResults.size() != 0) {
1136 pw.println(" BSSID Frequency RSSI Flags SSID");
1137 for (ScanResult r : scanResults) {
1138 pw.printf(" %17s %9d %5d %-16s %s%n",
1139 r.BSSID,
1140 r.frequency,
1141 r.level,
1142 r.capabilities,
1143 r.SSID == null ? "" : r.SSID);
1144 }
1145 }
1146 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001147 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1148 mScanLocksAcquired + " scan");
1149 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1150 mScanLocksReleased + " scan");
1151 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 pw.println("Locks held:");
1153 mLocks.dump(pw);
1154 }
1155
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001156 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001157 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1158 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 }
1160
1161 public void binderDied() {
1162 synchronized (mLocks) {
1163 releaseWifiLockLocked(mBinder);
1164 }
1165 }
1166
1167 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001168 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
1170 }
1171
1172 private class LockList {
1173 private List<WifiLock> mList;
1174
1175 private LockList() {
1176 mList = new ArrayList<WifiLock>();
1177 }
1178
1179 private synchronized boolean hasLocks() {
1180 return !mList.isEmpty();
1181 }
1182
1183 private synchronized int getStrongestLockMode() {
1184 if (mList.isEmpty()) {
1185 return WifiManager.WIFI_MODE_FULL;
1186 }
1187 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001188 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 return WifiManager.WIFI_MODE_FULL;
1190 }
1191 }
1192 return WifiManager.WIFI_MODE_SCAN_ONLY;
1193 }
1194
1195 private void addLock(WifiLock lock) {
1196 if (findLockByBinder(lock.mBinder) < 0) {
1197 mList.add(lock);
1198 }
1199 }
1200
1201 private WifiLock removeLock(IBinder binder) {
1202 int index = findLockByBinder(binder);
1203 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001204 WifiLock ret = mList.remove(index);
1205 ret.unlinkDeathRecipient();
1206 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 } else {
1208 return null;
1209 }
1210 }
1211
1212 private int findLockByBinder(IBinder binder) {
1213 int size = mList.size();
1214 for (int i = size - 1; i >= 0; i--)
1215 if (mList.get(i).mBinder == binder)
1216 return i;
1217 return -1;
1218 }
1219
1220 private void dump(PrintWriter pw) {
1221 for (WifiLock l : mList) {
1222 pw.print(" ");
1223 pw.println(l);
1224 }
1225 }
1226 }
1227
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001228 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001229 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001230 return;
1231 }
1232 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1233 pid, uid, null);
1234 }
1235
1236 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1238 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1239 return false;
1240 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001241 if (ws != null && ws.size() == 0) {
1242 ws = null;
1243 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001244 if (ws != null) {
1245 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1246 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001247 if (ws == null) {
1248 ws = new WorkSource(Binder.getCallingUid());
1249 }
1250 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 synchronized (mLocks) {
1252 return acquireWifiLockLocked(wifiLock);
1253 }
1254 }
1255
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001256 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1257 switch(wifiLock.mMode) {
1258 case WifiManager.WIFI_MODE_FULL:
1259 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1260 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001261 case WifiManager.WIFI_MODE_SCAN_ONLY:
1262 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1263 break;
1264 }
1265 }
1266
1267 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1268 switch(wifiLock.mMode) {
1269 case WifiManager.WIFI_MODE_FULL:
1270 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1271 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001272 case WifiManager.WIFI_MODE_SCAN_ONLY:
1273 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1274 break;
1275 }
1276 }
1277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001279 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001282
The Android Open Source Project10592532009-03-18 17:39:46 -07001283 long ident = Binder.clearCallingIdentity();
1284 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001285 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001286 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001287 case WifiManager.WIFI_MODE_FULL:
1288 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001289 break;
1290 case WifiManager.WIFI_MODE_SCAN_ONLY:
1291 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001292 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001293 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001294
1295 // Be aggressive about adding new locks into the accounted state...
1296 // we want to over-report rather than under-report.
1297 reportStartWorkSource();
1298
1299 updateWifiState();
1300 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001301 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001302 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001303 } finally {
1304 Binder.restoreCallingIdentity(ident);
1305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 }
1307
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001308 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1309 int uid = Binder.getCallingUid();
1310 int pid = Binder.getCallingPid();
1311 if (ws != null && ws.size() == 0) {
1312 ws = null;
1313 }
1314 if (ws != null) {
1315 enforceWakeSourcePermission(uid, pid);
1316 }
1317 long ident = Binder.clearCallingIdentity();
1318 try {
1319 synchronized (mLocks) {
1320 int index = mLocks.findLockByBinder(lock);
1321 if (index < 0) {
1322 throw new IllegalArgumentException("Wifi lock not active");
1323 }
1324 WifiLock wl = mLocks.mList.get(index);
1325 noteReleaseWifiLock(wl);
1326 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1327 noteAcquireWifiLock(wl);
1328 }
1329 } catch (RemoteException e) {
1330 } finally {
1331 Binder.restoreCallingIdentity(ident);
1332 }
1333 }
1334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 public boolean releaseWifiLock(IBinder lock) {
1336 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1337 synchronized (mLocks) {
1338 return releaseWifiLockLocked(lock);
1339 }
1340 }
1341
1342 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001343 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001344
The Android Open Source Project10592532009-03-18 17:39:46 -07001345 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001346
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001347 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001348
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001349 hadLock = (wifiLock != null);
1350
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001351 long ident = Binder.clearCallingIdentity();
1352 try {
1353 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001354 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001355 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001356 case WifiManager.WIFI_MODE_FULL:
1357 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001358 break;
1359 case WifiManager.WIFI_MODE_SCAN_ONLY:
1360 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001361 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001362 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001363 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001364
1365 // TODO - should this only happen if you hadLock?
1366 updateWifiState();
1367
1368 } catch (RemoteException e) {
1369 } finally {
1370 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001371 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001372
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001373 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001375
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001376 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001377 implements IBinder.DeathRecipient {
1378 String mTag;
1379 int mMode;
1380 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001381 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001382
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001383 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001384 super();
1385 mTag = tag;
1386 mMode = mode;
1387 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001388 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001389 try {
1390 mBinder.linkToDeath(this, 0);
1391 } catch (RemoteException e) {
1392 binderDied();
1393 }
1394 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001395
1396 void unlinkDeathRecipient() {
1397 mBinder.unlinkToDeath(this, 0);
1398 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001399 }
1400
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001401 private class Multicaster extends DeathRecipient {
1402 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001403 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001404 }
1405
1406 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001407 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001408 synchronized (mMulticasters) {
1409 int i = mMulticasters.indexOf(this);
1410 if (i != -1) {
1411 removeMulticasterLocked(i, mMode);
1412 }
1413 }
1414 }
1415
1416 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001417 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001418 }
1419
1420 public int getUid() {
1421 return mMode;
1422 }
1423 }
1424
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001425 public void initializeMulticastFiltering() {
1426 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001427
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001428 synchronized (mMulticasters) {
1429 // if anybody had requested filters be off, leave off
1430 if (mMulticasters.size() != 0) {
1431 return;
1432 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001433 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001434 }
1435 }
1436 }
1437
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001438 public void acquireMulticastLock(IBinder binder, String tag) {
1439 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001440
1441 synchronized (mMulticasters) {
1442 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001443 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001444 // Note that we could call stopPacketFiltering only when
1445 // our new size == 1 (first call), but this function won't
1446 // be called often and by making the stopPacket call each
1447 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001448 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001449 }
1450
1451 int uid = Binder.getCallingUid();
1452 Long ident = Binder.clearCallingIdentity();
1453 try {
1454 mBatteryStats.noteWifiMulticastEnabled(uid);
1455 } catch (RemoteException e) {
1456 } finally {
1457 Binder.restoreCallingIdentity(ident);
1458 }
1459 }
1460
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001461 public void releaseMulticastLock() {
1462 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001463
1464 int uid = Binder.getCallingUid();
1465 synchronized (mMulticasters) {
1466 mMulticastDisabled++;
1467 int size = mMulticasters.size();
1468 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001469 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001470 if ((m != null) && (m.getUid() == uid)) {
1471 removeMulticasterLocked(i, uid);
1472 }
1473 }
1474 }
1475 }
1476
1477 private void removeMulticasterLocked(int i, int uid)
1478 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001479 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001480
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001481 if (removed != null) {
1482 removed.unlinkDeathRecipient();
1483 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001484 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001485 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001486 }
1487
1488 Long ident = Binder.clearCallingIdentity();
1489 try {
1490 mBatteryStats.noteWifiMulticastDisabled(uid);
1491 } catch (RemoteException e) {
1492 } finally {
1493 Binder.restoreCallingIdentity(ident);
1494 }
1495 }
1496
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001497 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001498 enforceAccessPermission();
1499
1500 synchronized (mMulticasters) {
1501 return (mMulticasters.size() > 0);
1502 }
1503 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001504
1505 private void checkAndSetNotification() {
1506 // If we shouldn't place a notification on available networks, then
1507 // don't bother doing any of the following
1508 if (!mNotificationEnabled) return;
1509
1510 State state = mNetworkInfo.getState();
1511 if ((state == NetworkInfo.State.DISCONNECTED)
1512 || (state == NetworkInfo.State.UNKNOWN)) {
1513 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001514 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001515 if (scanResults != null) {
1516 int numOpenNetworks = 0;
1517 for (int i = scanResults.size() - 1; i >= 0; i--) {
1518 ScanResult scanResult = scanResults.get(i);
1519
1520 if (TextUtils.isEmpty(scanResult.capabilities)) {
1521 numOpenNetworks++;
1522 }
1523 }
1524
1525 if (numOpenNetworks > 0) {
1526 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1527 /*
1528 * We've scanned continuously at least
1529 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1530 * probably does not have a remembered network in range,
1531 * since otherwise supplicant would have tried to
1532 * associate and thus resetting this counter.
1533 */
1534 setNotificationVisible(true, numOpenNetworks, false, 0);
1535 }
1536 return;
1537 }
1538 }
1539 }
1540
1541 // No open networks in range, remove the notification
1542 setNotificationVisible(false, 0, false, 0);
1543 }
1544
1545 /**
1546 * Clears variables related to tracking whether a notification has been
1547 * shown recently and clears the current notification.
1548 */
1549 private void resetNotification() {
1550 mNotificationRepeatTime = 0;
1551 mNumScansSinceNetworkStateChange = 0;
1552 setNotificationVisible(false, 0, false, 0);
1553 }
1554
1555 /**
1556 * Display or don't display a notification that there are open Wi-Fi networks.
1557 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1558 * @param numNetworks the number networks seen
1559 * @param force {@code true} to force notification to be shown/not-shown,
1560 * even if it is already shown/not-shown.
1561 * @param delay time in milliseconds after which the notification should be made
1562 * visible or invisible.
1563 */
1564 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1565 int delay) {
1566
1567 // Since we use auto cancel on the notification, when the
1568 // mNetworksAvailableNotificationShown is true, the notification may
1569 // have actually been canceled. However, when it is false we know
1570 // for sure that it is not being shown (it will not be shown any other
1571 // place than here)
1572
1573 // If it should be hidden and it is already hidden, then noop
1574 if (!visible && !mNotificationShown && !force) {
1575 return;
1576 }
1577
1578 NotificationManager notificationManager = (NotificationManager) mContext
1579 .getSystemService(Context.NOTIFICATION_SERVICE);
1580
1581 Message message;
1582 if (visible) {
1583
1584 // Not enough time has passed to show the notification again
1585 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1586 return;
1587 }
1588
1589 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001590 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001591 mNotification = new Notification();
1592 mNotification.when = 0;
1593 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1594 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1595 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1596 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1597 }
1598
1599 CharSequence title = mContext.getResources().getQuantityText(
1600 com.android.internal.R.plurals.wifi_available, numNetworks);
1601 CharSequence details = mContext.getResources().getQuantityText(
1602 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1603 mNotification.tickerText = title;
1604 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1605
1606 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1607
1608 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001609 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001610 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001611 }
1612
Irfan Sheriff0d255342010-07-28 09:35:20 -07001613 mNotificationShown = visible;
1614 }
1615
1616 private class NotificationEnabledSettingObserver extends ContentObserver {
1617
1618 public NotificationEnabledSettingObserver(Handler handler) {
1619 super(handler);
1620 }
1621
1622 public void register() {
1623 ContentResolver cr = mContext.getContentResolver();
1624 cr.registerContentObserver(Settings.Secure.getUriFor(
1625 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1626 mNotificationEnabled = getValue();
1627 }
1628
1629 @Override
1630 public void onChange(boolean selfChange) {
1631 super.onChange(selfChange);
1632
1633 mNotificationEnabled = getValue();
1634 resetNotification();
1635 }
1636
1637 private boolean getValue() {
1638 return Settings.Secure.getInt(mContext.getContentResolver(),
1639 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1640 }
1641 }
1642
1643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644}