blob: 4f753663c8cfe7652287dcdaa855eda779870b76 [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
875 public void startWpsPin(String bssid, int apPin) {
876 enforceChangePermission();
877 mWifiStateMachine.startWpsPin(bssid, apPin);
878 }
879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
881 @Override
882 public void onReceive(Context context, Intent intent) {
883 String action = intent.getAction();
884
Doug Zongker43866e02010-01-07 12:09:54 -0800885 long idleMillis =
886 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700887 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800889 Settings.System.getInt(mContext.getContentResolver(),
890 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400892 if (DBG) {
893 Slog.d(TAG, "ACTION_SCREEN_ON");
894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 mAlarmManager.cancel(mIdleIntent);
896 mDeviceIdle = false;
897 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700898 // Once the screen is on, we are not keeping WIFI running
899 // because of any locks so clear that tracking immediately.
900 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700901 mWifiStateMachine.enableRssiPolling(true);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700902 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400904 if (DBG) {
905 Slog.d(TAG, "ACTION_SCREEN_OFF");
906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700908 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 /*
910 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
911 * AND the "stay on while plugged in" setting doesn't match the
912 * current power conditions (i.e, not plugged in, plugged in to USB,
913 * or plugged in to AC).
914 */
915 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700916 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700917 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700918 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700919 // we don't have time to track down for this release. Delay instead,
920 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700921 // TODO - fix the race conditions and switch back to the immediate turn-off
922 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400923 if (DBG) {
924 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
925 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700926 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
927 // // do not keep Wifi awake when screen is off if Wifi is not associated
928 // mDeviceIdle = true;
929 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400930 } else {
931 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400932 if (DBG) {
933 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
934 + "ms");
935 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400936 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400940 if (DBG) {
941 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700944 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700945 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
947 /*
948 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
949 * AND we are transitioning from a state in which the device was supposed
950 * to stay awake to a state in which it is not supposed to stay awake.
951 * If "stay awake" state is not changing, we do nothing, to avoid resetting
952 * the already-set timer.
953 */
954 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400955 if (DBG) {
956 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
959 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
960 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400961 if (DBG) {
962 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 }
966 mPluggedType = pluggedType;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700967 } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
968 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
969 BluetoothA2dp.STATE_NOT_PLAYING);
970 mWifiStateMachine.setBluetoothScanMode(state == BluetoothA2dp.STATE_PLAYING);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700971 } else if (action.equals(ACTION_START_SCAN)) {
972 mWifiStateMachine.startScan(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 }
975
976 /**
977 * Determines whether the Wi-Fi chipset should stay awake or be put to
978 * sleep. Looks at the setting for the sleep policy and the current
979 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800980 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 * @see #shouldDeviceStayAwake(int, int)
982 */
983 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
984 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
985 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
986
987 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
988 // Never sleep
989 return true;
990 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
991 (pluggedType != 0)) {
992 // Never sleep while plugged, and we're plugged
993 return true;
994 } else {
995 // Default
996 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
997 }
998 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 /**
1001 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1002 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1003 * of {@code 0} isn't really a plugged type, but rather an indication that the
1004 * device isn't plugged in at all, there is no bit value corresponding to a
1005 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -07001006 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1008 * keep the device (and hence Wi-Fi) awake.
1009 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1010 * being made
1011 * @return {@code true} if {@code pluggedType} indicates that the device is
1012 * supposed to stay awake, {@code false} otherwise.
1013 */
1014 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1015 return (stayAwakeConditions & pluggedType) != 0;
1016 }
1017 };
1018
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001019 private synchronized void reportStartWorkSource() {
1020 mTmpWorkSource.clear();
1021 if (mDeviceIdle) {
1022 for (int i=0; i<mLocks.mList.size(); i++) {
1023 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001024 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001025 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001026 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001027 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 private void updateWifiState() {
1030 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001031 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 boolean lockHeld = mLocks.hasLocks();
1033 int strongestLockMode;
1034 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1035 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1036 if (mDeviceIdle && lockHeld) {
1037 strongestLockMode = mLocks.getStrongestLockMode();
1038 } else {
1039 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1040 }
1041
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001042 /* Scan interval when driver is started */
1043 long scanMs = Settings.Secure.getLong(mContext.getContentResolver(),
1044 Settings.Secure.WIFI_SCAN_INTERVAL_MS, DEFAULT_SCAN_INTERVAL_MS);
1045
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001046 /* Disable tethering when airplane mode is enabled */
1047 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001048 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001049 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001050
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001051 if (wifiShouldBeEnabled) {
1052 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001053 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001054 mWifiStateMachine.setWifiEnabled(true);
1055 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001056 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001057 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001058 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
1059 System.currentTimeMillis() + scanMs, scanMs, mScanIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001061 mWifiStateMachine.requestCmWakeLock();
1062 mWifiStateMachine.setDriverStart(false);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001063 mAlarmManager.cancel(mScanIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001065 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001066 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068 }
1069
1070 private void registerForBroadcasts() {
1071 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1073 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1074 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1075 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001076 intentFilter.addAction(ACTION_START_SCAN);
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001077 intentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 mContext.registerReceiver(mReceiver, intentFilter);
1079 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 private boolean isAirplaneSensitive() {
1082 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1083 Settings.System.AIRPLANE_MODE_RADIOS);
1084 return airplaneModeRadios == null
1085 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1086 }
1087
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001088 private boolean isAirplaneToggleable() {
1089 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1090 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1091 return toggleableRadios != null
1092 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1093 }
1094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 /**
1096 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1097 * currently on.
1098 * @return {@code true} if airplane mode is on.
1099 */
1100 private boolean isAirplaneModeOn() {
1101 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1102 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1103 }
1104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 @Override
1106 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1107 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1108 != PackageManager.PERMISSION_GRANTED) {
1109 pw.println("Permission Denial: can't dump WifiService from from pid="
1110 + Binder.getCallingPid()
1111 + ", uid=" + Binder.getCallingUid());
1112 return;
1113 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001114 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 pw.println("Stay-awake conditions: " +
1116 Settings.System.getInt(mContext.getContentResolver(),
1117 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1118 pw.println();
1119
1120 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001121 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 pw.println();
1123 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001124 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 if (scanResults != null && scanResults.size() != 0) {
1126 pw.println(" BSSID Frequency RSSI Flags SSID");
1127 for (ScanResult r : scanResults) {
1128 pw.printf(" %17s %9d %5d %-16s %s%n",
1129 r.BSSID,
1130 r.frequency,
1131 r.level,
1132 r.capabilities,
1133 r.SSID == null ? "" : r.SSID);
1134 }
1135 }
1136 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001137 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1138 mScanLocksAcquired + " scan");
1139 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1140 mScanLocksReleased + " scan");
1141 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 pw.println("Locks held:");
1143 mLocks.dump(pw);
1144 }
1145
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001146 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001147 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1148 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150
1151 public void binderDied() {
1152 synchronized (mLocks) {
1153 releaseWifiLockLocked(mBinder);
1154 }
1155 }
1156
1157 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001158 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 }
1160 }
1161
1162 private class LockList {
1163 private List<WifiLock> mList;
1164
1165 private LockList() {
1166 mList = new ArrayList<WifiLock>();
1167 }
1168
1169 private synchronized boolean hasLocks() {
1170 return !mList.isEmpty();
1171 }
1172
1173 private synchronized int getStrongestLockMode() {
1174 if (mList.isEmpty()) {
1175 return WifiManager.WIFI_MODE_FULL;
1176 }
1177 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001178 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 return WifiManager.WIFI_MODE_FULL;
1180 }
1181 }
1182 return WifiManager.WIFI_MODE_SCAN_ONLY;
1183 }
1184
1185 private void addLock(WifiLock lock) {
1186 if (findLockByBinder(lock.mBinder) < 0) {
1187 mList.add(lock);
1188 }
1189 }
1190
1191 private WifiLock removeLock(IBinder binder) {
1192 int index = findLockByBinder(binder);
1193 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001194 WifiLock ret = mList.remove(index);
1195 ret.unlinkDeathRecipient();
1196 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 } else {
1198 return null;
1199 }
1200 }
1201
1202 private int findLockByBinder(IBinder binder) {
1203 int size = mList.size();
1204 for (int i = size - 1; i >= 0; i--)
1205 if (mList.get(i).mBinder == binder)
1206 return i;
1207 return -1;
1208 }
1209
1210 private void dump(PrintWriter pw) {
1211 for (WifiLock l : mList) {
1212 pw.print(" ");
1213 pw.println(l);
1214 }
1215 }
1216 }
1217
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001218 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001219 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001220 return;
1221 }
1222 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1223 pid, uid, null);
1224 }
1225
1226 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1228 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1229 return false;
1230 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001231 if (ws != null && ws.size() == 0) {
1232 ws = null;
1233 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001234 if (ws != null) {
1235 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1236 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001237 if (ws == null) {
1238 ws = new WorkSource(Binder.getCallingUid());
1239 }
1240 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 synchronized (mLocks) {
1242 return acquireWifiLockLocked(wifiLock);
1243 }
1244 }
1245
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001246 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1247 switch(wifiLock.mMode) {
1248 case WifiManager.WIFI_MODE_FULL:
1249 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1250 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001251 case WifiManager.WIFI_MODE_SCAN_ONLY:
1252 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1253 break;
1254 }
1255 }
1256
1257 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1258 switch(wifiLock.mMode) {
1259 case WifiManager.WIFI_MODE_FULL:
1260 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1261 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001262 case WifiManager.WIFI_MODE_SCAN_ONLY:
1263 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1264 break;
1265 }
1266 }
1267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001269 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001272
The Android Open Source Project10592532009-03-18 17:39:46 -07001273 long ident = Binder.clearCallingIdentity();
1274 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001275 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001276 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001277 case WifiManager.WIFI_MODE_FULL:
1278 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001279 break;
1280 case WifiManager.WIFI_MODE_SCAN_ONLY:
1281 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001282 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001283 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001284
1285 // Be aggressive about adding new locks into the accounted state...
1286 // we want to over-report rather than under-report.
1287 reportStartWorkSource();
1288
1289 updateWifiState();
1290 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001291 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001292 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001293 } finally {
1294 Binder.restoreCallingIdentity(ident);
1295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 }
1297
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001298 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1299 int uid = Binder.getCallingUid();
1300 int pid = Binder.getCallingPid();
1301 if (ws != null && ws.size() == 0) {
1302 ws = null;
1303 }
1304 if (ws != null) {
1305 enforceWakeSourcePermission(uid, pid);
1306 }
1307 long ident = Binder.clearCallingIdentity();
1308 try {
1309 synchronized (mLocks) {
1310 int index = mLocks.findLockByBinder(lock);
1311 if (index < 0) {
1312 throw new IllegalArgumentException("Wifi lock not active");
1313 }
1314 WifiLock wl = mLocks.mList.get(index);
1315 noteReleaseWifiLock(wl);
1316 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1317 noteAcquireWifiLock(wl);
1318 }
1319 } catch (RemoteException e) {
1320 } finally {
1321 Binder.restoreCallingIdentity(ident);
1322 }
1323 }
1324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 public boolean releaseWifiLock(IBinder lock) {
1326 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1327 synchronized (mLocks) {
1328 return releaseWifiLockLocked(lock);
1329 }
1330 }
1331
1332 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001333 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001334
The Android Open Source Project10592532009-03-18 17:39:46 -07001335 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001336
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001337 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001338
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001339 hadLock = (wifiLock != null);
1340
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001341 long ident = Binder.clearCallingIdentity();
1342 try {
1343 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001344 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001345 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001346 case WifiManager.WIFI_MODE_FULL:
1347 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001348 break;
1349 case WifiManager.WIFI_MODE_SCAN_ONLY:
1350 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001351 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001352 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001353 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001354
1355 // TODO - should this only happen if you hadLock?
1356 updateWifiState();
1357
1358 } catch (RemoteException e) {
1359 } finally {
1360 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001361 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001362
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001363 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001365
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001366 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001367 implements IBinder.DeathRecipient {
1368 String mTag;
1369 int mMode;
1370 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001371 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001372
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001373 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001374 super();
1375 mTag = tag;
1376 mMode = mode;
1377 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001378 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001379 try {
1380 mBinder.linkToDeath(this, 0);
1381 } catch (RemoteException e) {
1382 binderDied();
1383 }
1384 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001385
1386 void unlinkDeathRecipient() {
1387 mBinder.unlinkToDeath(this, 0);
1388 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001389 }
1390
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001391 private class Multicaster extends DeathRecipient {
1392 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001393 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001394 }
1395
1396 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001397 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001398 synchronized (mMulticasters) {
1399 int i = mMulticasters.indexOf(this);
1400 if (i != -1) {
1401 removeMulticasterLocked(i, mMode);
1402 }
1403 }
1404 }
1405
1406 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001407 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001408 }
1409
1410 public int getUid() {
1411 return mMode;
1412 }
1413 }
1414
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001415 public void initializeMulticastFiltering() {
1416 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001417
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001418 synchronized (mMulticasters) {
1419 // if anybody had requested filters be off, leave off
1420 if (mMulticasters.size() != 0) {
1421 return;
1422 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001423 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001424 }
1425 }
1426 }
1427
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001428 public void acquireMulticastLock(IBinder binder, String tag) {
1429 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001430
1431 synchronized (mMulticasters) {
1432 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001433 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001434 // Note that we could call stopPacketFiltering only when
1435 // our new size == 1 (first call), but this function won't
1436 // be called often and by making the stopPacket call each
1437 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001438 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001439 }
1440
1441 int uid = Binder.getCallingUid();
1442 Long ident = Binder.clearCallingIdentity();
1443 try {
1444 mBatteryStats.noteWifiMulticastEnabled(uid);
1445 } catch (RemoteException e) {
1446 } finally {
1447 Binder.restoreCallingIdentity(ident);
1448 }
1449 }
1450
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001451 public void releaseMulticastLock() {
1452 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001453
1454 int uid = Binder.getCallingUid();
1455 synchronized (mMulticasters) {
1456 mMulticastDisabled++;
1457 int size = mMulticasters.size();
1458 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001459 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001460 if ((m != null) && (m.getUid() == uid)) {
1461 removeMulticasterLocked(i, uid);
1462 }
1463 }
1464 }
1465 }
1466
1467 private void removeMulticasterLocked(int i, int uid)
1468 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001469 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001470
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001471 if (removed != null) {
1472 removed.unlinkDeathRecipient();
1473 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001474 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001475 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001476 }
1477
1478 Long ident = Binder.clearCallingIdentity();
1479 try {
1480 mBatteryStats.noteWifiMulticastDisabled(uid);
1481 } catch (RemoteException e) {
1482 } finally {
1483 Binder.restoreCallingIdentity(ident);
1484 }
1485 }
1486
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001487 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001488 enforceAccessPermission();
1489
1490 synchronized (mMulticasters) {
1491 return (mMulticasters.size() > 0);
1492 }
1493 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001494
1495 private void checkAndSetNotification() {
1496 // If we shouldn't place a notification on available networks, then
1497 // don't bother doing any of the following
1498 if (!mNotificationEnabled) return;
1499
1500 State state = mNetworkInfo.getState();
1501 if ((state == NetworkInfo.State.DISCONNECTED)
1502 || (state == NetworkInfo.State.UNKNOWN)) {
1503 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001504 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001505 if (scanResults != null) {
1506 int numOpenNetworks = 0;
1507 for (int i = scanResults.size() - 1; i >= 0; i--) {
1508 ScanResult scanResult = scanResults.get(i);
1509
1510 if (TextUtils.isEmpty(scanResult.capabilities)) {
1511 numOpenNetworks++;
1512 }
1513 }
1514
1515 if (numOpenNetworks > 0) {
1516 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1517 /*
1518 * We've scanned continuously at least
1519 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1520 * probably does not have a remembered network in range,
1521 * since otherwise supplicant would have tried to
1522 * associate and thus resetting this counter.
1523 */
1524 setNotificationVisible(true, numOpenNetworks, false, 0);
1525 }
1526 return;
1527 }
1528 }
1529 }
1530
1531 // No open networks in range, remove the notification
1532 setNotificationVisible(false, 0, false, 0);
1533 }
1534
1535 /**
1536 * Clears variables related to tracking whether a notification has been
1537 * shown recently and clears the current notification.
1538 */
1539 private void resetNotification() {
1540 mNotificationRepeatTime = 0;
1541 mNumScansSinceNetworkStateChange = 0;
1542 setNotificationVisible(false, 0, false, 0);
1543 }
1544
1545 /**
1546 * Display or don't display a notification that there are open Wi-Fi networks.
1547 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1548 * @param numNetworks the number networks seen
1549 * @param force {@code true} to force notification to be shown/not-shown,
1550 * even if it is already shown/not-shown.
1551 * @param delay time in milliseconds after which the notification should be made
1552 * visible or invisible.
1553 */
1554 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1555 int delay) {
1556
1557 // Since we use auto cancel on the notification, when the
1558 // mNetworksAvailableNotificationShown is true, the notification may
1559 // have actually been canceled. However, when it is false we know
1560 // for sure that it is not being shown (it will not be shown any other
1561 // place than here)
1562
1563 // If it should be hidden and it is already hidden, then noop
1564 if (!visible && !mNotificationShown && !force) {
1565 return;
1566 }
1567
1568 NotificationManager notificationManager = (NotificationManager) mContext
1569 .getSystemService(Context.NOTIFICATION_SERVICE);
1570
1571 Message message;
1572 if (visible) {
1573
1574 // Not enough time has passed to show the notification again
1575 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1576 return;
1577 }
1578
1579 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001580 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001581 mNotification = new Notification();
1582 mNotification.when = 0;
1583 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1584 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1585 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1586 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1587 }
1588
1589 CharSequence title = mContext.getResources().getQuantityText(
1590 com.android.internal.R.plurals.wifi_available, numNetworks);
1591 CharSequence details = mContext.getResources().getQuantityText(
1592 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1593 mNotification.tickerText = title;
1594 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1595
1596 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1597
1598 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001599 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001600 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001601 }
1602
Irfan Sheriff0d255342010-07-28 09:35:20 -07001603 mNotificationShown = visible;
1604 }
1605
1606 private class NotificationEnabledSettingObserver extends ContentObserver {
1607
1608 public NotificationEnabledSettingObserver(Handler handler) {
1609 super(handler);
1610 }
1611
1612 public void register() {
1613 ContentResolver cr = mContext.getContentResolver();
1614 cr.registerContentObserver(Settings.Secure.getUriFor(
1615 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1616 mNotificationEnabled = getValue();
1617 }
1618
1619 @Override
1620 public void onChange(boolean selfChange) {
1621 super.onChange(selfChange);
1622
1623 mNotificationEnabled = getValue();
1624 resetNotification();
1625 }
1626
1627 private boolean getValue() {
1628 return Settings.Secure.getInt(mContext.getContentResolver(),
1629 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1630 }
1631 }
1632
1633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634}