blob: 9687aa7e97f5ab3e31303a0002f56ba41ae167f9 [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
Irfan Sheriff5876a422010-08-12 20:26:23 -0700105 private int mFullHighPerfLocksAcquired;
106 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700107 private int mFullLocksAcquired;
108 private int mFullLocksReleased;
109 private int mScanLocksAcquired;
110 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700111
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700112 private final List<Multicaster> mMulticasters =
113 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700114 private int mMulticastEnabled;
115 private int mMulticastDisabled;
116
The Android Open Source Project10592532009-03-18 17:39:46 -0700117 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800118
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800119 ConnectivityManager mCm;
120 private String[] mWifiRegexs;
121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800123 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
124 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 * the approximate point at which the battery drain caused by Wi-Fi
126 * being enabled but not active exceeds the battery drain caused by
127 * re-establishing a connection to the mobile data network.
128 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700129 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
130
131 /**
132 * See {@link Settings.Secure#WIFI_SCAN_INTERVAL_MS}. This is the default value if a
133 * Settings.Secure value is not present.
134 */
135 private static final long DEFAULT_SCAN_INTERVAL_MS = 60 * 1000; /* 1 minute */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private static final String ACTION_DEVICE_IDLE =
138 "com.android.server.WifiManager.action.DEVICE_IDLE";
139
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700140 private static final String ACTION_START_SCAN =
141 "com.android.server.WifiManager.action.START_SCAN";
142
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700143 private boolean mIsReceiverRegistered = false;
144
Irfan Sheriff0d255342010-07-28 09:35:20 -0700145
146 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
147
148 // Variables relating to the 'available networks' notification
149 /**
150 * The icon to show in the 'available networks' notification. This will also
151 * be the ID of the Notification given to the NotificationManager.
152 */
153 private static final int ICON_NETWORKS_AVAILABLE =
154 com.android.internal.R.drawable.stat_notify_wifi_in_range;
155 /**
156 * When a notification is shown, we wait this amount before possibly showing it again.
157 */
158 private final long NOTIFICATION_REPEAT_DELAY_MS;
159 /**
160 * Whether the user has set the setting to show the 'available networks' notification.
161 */
162 private boolean mNotificationEnabled;
163 /**
164 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
165 */
166 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
167 /**
168 * The {@link System#currentTimeMillis()} must be at least this value for us
169 * to show the notification again.
170 */
171 private long mNotificationRepeatTime;
172 /**
173 * The Notification object given to the NotificationManager.
174 */
175 private Notification mNotification;
176 /**
177 * Whether the notification is being shown, as set by us. That is, if the
178 * user cancels the notification, we will not receive the callback so this
179 * will still be true. We only guarantee if this is false, then the
180 * notification is not showing.
181 */
182 private boolean mNotificationShown;
183 /**
184 * The number of continuous scans that must occur before consider the
185 * supplicant in a scanning state. This allows supplicant to associate with
186 * remembered networks that are in the scan results.
187 */
188 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
189 /**
190 * The number of scans since the last network state change. When this
191 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
192 * supplicant to actually be scanning. When the network state changes to
193 * something other than scanning, we reset this to 0.
194 */
195 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700196
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700197 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700198 * Asynchronous channel to WifiStateMachine
199 */
200 private AsyncChannel mChannel;
201
202 /**
203 * TODO: Possibly change WifiService into an AsyncService.
204 */
205 private class WifiServiceHandler extends Handler {
206 private AsyncChannel mWshChannel;
207
208 WifiServiceHandler(android.os.Looper looper, Context context) {
209 super(looper);
210 mWshChannel = new AsyncChannel();
211 mWshChannel.connect(context, this, mWifiStateMachine.getHandler(), 0);
212 }
213
214 @Override
215 public void handleMessage(Message msg) {
216 switch (msg.what) {
217 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
218 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
219 mChannel = mWshChannel;
220 } else {
221 Slog.d(TAG, "WifiServicehandler.handleMessage could not connect error=" +
222 msg.arg1);
223 mChannel = null;
224 }
225 break;
226 }
227 default: {
228 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
229 break;
230 }
231 }
232 }
233 }
234 WifiServiceHandler mHandler;
235
236 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700237 * Temporary for computing UIDS that are responsible for starting WIFI.
238 * Protected by mWifiStateTracker lock.
239 */
240 private final WorkSource mTmpWorkSource = new WorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700241
242 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700244 mWifiStateMachine = new WifiStateMachine(mContext);
245 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700246 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
249 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
250 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
251
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700252 Intent scanIntent = new Intent(ACTION_START_SCAN, null);
253 mScanIntent = PendingIntent.getBroadcast(mContext, SCAN_REQUEST, scanIntent, 0);
254
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700255 HandlerThread wifiThread = new HandlerThread("WifiService");
256 wifiThread.start();
Wink Saville4b7ba092010-10-20 15:37:41 -0700257 mHandler = new WifiServiceHandler(wifiThread.getLooper(), context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 mContext.registerReceiver(
260 new BroadcastReceiver() {
261 @Override
262 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700263 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700264 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700265 // on airplane disable, restore Wifi if the saved state indicates so
266 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
267 persistWifiEnabled(true);
268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 updateWifiState();
270 }
271 },
272 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
273
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800274 mContext.registerReceiver(
275 new BroadcastReceiver() {
276 @Override
277 public void onReceive(Context context, Intent intent) {
278
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700279 ArrayList<String> available = intent.getStringArrayListExtra(
280 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
281 ArrayList<String> active = intent.getStringArrayListExtra(
282 ConnectivityManager.EXTRA_ACTIVE_TETHER);
283 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800284
285 }
286 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700287
288 IntentFilter filter = new IntentFilter();
289 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
290 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
291 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
292
293 mContext.registerReceiver(
294 new BroadcastReceiver() {
295 @Override
296 public void onReceive(Context context, Intent intent) {
297 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
298 // reset & clear notification on any wifi state change
299 resetNotification();
300 } else if (intent.getAction().equals(
301 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
302 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
303 WifiManager.EXTRA_NETWORK_INFO);
304 // reset & clear notification on a network connect & disconnect
305 switch(mNetworkInfo.getDetailedState()) {
306 case CONNECTED:
307 case DISCONNECTED:
308 resetNotification();
309 break;
310 }
311 } else if (intent.getAction().equals(
312 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
313 checkAndSetNotification();
314 }
315 }
316 }, filter);
317
318 // Setting is in seconds
319 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
320 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
321 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
322 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800323 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800324
Irfan Sheriff7b009782010-03-11 16:37:45 -0800325 /**
326 * Check if Wi-Fi needs to be enabled and start
327 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700328 *
329 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800330 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700331 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700332 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700333 boolean wifiEnabled = !isAirplaneModeOn()
334 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800335 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
336 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700337 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800338 }
339
340 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
341
342 boolean wifiTethered = false;
343 boolean wifiAvailable = false;
344
345 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
346 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
347
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700348 if (mCm == null) {
349 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
350 }
351
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800352 mWifiRegexs = mCm.getTetherableWifiRegexs();
353
354 for (String intf : available) {
355 for (String regex : mWifiRegexs) {
356 if (intf.matches(regex)) {
357
358 InterfaceConfiguration ifcg = null;
359 try {
360 ifcg = service.getInterfaceConfig(intf);
361 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700362 /* IP/netmask: 192.168.43.1/255.255.255.0 */
363 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800364 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
Irfan Sheriff07bd5ae2010-10-28 14:45:56 -0700365 ifcg.interfaceFlags = "[up]";
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800366
367 service.setInterfaceConfig(intf, ifcg);
368 }
369 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800370 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700371 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800372 return;
373 }
374
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800375 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700376 Slog.e(TAG, "Error tethering on " + intf);
377 setWifiApEnabled(null, false);
378 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800379 }
380 break;
381 }
382 }
383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 }
385
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700386 private boolean testAndClearWifiSavedState() {
387 final ContentResolver cr = mContext.getContentResolver();
388 int wifiSavedState = 0;
389 try {
390 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
391 if(wifiSavedState == 1)
392 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
393 } catch (Settings.SettingNotFoundException e) {
394 ;
395 }
396 return (wifiSavedState == 1);
397 }
398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 private boolean getPersistedWifiEnabled() {
400 final ContentResolver cr = mContext.getContentResolver();
401 try {
402 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
403 } catch (Settings.SettingNotFoundException e) {
404 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
405 return false;
406 }
407 }
408
409 private void persistWifiEnabled(boolean enabled) {
410 final ContentResolver cr = mContext.getContentResolver();
411 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
412 }
413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 /**
415 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700416 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 */
418 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700419 enforceAccessPermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700420 if (mChannel != null) {
421 return mWifiStateMachine.syncPingSupplicant(mChannel);
422 } else {
423 Slog.e(TAG, "mChannel is not initialized");
424 return false;
425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 }
427
428 /**
429 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700431 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700433 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 }
435
436 private void enforceAccessPermission() {
437 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
438 "WifiService");
439 }
440
441 private void enforceChangePermission() {
442 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
443 "WifiService");
444
445 }
446
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700447 private void enforceMulticastChangePermission() {
448 mContext.enforceCallingOrSelfPermission(
449 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
450 "WifiService");
451 }
452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700454 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
455 * @param enable {@code true} to enable, {@code false} to disable.
456 * @return {@code true} if the enable/disable operation was
457 * started or is already in the queue.
458 */
459 public synchronized boolean setWifiEnabled(boolean enable) {
460 enforceChangePermission();
461
462 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700463 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700464 }
465
466 // set a flag if the user is enabling Wifi while in airplane mode
467 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
468 mAirplaneModeOverwridden.set(true);
469 }
470
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700471 if (enable) {
472 reportStartWorkSource();
473 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700474 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700475
476 /*
477 * Caller might not have WRITE_SECURE_SETTINGS,
478 * only CHANGE_WIFI_STATE is enforced
479 */
480 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700481 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700482 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700483
484 if (enable) {
485 if (!mIsReceiverRegistered) {
486 registerForBroadcasts();
487 mIsReceiverRegistered = true;
488 }
489 } else if (mIsReceiverRegistered){
490 mContext.unregisterReceiver(mReceiver);
491 mIsReceiverRegistered = false;
492 }
493
494 return true;
495 }
496
497 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 * see {@link WifiManager#getWifiState()}
499 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
500 * {@link WifiManager#WIFI_STATE_DISABLING},
501 * {@link WifiManager#WIFI_STATE_ENABLED},
502 * {@link WifiManager#WIFI_STATE_ENABLING},
503 * {@link WifiManager#WIFI_STATE_UNKNOWN}
504 */
505 public int getWifiEnabledState() {
506 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700507 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 }
509
510 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700511 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800512 * @param wifiConfig SSID, security and channel details as
513 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700514 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800515 * @return {@code true} if the start operation was
516 * started or is already in the queue.
517 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700518 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800519 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800520
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700521 if (enabled) {
522 /* Use default config if there is no existing config */
523 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
524 wifiConfig = new WifiConfiguration();
525 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
526 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
527 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700528 /*
529 * Caller might not have WRITE_SECURE_SETTINGS,
530 * only CHANGE_WIFI_STATE is enforced
531 */
532 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700533 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700534 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800535 }
536
Irfan Sheriff0d255342010-07-28 09:35:20 -0700537 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700538
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800539 return true;
540 }
541
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700542 /**
543 * see {@link WifiManager#getWifiApState()}
544 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
545 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
546 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
547 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
548 * {@link WifiManager#WIFI_AP_STATE_FAILED}
549 */
550 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700551 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700552 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700553 }
554
555 /**
556 * see {@link WifiManager#getWifiApConfiguration()}
557 * @return soft access point configuration
558 */
559 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800560 final ContentResolver cr = mContext.getContentResolver();
561 WifiConfiguration wifiConfig = new WifiConfiguration();
562 int authType;
563 try {
564 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
565 if (wifiConfig.SSID == null)
566 return null;
567 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
568 wifiConfig.allowedKeyManagement.set(authType);
569 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
570 return wifiConfig;
571 } catch (Settings.SettingNotFoundException e) {
572 Slog.e(TAG,"AP settings not found, returning");
573 return null;
574 }
575 }
576
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700577 /**
578 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
579 * @param wifiConfig WifiConfiguration details for soft access point
580 */
581 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700582 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800583 final ContentResolver cr = mContext.getContentResolver();
584 boolean isWpa;
585 if (wifiConfig == null)
586 return;
587 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
588 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
589 Settings.Secure.putInt(cr,
590 Settings.Secure.WIFI_AP_SECURITY,
591 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
592 if (isWpa)
593 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
594 }
595
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800596 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700597 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800598 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700599 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700600 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700601 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800602 }
603
604 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700605 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800606 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700607 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700608 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700609 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800610 }
611
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700612 /**
613 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700614 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700615 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700616 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700617 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800618 }
619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 /**
621 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
622 * @return the list of configured networks
623 */
624 public List<WifiConfiguration> getConfiguredNetworks() {
625 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700626 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800627 }
628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 /**
630 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
631 * @return the supplicant-assigned identifier for the new or updated
632 * network if the operation succeeds, or {@code -1} if it fails
633 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800634 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700636 if (mChannel != null) {
637 return mWifiStateMachine.syncAddOrUpdateNetwork(mChannel, config);
638 } else {
639 Slog.e(TAG, "mChannel is not initialized");
640 return -1;
641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 }
643
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700644 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
646 * @param netId the integer that identifies the network configuration
647 * to the supplicant
648 * @return {@code true} if the operation succeeded
649 */
650 public boolean removeNetwork(int netId) {
651 enforceChangePermission();
Wink Saville4b7ba092010-10-20 15:37:41 -0700652 if (mChannel != null) {
653 return mWifiStateMachine.syncRemoveNetwork(mChannel, netId);
654 } else {
655 Slog.e(TAG, "mChannel is not initialized");
656 return false;
657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 }
659
660 /**
661 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
662 * @param netId the integer that identifies the network configuration
663 * to the supplicant
664 * @param disableOthers if true, disable all other networks.
665 * @return {@code true} if the operation succeeded
666 */
667 public boolean enableNetwork(int netId, boolean disableOthers) {
668 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700669 if (mChannel != null) {
670 return mWifiStateMachine.syncEnableNetwork(mChannel, netId, disableOthers);
671 } else {
672 Slog.e(TAG, "mChannel is not initialized");
673 return false;
674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 }
676
677 /**
678 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
679 * @param netId the integer that identifies the network configuration
680 * to the supplicant
681 * @return {@code true} if the operation succeeded
682 */
683 public boolean disableNetwork(int netId) {
684 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700685 if (mChannel != null) {
686 return mWifiStateMachine.syncDisableNetwork(mChannel, netId);
687 } else {
688 Slog.e(TAG, "mChannel is not initialized");
689 return false;
690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 }
692
693 /**
694 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
695 * @return the Wi-Fi information, contained in {@link WifiInfo}.
696 */
697 public WifiInfo getConnectionInfo() {
698 enforceAccessPermission();
699 /*
700 * Make sure we have the latest information, by sending
701 * a status request to the supplicant.
702 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700703 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 }
705
706 /**
707 * Return the results of the most recent access point scan, in the form of
708 * a list of {@link ScanResult} objects.
709 * @return the list of results
710 */
711 public List<ScanResult> getScanResults() {
712 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700713 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 }
715
716 /**
717 * Tell the supplicant to persist the current list of configured networks.
718 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700719 *
720 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 */
722 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700723 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700725 if (mChannel != null) {
726 return mWifiStateMachine.syncSaveConfig(mChannel);
727 } else {
728 Slog.e(TAG, "mChannel is not initialized");
729 return false;
730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 }
732
733 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700734 * Set the country code
735 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700736 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700737 *
738 * The persist behavior exists so that wifi can fall back to the last
739 * persisted country code on a restart, when the locale information is
740 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700742 public void setCountryCode(String countryCode, boolean persist) {
743 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
744 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700746 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 }
748
749 /**
750 * Return the DHCP-assigned addresses from the last successful DHCP request,
751 * if any.
752 * @return the DHCP information
753 */
754 public DhcpInfo getDhcpInfo() {
755 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700756 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 }
758
Irfan Sheriff0d255342010-07-28 09:35:20 -0700759 /**
760 * see {@link android.net.wifi.WifiManager#startWifi}
761 *
762 */
763 public void startWifi() {
764 enforceChangePermission();
765 /* TODO: may be add permissions for access only to connectivity service
766 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
767 * of WifiLock & device idle status unless wifi enabled status is toggled
768 */
769
770 mWifiStateMachine.setDriverStart(true);
771 mWifiStateMachine.reconnectCommand();
772 }
773
774 /**
775 * see {@link android.net.wifi.WifiManager#stopWifi}
776 *
777 */
778 public void stopWifi() {
779 enforceChangePermission();
780 /* TODO: may be add permissions for access only to connectivity service
781 * TODO: if a stop is issued, wifi is brought up only by startWifi
782 * unless wifi enabled status is toggled
783 */
784 mWifiStateMachine.setDriverStart(false);
785 }
786
787
788 /**
789 * see {@link android.net.wifi.WifiManager#addToBlacklist}
790 *
791 */
792 public void addToBlacklist(String bssid) {
793 enforceChangePermission();
794
795 mWifiStateMachine.addToBlacklist(bssid);
796 }
797
798 /**
799 * see {@link android.net.wifi.WifiManager#clearBlacklist}
800 *
801 */
802 public void clearBlacklist() {
803 enforceChangePermission();
804
805 mWifiStateMachine.clearBlacklist();
806 }
807
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700808 public void connectNetworkWithId(int networkId) {
809 enforceChangePermission();
810 mWifiStateMachine.connectNetwork(networkId);
811 }
812
813 public void connectNetworkWithConfig(WifiConfiguration config) {
814 enforceChangePermission();
815 mWifiStateMachine.connectNetwork(config);
816 }
817
818 public void saveNetwork(WifiConfiguration config) {
819 enforceChangePermission();
820 mWifiStateMachine.saveNetwork(config);
821 }
822
823 public void forgetNetwork(int netId) {
824 enforceChangePermission();
825 mWifiStateMachine.forgetNetwork(netId);
826 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700827
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700828 public void startWpsPbc(String bssid) {
829 enforceChangePermission();
830 mWifiStateMachine.startWpsPbc(bssid);
831 }
832
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700833 public void startWpsWithPinFromAccessPoint(String bssid, int apPin) {
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700834 enforceChangePermission();
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700835 mWifiStateMachine.startWpsWithPinFromAccessPoint(bssid, apPin);
836 }
837
838 public int startWpsWithPinFromDevice(String bssid) {
839 enforceChangePermission();
840 if (mChannel != null) {
841 return mWifiStateMachine.syncStartWpsWithPinFromDevice(mChannel, bssid);
842 } else {
843 Slog.e(TAG, "mChannel is not initialized");
844 return -1;
845 }
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700846 }
847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
849 @Override
850 public void onReceive(Context context, Intent intent) {
851 String action = intent.getAction();
852
Doug Zongker43866e02010-01-07 12:09:54 -0800853 long idleMillis =
854 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700855 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800857 Settings.System.getInt(mContext.getContentResolver(),
858 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400860 if (DBG) {
861 Slog.d(TAG, "ACTION_SCREEN_ON");
862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 mAlarmManager.cancel(mIdleIntent);
864 mDeviceIdle = false;
865 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700866 // Once the screen is on, we are not keeping WIFI running
867 // because of any locks so clear that tracking immediately.
868 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700869 mWifiStateMachine.enableRssiPolling(true);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700870 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400872 if (DBG) {
873 Slog.d(TAG, "ACTION_SCREEN_OFF");
874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700876 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 /*
878 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
879 * AND the "stay on while plugged in" setting doesn't match the
880 * current power conditions (i.e, not plugged in, plugged in to USB,
881 * or plugged in to AC).
882 */
883 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700884 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700885 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700886 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700887 // we don't have time to track down for this release. Delay instead,
888 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700889 // TODO - fix the race conditions and switch back to the immediate turn-off
890 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400891 if (DBG) {
892 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
893 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700894 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
895 // // do not keep Wifi awake when screen is off if Wifi is not associated
896 // mDeviceIdle = true;
897 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400898 } else {
899 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400900 if (DBG) {
901 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
902 + "ms");
903 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400904 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400908 if (DBG) {
909 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700912 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700913 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
915 /*
916 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
917 * AND we are transitioning from a state in which the device was supposed
918 * to stay awake to a state in which it is not supposed to stay awake.
919 * If "stay awake" state is not changing, we do nothing, to avoid resetting
920 * the already-set timer.
921 */
922 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400923 if (DBG) {
924 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
927 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
928 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400929 if (DBG) {
930 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
934 mPluggedType = pluggedType;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700935 } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
936 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
937 BluetoothA2dp.STATE_NOT_PLAYING);
938 mWifiStateMachine.setBluetoothScanMode(state == BluetoothA2dp.STATE_PLAYING);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700939 } else if (action.equals(ACTION_START_SCAN)) {
940 mWifiStateMachine.startScan(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 }
943
944 /**
945 * Determines whether the Wi-Fi chipset should stay awake or be put to
946 * sleep. Looks at the setting for the sleep policy and the current
947 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800948 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 * @see #shouldDeviceStayAwake(int, int)
950 */
951 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
952 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
953 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
954
955 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
956 // Never sleep
957 return true;
958 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
959 (pluggedType != 0)) {
960 // Never sleep while plugged, and we're plugged
961 return true;
962 } else {
963 // Default
964 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
965 }
966 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 /**
969 * Determine whether the bit value corresponding to {@code pluggedType} is set in
970 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
971 * of {@code 0} isn't really a plugged type, but rather an indication that the
972 * device isn't plugged in at all, there is no bit value corresponding to a
973 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700974 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 * @param stayAwakeConditions a bit string specifying which "plugged types" should
976 * keep the device (and hence Wi-Fi) awake.
977 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
978 * being made
979 * @return {@code true} if {@code pluggedType} indicates that the device is
980 * supposed to stay awake, {@code false} otherwise.
981 */
982 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
983 return (stayAwakeConditions & pluggedType) != 0;
984 }
985 };
986
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700987 private synchronized void reportStartWorkSource() {
988 mTmpWorkSource.clear();
989 if (mDeviceIdle) {
990 for (int i=0; i<mLocks.mList.size(); i++) {
991 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700992 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700993 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700994 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700995 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 private void updateWifiState() {
998 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700999 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001001 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1003 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001004
1005 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001007 }
1008 /* If device is not idle, lockmode cannot be scan only */
1009 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1011 }
1012
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001013 /* Scan interval when driver is started */
1014 long scanMs = Settings.Secure.getLong(mContext.getContentResolver(),
1015 Settings.Secure.WIFI_SCAN_INTERVAL_MS, DEFAULT_SCAN_INTERVAL_MS);
1016
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001017 /* Disable tethering when airplane mode is enabled */
1018 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001019 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001020 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001021
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001022 if (wifiShouldBeEnabled) {
1023 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001024 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001025 mWifiStateMachine.setWifiEnabled(true);
1026 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001027 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001028 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001029 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
1030 System.currentTimeMillis() + scanMs, scanMs, mScanIntent);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001031 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1032 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001034 mWifiStateMachine.requestCmWakeLock();
1035 mWifiStateMachine.setDriverStart(false);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001036 mAlarmManager.cancel(mScanIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001038 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001039 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
1041 }
1042
1043 private void registerForBroadcasts() {
1044 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1046 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1047 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1048 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -07001049 intentFilter.addAction(ACTION_START_SCAN);
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001050 intentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 mContext.registerReceiver(mReceiver, intentFilter);
1052 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 private boolean isAirplaneSensitive() {
1055 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1056 Settings.System.AIRPLANE_MODE_RADIOS);
1057 return airplaneModeRadios == null
1058 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1059 }
1060
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001061 private boolean isAirplaneToggleable() {
1062 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1063 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1064 return toggleableRadios != null
1065 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1066 }
1067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 /**
1069 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1070 * currently on.
1071 * @return {@code true} if airplane mode is on.
1072 */
1073 private boolean isAirplaneModeOn() {
1074 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1075 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1076 }
1077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 @Override
1079 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1080 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1081 != PackageManager.PERMISSION_GRANTED) {
1082 pw.println("Permission Denial: can't dump WifiService from from pid="
1083 + Binder.getCallingPid()
1084 + ", uid=" + Binder.getCallingUid());
1085 return;
1086 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001087 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 pw.println("Stay-awake conditions: " +
1089 Settings.System.getInt(mContext.getContentResolver(),
1090 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1091 pw.println();
1092
1093 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001094 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 pw.println();
1096 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001097 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 if (scanResults != null && scanResults.size() != 0) {
1099 pw.println(" BSSID Frequency RSSI Flags SSID");
1100 for (ScanResult r : scanResults) {
1101 pw.printf(" %17s %9d %5d %-16s %s%n",
1102 r.BSSID,
1103 r.frequency,
1104 r.level,
1105 r.capabilities,
1106 r.SSID == null ? "" : r.SSID);
1107 }
1108 }
1109 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001110 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001111 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001112 mScanLocksAcquired + " scan");
1113 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001114 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001115 mScanLocksReleased + " scan");
1116 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 pw.println("Locks held:");
1118 mLocks.dump(pw);
1119 }
1120
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001121 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001122 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1123 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
1125
1126 public void binderDied() {
1127 synchronized (mLocks) {
1128 releaseWifiLockLocked(mBinder);
1129 }
1130 }
1131
1132 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001133 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
1135 }
1136
1137 private class LockList {
1138 private List<WifiLock> mList;
1139
1140 private LockList() {
1141 mList = new ArrayList<WifiLock>();
1142 }
1143
1144 private synchronized boolean hasLocks() {
1145 return !mList.isEmpty();
1146 }
1147
1148 private synchronized int getStrongestLockMode() {
1149 if (mList.isEmpty()) {
1150 return WifiManager.WIFI_MODE_FULL;
1151 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001152
1153 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1154 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001156
1157 if (mFullLocksAcquired > mFullLocksReleased) {
1158 return WifiManager.WIFI_MODE_FULL;
1159 }
1160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 return WifiManager.WIFI_MODE_SCAN_ONLY;
1162 }
1163
1164 private void addLock(WifiLock lock) {
1165 if (findLockByBinder(lock.mBinder) < 0) {
1166 mList.add(lock);
1167 }
1168 }
1169
1170 private WifiLock removeLock(IBinder binder) {
1171 int index = findLockByBinder(binder);
1172 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001173 WifiLock ret = mList.remove(index);
1174 ret.unlinkDeathRecipient();
1175 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 } else {
1177 return null;
1178 }
1179 }
1180
1181 private int findLockByBinder(IBinder binder) {
1182 int size = mList.size();
1183 for (int i = size - 1; i >= 0; i--)
1184 if (mList.get(i).mBinder == binder)
1185 return i;
1186 return -1;
1187 }
1188
1189 private void dump(PrintWriter pw) {
1190 for (WifiLock l : mList) {
1191 pw.print(" ");
1192 pw.println(l);
1193 }
1194 }
1195 }
1196
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001197 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001198 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001199 return;
1200 }
1201 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1202 pid, uid, null);
1203 }
1204
1205 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001207 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1208 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1209 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1210 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1211 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 return false;
1213 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001214 if (ws != null && ws.size() == 0) {
1215 ws = null;
1216 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001217 if (ws != null) {
1218 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1219 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001220 if (ws == null) {
1221 ws = new WorkSource(Binder.getCallingUid());
1222 }
1223 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 synchronized (mLocks) {
1225 return acquireWifiLockLocked(wifiLock);
1226 }
1227 }
1228
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001229 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1230 switch(wifiLock.mMode) {
1231 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001232 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001233 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1234 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001235 case WifiManager.WIFI_MODE_SCAN_ONLY:
1236 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1237 break;
1238 }
1239 }
1240
1241 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1242 switch(wifiLock.mMode) {
1243 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001244 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001245 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1246 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001247 case WifiManager.WIFI_MODE_SCAN_ONLY:
1248 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1249 break;
1250 }
1251 }
1252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001254 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001257
The Android Open Source Project10592532009-03-18 17:39:46 -07001258 long ident = Binder.clearCallingIdentity();
1259 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001260 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001261 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001262 case WifiManager.WIFI_MODE_FULL:
1263 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001264 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001265 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1266 ++mFullHighPerfLocksAcquired;
1267 break;
1268
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001269 case WifiManager.WIFI_MODE_SCAN_ONLY:
1270 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001271 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001272 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001273
1274 // Be aggressive about adding new locks into the accounted state...
1275 // we want to over-report rather than under-report.
1276 reportStartWorkSource();
1277
1278 updateWifiState();
1279 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001280 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001281 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001282 } finally {
1283 Binder.restoreCallingIdentity(ident);
1284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 }
1286
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001287 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1288 int uid = Binder.getCallingUid();
1289 int pid = Binder.getCallingPid();
1290 if (ws != null && ws.size() == 0) {
1291 ws = null;
1292 }
1293 if (ws != null) {
1294 enforceWakeSourcePermission(uid, pid);
1295 }
1296 long ident = Binder.clearCallingIdentity();
1297 try {
1298 synchronized (mLocks) {
1299 int index = mLocks.findLockByBinder(lock);
1300 if (index < 0) {
1301 throw new IllegalArgumentException("Wifi lock not active");
1302 }
1303 WifiLock wl = mLocks.mList.get(index);
1304 noteReleaseWifiLock(wl);
1305 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1306 noteAcquireWifiLock(wl);
1307 }
1308 } catch (RemoteException e) {
1309 } finally {
1310 Binder.restoreCallingIdentity(ident);
1311 }
1312 }
1313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 public boolean releaseWifiLock(IBinder lock) {
1315 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1316 synchronized (mLocks) {
1317 return releaseWifiLockLocked(lock);
1318 }
1319 }
1320
1321 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001322 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001323
The Android Open Source Project10592532009-03-18 17:39:46 -07001324 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001325
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001326 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001327
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001328 hadLock = (wifiLock != null);
1329
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001330 long ident = Binder.clearCallingIdentity();
1331 try {
1332 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001333 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001334 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001335 case WifiManager.WIFI_MODE_FULL:
1336 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001337 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001338 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1339 ++mFullHighPerfLocksReleased;
1340 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001341 case WifiManager.WIFI_MODE_SCAN_ONLY:
1342 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001343 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001344 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001345 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001346
1347 // TODO - should this only happen if you hadLock?
1348 updateWifiState();
1349
1350 } catch (RemoteException e) {
1351 } finally {
1352 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001353 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001354
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001355 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001357
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001358 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001359 implements IBinder.DeathRecipient {
1360 String mTag;
1361 int mMode;
1362 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001363 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001364
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001365 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001366 super();
1367 mTag = tag;
1368 mMode = mode;
1369 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001370 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001371 try {
1372 mBinder.linkToDeath(this, 0);
1373 } catch (RemoteException e) {
1374 binderDied();
1375 }
1376 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001377
1378 void unlinkDeathRecipient() {
1379 mBinder.unlinkToDeath(this, 0);
1380 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001381 }
1382
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001383 private class Multicaster extends DeathRecipient {
1384 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001385 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001386 }
1387
1388 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001389 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001390 synchronized (mMulticasters) {
1391 int i = mMulticasters.indexOf(this);
1392 if (i != -1) {
1393 removeMulticasterLocked(i, mMode);
1394 }
1395 }
1396 }
1397
1398 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001399 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001400 }
1401
1402 public int getUid() {
1403 return mMode;
1404 }
1405 }
1406
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001407 public void initializeMulticastFiltering() {
1408 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001409
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001410 synchronized (mMulticasters) {
1411 // if anybody had requested filters be off, leave off
1412 if (mMulticasters.size() != 0) {
1413 return;
1414 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001415 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001416 }
1417 }
1418 }
1419
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001420 public void acquireMulticastLock(IBinder binder, String tag) {
1421 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001422
1423 synchronized (mMulticasters) {
1424 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001425 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001426 // Note that we could call stopPacketFiltering only when
1427 // our new size == 1 (first call), but this function won't
1428 // be called often and by making the stopPacket call each
1429 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001430 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001431 }
1432
1433 int uid = Binder.getCallingUid();
1434 Long ident = Binder.clearCallingIdentity();
1435 try {
1436 mBatteryStats.noteWifiMulticastEnabled(uid);
1437 } catch (RemoteException e) {
1438 } finally {
1439 Binder.restoreCallingIdentity(ident);
1440 }
1441 }
1442
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001443 public void releaseMulticastLock() {
1444 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001445
1446 int uid = Binder.getCallingUid();
1447 synchronized (mMulticasters) {
1448 mMulticastDisabled++;
1449 int size = mMulticasters.size();
1450 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001451 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001452 if ((m != null) && (m.getUid() == uid)) {
1453 removeMulticasterLocked(i, uid);
1454 }
1455 }
1456 }
1457 }
1458
1459 private void removeMulticasterLocked(int i, int uid)
1460 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001461 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001462
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001463 if (removed != null) {
1464 removed.unlinkDeathRecipient();
1465 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001466 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001467 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001468 }
1469
1470 Long ident = Binder.clearCallingIdentity();
1471 try {
1472 mBatteryStats.noteWifiMulticastDisabled(uid);
1473 } catch (RemoteException e) {
1474 } finally {
1475 Binder.restoreCallingIdentity(ident);
1476 }
1477 }
1478
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001479 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001480 enforceAccessPermission();
1481
1482 synchronized (mMulticasters) {
1483 return (mMulticasters.size() > 0);
1484 }
1485 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001486
1487 private void checkAndSetNotification() {
1488 // If we shouldn't place a notification on available networks, then
1489 // don't bother doing any of the following
1490 if (!mNotificationEnabled) return;
1491
1492 State state = mNetworkInfo.getState();
1493 if ((state == NetworkInfo.State.DISCONNECTED)
1494 || (state == NetworkInfo.State.UNKNOWN)) {
1495 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001496 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001497 if (scanResults != null) {
1498 int numOpenNetworks = 0;
1499 for (int i = scanResults.size() - 1; i >= 0; i--) {
1500 ScanResult scanResult = scanResults.get(i);
1501
1502 if (TextUtils.isEmpty(scanResult.capabilities)) {
1503 numOpenNetworks++;
1504 }
1505 }
1506
1507 if (numOpenNetworks > 0) {
1508 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1509 /*
1510 * We've scanned continuously at least
1511 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1512 * probably does not have a remembered network in range,
1513 * since otherwise supplicant would have tried to
1514 * associate and thus resetting this counter.
1515 */
1516 setNotificationVisible(true, numOpenNetworks, false, 0);
1517 }
1518 return;
1519 }
1520 }
1521 }
1522
1523 // No open networks in range, remove the notification
1524 setNotificationVisible(false, 0, false, 0);
1525 }
1526
1527 /**
1528 * Clears variables related to tracking whether a notification has been
1529 * shown recently and clears the current notification.
1530 */
1531 private void resetNotification() {
1532 mNotificationRepeatTime = 0;
1533 mNumScansSinceNetworkStateChange = 0;
1534 setNotificationVisible(false, 0, false, 0);
1535 }
1536
1537 /**
1538 * Display or don't display a notification that there are open Wi-Fi networks.
1539 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1540 * @param numNetworks the number networks seen
1541 * @param force {@code true} to force notification to be shown/not-shown,
1542 * even if it is already shown/not-shown.
1543 * @param delay time in milliseconds after which the notification should be made
1544 * visible or invisible.
1545 */
1546 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1547 int delay) {
1548
1549 // Since we use auto cancel on the notification, when the
1550 // mNetworksAvailableNotificationShown is true, the notification may
1551 // have actually been canceled. However, when it is false we know
1552 // for sure that it is not being shown (it will not be shown any other
1553 // place than here)
1554
1555 // If it should be hidden and it is already hidden, then noop
1556 if (!visible && !mNotificationShown && !force) {
1557 return;
1558 }
1559
1560 NotificationManager notificationManager = (NotificationManager) mContext
1561 .getSystemService(Context.NOTIFICATION_SERVICE);
1562
1563 Message message;
1564 if (visible) {
1565
1566 // Not enough time has passed to show the notification again
1567 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1568 return;
1569 }
1570
1571 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001572 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001573 mNotification = new Notification();
1574 mNotification.when = 0;
1575 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1576 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1577 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1578 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1579 }
1580
1581 CharSequence title = mContext.getResources().getQuantityText(
1582 com.android.internal.R.plurals.wifi_available, numNetworks);
1583 CharSequence details = mContext.getResources().getQuantityText(
1584 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1585 mNotification.tickerText = title;
1586 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1587
1588 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1589
1590 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001591 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001592 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001593 }
1594
Irfan Sheriff0d255342010-07-28 09:35:20 -07001595 mNotificationShown = visible;
1596 }
1597
1598 private class NotificationEnabledSettingObserver extends ContentObserver {
1599
1600 public NotificationEnabledSettingObserver(Handler handler) {
1601 super(handler);
1602 }
1603
1604 public void register() {
1605 ContentResolver cr = mContext.getContentResolver();
1606 cr.registerContentObserver(Settings.Secure.getUriFor(
1607 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1608 mNotificationEnabled = getValue();
1609 }
1610
1611 @Override
1612 public void onChange(boolean selfChange) {
1613 super.onChange(selfChange);
1614
1615 mNotificationEnabled = getValue();
1616 resetNotification();
1617 }
1618
1619 private boolean getValue() {
1620 return Settings.Secure.getInt(mContext.getContentResolver(),
1621 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1622 }
1623 }
1624
1625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626}