blob: a9d42e3fad5e7432ad941c5fa7d82d2528efac5e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07002 * Copyright (C) 2010 The Android Open Source Project
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080019import android.app.AlarmManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070020import android.app.Notification;
21import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070023import android.bluetooth.BluetoothA2dp;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070024import android.bluetooth.BluetoothAdapter;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080025import android.bluetooth.BluetoothDevice;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070026import android.bluetooth.BluetoothProfile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.BroadcastReceiver;
28import android.content.ContentResolver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.net.wifi.IWifiManager;
35import android.net.wifi.WifiInfo;
36import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070037import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.net.wifi.ScanResult;
39import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070040import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080041import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff02fb46a2010-12-08 11:27:37 -080042import android.net.wifi.WpsConfiguration;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080043import android.net.ConnectivityManager;
44import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070046import android.net.NetworkInfo;
47import android.net.NetworkInfo.State;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070049import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.HandlerThread;
51import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080052import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070053import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070055import android.os.ServiceManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070056import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070058import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080059import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
Robert Greenwalt04808c22010-12-13 17:01:41 -080061import java.net.InetAddress;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080064import java.util.Set;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070065import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.io.FileDescriptor;
67import java.io.PrintWriter;
68
The Android Open Source Project10592532009-03-18 17:39:46 -070069import com.android.internal.app.IBatteryStats;
Wink Saville4b7ba092010-10-20 15:37:41 -070070import com.android.internal.util.AsyncChannel;
The Android Open Source Project10592532009-03-18 17:39:46 -070071import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080072import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074/**
75 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070076 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 *
78 * @hide
79 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070080//TODO: Clean up multiple locks and implement WifiService
81// as a SM to track soft AP/client/adhoc bring up based
82// on device idle state, airplane mode and boot.
83
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084public class WifiService extends IWifiManager.Stub {
85 private static final String TAG = "WifiService";
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070086 private static final boolean DBG = true;
87
Irfan Sheriff0d255342010-07-28 09:35:20 -070088 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
90 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
92 private AlarmManager mAlarmManager;
93 private PendingIntent mIdleIntent;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070094 private BluetoothA2dp mBluetoothA2dp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 private static final int IDLE_REQUEST = 0;
96 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 private static final String ACTION_DEVICE_IDLE =
132 "com.android.server.WifiManager.action.DEVICE_IDLE";
133
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700134 private boolean mIsReceiverRegistered = false;
135
Irfan Sheriff0d255342010-07-28 09:35:20 -0700136
137 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
138
139 // Variables relating to the 'available networks' notification
140 /**
141 * The icon to show in the 'available networks' notification. This will also
142 * be the ID of the Notification given to the NotificationManager.
143 */
144 private static final int ICON_NETWORKS_AVAILABLE =
145 com.android.internal.R.drawable.stat_notify_wifi_in_range;
146 /**
147 * When a notification is shown, we wait this amount before possibly showing it again.
148 */
149 private final long NOTIFICATION_REPEAT_DELAY_MS;
150 /**
151 * Whether the user has set the setting to show the 'available networks' notification.
152 */
153 private boolean mNotificationEnabled;
154 /**
155 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
156 */
157 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
158 /**
159 * The {@link System#currentTimeMillis()} must be at least this value for us
160 * to show the notification again.
161 */
162 private long mNotificationRepeatTime;
163 /**
164 * The Notification object given to the NotificationManager.
165 */
166 private Notification mNotification;
167 /**
168 * Whether the notification is being shown, as set by us. That is, if the
169 * user cancels the notification, we will not receive the callback so this
170 * will still be true. We only guarantee if this is false, then the
171 * notification is not showing.
172 */
173 private boolean mNotificationShown;
174 /**
175 * The number of continuous scans that must occur before consider the
176 * supplicant in a scanning state. This allows supplicant to associate with
177 * remembered networks that are in the scan results.
178 */
179 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
180 /**
181 * The number of scans since the last network state change. When this
182 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
183 * supplicant to actually be scanning. When the network state changes to
184 * something other than scanning, we reset this to 0.
185 */
186 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700187
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700188 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700189 * Asynchronous channel to WifiStateMachine
190 */
191 private AsyncChannel mChannel;
192
193 /**
194 * TODO: Possibly change WifiService into an AsyncService.
195 */
196 private class WifiServiceHandler extends Handler {
197 private AsyncChannel mWshChannel;
198
199 WifiServiceHandler(android.os.Looper looper, Context context) {
200 super(looper);
201 mWshChannel = new AsyncChannel();
Wink Savillecfce3032010-12-01 23:20:25 -0800202 mWshChannel.connect(context, this, mWifiStateMachine.getHandler());
Wink Saville4b7ba092010-10-20 15:37:41 -0700203 }
204
205 @Override
206 public void handleMessage(Message msg) {
207 switch (msg.what) {
208 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
209 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
210 mChannel = mWshChannel;
211 } else {
212 Slog.d(TAG, "WifiServicehandler.handleMessage could not connect error=" +
213 msg.arg1);
214 mChannel = null;
215 }
216 break;
217 }
218 default: {
219 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
220 break;
221 }
222 }
223 }
224 }
225 WifiServiceHandler mHandler;
226
227 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700228 * Temporary for computing UIDS that are responsible for starting WIFI.
229 * Protected by mWifiStateTracker lock.
230 */
231 private final WorkSource mTmpWorkSource = new WorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700232
233 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700235 mWifiStateMachine = new WifiStateMachine(mContext);
236 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700237 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
240 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
241 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
242
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700243 HandlerThread wifiThread = new HandlerThread("WifiService");
244 wifiThread.start();
Wink Saville4b7ba092010-10-20 15:37:41 -0700245 mHandler = new WifiServiceHandler(wifiThread.getLooper(), context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 mContext.registerReceiver(
248 new BroadcastReceiver() {
249 @Override
250 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700251 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700252 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700253 // on airplane disable, restore Wifi if the saved state indicates so
254 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
255 persistWifiEnabled(true);
256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 updateWifiState();
258 }
259 },
260 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
261
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800262 mContext.registerReceiver(
263 new BroadcastReceiver() {
264 @Override
265 public void onReceive(Context context, Intent intent) {
266
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700267 ArrayList<String> available = intent.getStringArrayListExtra(
268 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
269 ArrayList<String> active = intent.getStringArrayListExtra(
270 ConnectivityManager.EXTRA_ACTIVE_TETHER);
271 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800272
273 }
274 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700275
276 IntentFilter filter = new IntentFilter();
277 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
278 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
279 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
280
281 mContext.registerReceiver(
282 new BroadcastReceiver() {
283 @Override
284 public void onReceive(Context context, Intent intent) {
285 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
286 // reset & clear notification on any wifi state change
287 resetNotification();
288 } else if (intent.getAction().equals(
289 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
290 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
291 WifiManager.EXTRA_NETWORK_INFO);
292 // reset & clear notification on a network connect & disconnect
293 switch(mNetworkInfo.getDetailedState()) {
294 case CONNECTED:
295 case DISCONNECTED:
296 resetNotification();
297 break;
298 }
299 } else if (intent.getAction().equals(
300 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
301 checkAndSetNotification();
302 }
303 }
304 }, filter);
305
306 // Setting is in seconds
307 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
308 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
309 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
310 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800311 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800312
Irfan Sheriff7b009782010-03-11 16:37:45 -0800313 /**
314 * Check if Wi-Fi needs to be enabled and start
315 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700316 *
317 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800318 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700319 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700320 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700321 boolean wifiEnabled = !isAirplaneModeOn()
322 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800323 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
324 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700325 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800326 }
327
328 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
329
330 boolean wifiTethered = false;
331 boolean wifiAvailable = false;
332
333 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
334 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
335
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700336 if (mCm == null) {
337 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
338 }
339
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800340 mWifiRegexs = mCm.getTetherableWifiRegexs();
341
342 for (String intf : available) {
343 for (String regex : mWifiRegexs) {
344 if (intf.matches(regex)) {
345
346 InterfaceConfiguration ifcg = null;
347 try {
348 ifcg = service.getInterfaceConfig(intf);
349 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700350 /* IP/netmask: 192.168.43.1/255.255.255.0 */
Robert Greenwalt04808c22010-12-13 17:01:41 -0800351 ifcg.addr = InetAddress.getByName("192.168.43.1");
352 ifcg.mask = InetAddress.getByName("255.255.255.0");
Irfan Sheriff07bd5ae2010-10-28 14:45:56 -0700353 ifcg.interfaceFlags = "[up]";
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800354
355 service.setInterfaceConfig(intf, ifcg);
356 }
357 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800358 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700359 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800360 return;
361 }
362
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800363 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700364 Slog.e(TAG, "Error tethering on " + intf);
365 setWifiApEnabled(null, false);
366 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800367 }
368 break;
369 }
370 }
371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 }
373
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700374 private boolean testAndClearWifiSavedState() {
375 final ContentResolver cr = mContext.getContentResolver();
376 int wifiSavedState = 0;
377 try {
378 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
379 if(wifiSavedState == 1)
380 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
381 } catch (Settings.SettingNotFoundException e) {
382 ;
383 }
384 return (wifiSavedState == 1);
385 }
386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 private boolean getPersistedWifiEnabled() {
388 final ContentResolver cr = mContext.getContentResolver();
389 try {
390 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
391 } catch (Settings.SettingNotFoundException e) {
392 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
393 return false;
394 }
395 }
396
397 private void persistWifiEnabled(boolean enabled) {
398 final ContentResolver cr = mContext.getContentResolver();
399 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
400 }
401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 /**
403 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700404 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 */
406 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700407 enforceAccessPermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700408 if (mChannel != null) {
409 return mWifiStateMachine.syncPingSupplicant(mChannel);
410 } else {
411 Slog.e(TAG, "mChannel is not initialized");
412 return false;
413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 }
415
416 /**
417 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700419 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700421 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 }
423
424 private void enforceAccessPermission() {
425 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
426 "WifiService");
427 }
428
429 private void enforceChangePermission() {
430 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
431 "WifiService");
432
433 }
434
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700435 private void enforceMulticastChangePermission() {
436 mContext.enforceCallingOrSelfPermission(
437 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
438 "WifiService");
439 }
440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700442 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
443 * @param enable {@code true} to enable, {@code false} to disable.
444 * @return {@code true} if the enable/disable operation was
445 * started or is already in the queue.
446 */
447 public synchronized boolean setWifiEnabled(boolean enable) {
448 enforceChangePermission();
449
450 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700451 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700452 }
453
454 // set a flag if the user is enabling Wifi while in airplane mode
455 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
456 mAirplaneModeOverwridden.set(true);
457 }
458
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700459 if (enable) {
460 reportStartWorkSource();
461 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700462 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700463
464 /*
465 * Caller might not have WRITE_SECURE_SETTINGS,
466 * only CHANGE_WIFI_STATE is enforced
467 */
468 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700469 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700470 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700471
472 if (enable) {
473 if (!mIsReceiverRegistered) {
474 registerForBroadcasts();
475 mIsReceiverRegistered = true;
476 }
477 } else if (mIsReceiverRegistered){
478 mContext.unregisterReceiver(mReceiver);
479 mIsReceiverRegistered = false;
480 }
481
482 return true;
483 }
484
485 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 * see {@link WifiManager#getWifiState()}
487 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
488 * {@link WifiManager#WIFI_STATE_DISABLING},
489 * {@link WifiManager#WIFI_STATE_ENABLED},
490 * {@link WifiManager#WIFI_STATE_ENABLING},
491 * {@link WifiManager#WIFI_STATE_UNKNOWN}
492 */
493 public int getWifiEnabledState() {
494 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700495 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 }
497
498 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700499 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800500 * @param wifiConfig SSID, security and channel details as
501 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700502 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800503 * @return {@code true} if the start operation was
504 * started or is already in the queue.
505 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700506 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800507 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800508
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700509 if (enabled) {
510 /* Use default config if there is no existing config */
511 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
512 wifiConfig = new WifiConfiguration();
513 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
514 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
515 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700516 /*
517 * Caller might not have WRITE_SECURE_SETTINGS,
518 * only CHANGE_WIFI_STATE is enforced
519 */
520 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700521 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700522 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800523 }
524
Irfan Sheriff0d255342010-07-28 09:35:20 -0700525 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700526
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800527 return true;
528 }
529
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700530 /**
531 * see {@link WifiManager#getWifiApState()}
532 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
533 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
534 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
535 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
536 * {@link WifiManager#WIFI_AP_STATE_FAILED}
537 */
538 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700539 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700540 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700541 }
542
543 /**
544 * see {@link WifiManager#getWifiApConfiguration()}
545 * @return soft access point configuration
546 */
547 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800548 final ContentResolver cr = mContext.getContentResolver();
549 WifiConfiguration wifiConfig = new WifiConfiguration();
550 int authType;
551 try {
552 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
553 if (wifiConfig.SSID == null)
554 return null;
555 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
556 wifiConfig.allowedKeyManagement.set(authType);
557 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
558 return wifiConfig;
559 } catch (Settings.SettingNotFoundException e) {
560 Slog.e(TAG,"AP settings not found, returning");
561 return null;
562 }
563 }
564
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700565 /**
566 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
567 * @param wifiConfig WifiConfiguration details for soft access point
568 */
569 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700570 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800571 final ContentResolver cr = mContext.getContentResolver();
572 boolean isWpa;
573 if (wifiConfig == null)
574 return;
575 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
576 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
577 Settings.Secure.putInt(cr,
578 Settings.Secure.WIFI_AP_SECURITY,
579 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
580 if (isWpa)
581 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
582 }
583
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800584 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700585 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800586 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700587 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700588 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700589 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800590 }
591
592 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700593 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800594 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700595 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700596 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700597 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800598 }
599
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700600 /**
601 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700602 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700603 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700604 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700605 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800606 }
607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 /**
609 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
610 * @return the list of configured networks
611 */
612 public List<WifiConfiguration> getConfiguredNetworks() {
613 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700614 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800615 }
616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 /**
618 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
619 * @return the supplicant-assigned identifier for the new or updated
620 * network if the operation succeeds, or {@code -1} if it fails
621 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800622 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700624 if (mChannel != null) {
625 return mWifiStateMachine.syncAddOrUpdateNetwork(mChannel, config);
626 } else {
627 Slog.e(TAG, "mChannel is not initialized");
628 return -1;
629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 }
631
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700632 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
634 * @param netId the integer that identifies the network configuration
635 * to the supplicant
636 * @return {@code true} if the operation succeeded
637 */
638 public boolean removeNetwork(int netId) {
639 enforceChangePermission();
Wink Saville4b7ba092010-10-20 15:37:41 -0700640 if (mChannel != null) {
641 return mWifiStateMachine.syncRemoveNetwork(mChannel, netId);
642 } else {
643 Slog.e(TAG, "mChannel is not initialized");
644 return false;
645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 }
647
648 /**
649 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
650 * @param netId the integer that identifies the network configuration
651 * to the supplicant
652 * @param disableOthers if true, disable all other networks.
653 * @return {@code true} if the operation succeeded
654 */
655 public boolean enableNetwork(int netId, boolean disableOthers) {
656 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700657 if (mChannel != null) {
658 return mWifiStateMachine.syncEnableNetwork(mChannel, netId, disableOthers);
659 } else {
660 Slog.e(TAG, "mChannel is not initialized");
661 return false;
662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 }
664
665 /**
666 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
667 * @param netId the integer that identifies the network configuration
668 * to the supplicant
669 * @return {@code true} if the operation succeeded
670 */
671 public boolean disableNetwork(int netId) {
672 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700673 if (mChannel != null) {
674 return mWifiStateMachine.syncDisableNetwork(mChannel, netId);
675 } else {
676 Slog.e(TAG, "mChannel is not initialized");
677 return false;
678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 }
680
681 /**
682 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
683 * @return the Wi-Fi information, contained in {@link WifiInfo}.
684 */
685 public WifiInfo getConnectionInfo() {
686 enforceAccessPermission();
687 /*
688 * Make sure we have the latest information, by sending
689 * a status request to the supplicant.
690 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700691 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 }
693
694 /**
695 * Return the results of the most recent access point scan, in the form of
696 * a list of {@link ScanResult} objects.
697 * @return the list of results
698 */
699 public List<ScanResult> getScanResults() {
700 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700701 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 }
703
704 /**
705 * Tell the supplicant to persist the current list of configured networks.
706 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700707 *
708 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 */
710 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700711 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700713 if (mChannel != null) {
714 return mWifiStateMachine.syncSaveConfig(mChannel);
715 } else {
716 Slog.e(TAG, "mChannel is not initialized");
717 return false;
718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
720
721 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700722 * Set the country code
723 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700724 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700725 *
726 * The persist behavior exists so that wifi can fall back to the last
727 * persisted country code on a restart, when the locale information is
728 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700730 public void setCountryCode(String countryCode, boolean persist) {
731 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
732 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700734 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 }
736
737 /**
Irfan Sheriff36f74132010-11-04 16:57:37 -0700738 * Set the operational frequency band
739 * @param band One of
740 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
741 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
742 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
743 * @param persist {@code true} if the setting should be remembered.
744 *
745 */
746 public void setFrequencyBand(int band, boolean persist) {
747 enforceChangePermission();
748 if (!isDualBandSupported()) return;
749 Slog.i(TAG, "WifiService trying to set frequency band to " + band +
750 " with persist set to " + persist);
751 mWifiStateMachine.setFrequencyBand(band, persist);
752 }
753
754
755 /**
756 * Get the operational frequency band
757 */
758 public int getFrequencyBand() {
759 enforceAccessPermission();
760 return mWifiStateMachine.getFrequencyBand();
761 }
762
763 public boolean isDualBandSupported() {
764 //TODO: Should move towards adding a driver API that checks at runtime
765 return mContext.getResources().getBoolean(
766 com.android.internal.R.bool.config_wifi_dual_band_support);
767 }
768
769 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 * Return the DHCP-assigned addresses from the last successful DHCP request,
771 * if any.
772 * @return the DHCP information
773 */
774 public DhcpInfo getDhcpInfo() {
775 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700776 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
778
Irfan Sheriff0d255342010-07-28 09:35:20 -0700779 /**
780 * see {@link android.net.wifi.WifiManager#startWifi}
781 *
782 */
783 public void startWifi() {
784 enforceChangePermission();
785 /* TODO: may be add permissions for access only to connectivity service
786 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
787 * of WifiLock & device idle status unless wifi enabled status is toggled
788 */
789
790 mWifiStateMachine.setDriverStart(true);
791 mWifiStateMachine.reconnectCommand();
792 }
793
794 /**
795 * see {@link android.net.wifi.WifiManager#stopWifi}
796 *
797 */
798 public void stopWifi() {
799 enforceChangePermission();
800 /* TODO: may be add permissions for access only to connectivity service
801 * TODO: if a stop is issued, wifi is brought up only by startWifi
802 * unless wifi enabled status is toggled
803 */
804 mWifiStateMachine.setDriverStart(false);
805 }
806
807
808 /**
809 * see {@link android.net.wifi.WifiManager#addToBlacklist}
810 *
811 */
812 public void addToBlacklist(String bssid) {
813 enforceChangePermission();
814
815 mWifiStateMachine.addToBlacklist(bssid);
816 }
817
818 /**
819 * see {@link android.net.wifi.WifiManager#clearBlacklist}
820 *
821 */
822 public void clearBlacklist() {
823 enforceChangePermission();
824
825 mWifiStateMachine.clearBlacklist();
826 }
827
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700828 public void connectNetworkWithId(int networkId) {
829 enforceChangePermission();
830 mWifiStateMachine.connectNetwork(networkId);
831 }
832
833 public void connectNetworkWithConfig(WifiConfiguration config) {
834 enforceChangePermission();
835 mWifiStateMachine.connectNetwork(config);
836 }
837
838 public void saveNetwork(WifiConfiguration config) {
839 enforceChangePermission();
840 mWifiStateMachine.saveNetwork(config);
841 }
842
843 public void forgetNetwork(int netId) {
844 enforceChangePermission();
845 mWifiStateMachine.forgetNetwork(netId);
846 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700847
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800848 public String startWps(WpsConfiguration config) {
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700849 enforceChangePermission();
850 if (mChannel != null) {
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800851 return mWifiStateMachine.startWps(mChannel, config);
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700852 } else {
853 Slog.e(TAG, "mChannel is not initialized");
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800854 return "";
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700855 }
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700856 }
857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
859 @Override
860 public void onReceive(Context context, Intent intent) {
861 String action = intent.getAction();
862
Doug Zongker43866e02010-01-07 12:09:54 -0800863 long idleMillis =
864 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700865 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800867 Settings.System.getInt(mContext.getContentResolver(),
868 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400870 if (DBG) {
871 Slog.d(TAG, "ACTION_SCREEN_ON");
872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 mAlarmManager.cancel(mIdleIntent);
874 mDeviceIdle = false;
875 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700876 // Once the screen is on, we are not keeping WIFI running
877 // because of any locks so clear that tracking immediately.
878 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700879 mWifiStateMachine.enableRssiPolling(true);
Irfan Sheriff8e86b892010-12-22 11:02:20 -0800880 mWifiStateMachine.enableAllNetworks();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700881 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400883 if (DBG) {
884 Slog.d(TAG, "ACTION_SCREEN_OFF");
885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700887 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 /*
889 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
890 * AND the "stay on while plugged in" setting doesn't match the
891 * current power conditions (i.e, not plugged in, plugged in to USB,
892 * or plugged in to AC).
893 */
894 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700895 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700896 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700897 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700898 // we don't have time to track down for this release. Delay instead,
899 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700900 // TODO - fix the race conditions and switch back to the immediate turn-off
901 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400902 if (DBG) {
903 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
904 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700905 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
906 // // do not keep Wifi awake when screen is off if Wifi is not associated
907 // mDeviceIdle = true;
908 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400909 } else {
910 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400911 if (DBG) {
912 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
913 + "ms");
914 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400915 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400919 if (DBG) {
920 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700923 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700924 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
926 /*
927 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
928 * AND we are transitioning from a state in which the device was supposed
929 * to stay awake to a state in which it is not supposed to stay awake.
930 * If "stay awake" state is not changing, we do nothing, to avoid resetting
931 * the already-set timer.
932 */
933 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400934 if (DBG) {
935 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
938 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
939 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400940 if (DBG) {
941 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 }
945 mPluggedType = pluggedType;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700946 } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
947 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
948 BluetoothA2dp.STATE_NOT_PLAYING);
949 mWifiStateMachine.setBluetoothScanMode(state == BluetoothA2dp.STATE_PLAYING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 }
952
953 /**
954 * Determines whether the Wi-Fi chipset should stay awake or be put to
955 * sleep. Looks at the setting for the sleep policy and the current
956 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800957 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 * @see #shouldDeviceStayAwake(int, int)
959 */
960 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
961 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
962 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
963
964 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
965 // Never sleep
966 return true;
967 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
968 (pluggedType != 0)) {
969 // Never sleep while plugged, and we're plugged
970 return true;
971 } else {
972 // Default
973 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
974 }
975 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 /**
978 * Determine whether the bit value corresponding to {@code pluggedType} is set in
979 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
980 * of {@code 0} isn't really a plugged type, but rather an indication that the
981 * device isn't plugged in at all, there is no bit value corresponding to a
982 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700983 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 * @param stayAwakeConditions a bit string specifying which "plugged types" should
985 * keep the device (and hence Wi-Fi) awake.
986 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
987 * being made
988 * @return {@code true} if {@code pluggedType} indicates that the device is
989 * supposed to stay awake, {@code false} otherwise.
990 */
991 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
992 return (stayAwakeConditions & pluggedType) != 0;
993 }
994 };
995
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700996 private synchronized void reportStartWorkSource() {
997 mTmpWorkSource.clear();
998 if (mDeviceIdle) {
999 for (int i=0; i<mLocks.mList.size(); i++) {
1000 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001001 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001002 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001003 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001004 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 private void updateWifiState() {
1007 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001008 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001010 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1012 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001013
1014 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001016 }
1017 /* If device is not idle, lockmode cannot be scan only */
1018 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1020 }
1021
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001022 /* Disable tethering when airplane mode is enabled */
1023 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001024 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001025 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001026
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001027 if (wifiShouldBeEnabled) {
1028 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001029 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001030 mWifiStateMachine.setWifiEnabled(true);
1031 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001032 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001033 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001034 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1035 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001037 mWifiStateMachine.requestCmWakeLock();
1038 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001040 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001041 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043 }
1044
1045 private void registerForBroadcasts() {
1046 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1048 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1049 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1050 intentFilter.addAction(ACTION_DEVICE_IDLE);
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001051 intentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 mContext.registerReceiver(mReceiver, intentFilter);
1053 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 private boolean isAirplaneSensitive() {
1056 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1057 Settings.System.AIRPLANE_MODE_RADIOS);
1058 return airplaneModeRadios == null
1059 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1060 }
1061
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001062 private boolean isAirplaneToggleable() {
1063 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1064 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1065 return toggleableRadios != null
1066 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1067 }
1068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 /**
1070 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1071 * currently on.
1072 * @return {@code true} if airplane mode is on.
1073 */
1074 private boolean isAirplaneModeOn() {
1075 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1076 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1077 }
1078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 @Override
1080 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1081 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1082 != PackageManager.PERMISSION_GRANTED) {
1083 pw.println("Permission Denial: can't dump WifiService from from pid="
1084 + Binder.getCallingPid()
1085 + ", uid=" + Binder.getCallingUid());
1086 return;
1087 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001088 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 pw.println("Stay-awake conditions: " +
1090 Settings.System.getInt(mContext.getContentResolver(),
1091 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1092 pw.println();
1093
1094 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001095 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 pw.println();
1097 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001098 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 if (scanResults != null && scanResults.size() != 0) {
1100 pw.println(" BSSID Frequency RSSI Flags SSID");
1101 for (ScanResult r : scanResults) {
1102 pw.printf(" %17s %9d %5d %-16s %s%n",
1103 r.BSSID,
1104 r.frequency,
1105 r.level,
1106 r.capabilities,
1107 r.SSID == null ? "" : r.SSID);
1108 }
1109 }
1110 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001111 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001112 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001113 mScanLocksAcquired + " scan");
1114 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001115 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001116 mScanLocksReleased + " scan");
1117 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 pw.println("Locks held:");
1119 mLocks.dump(pw);
1120 }
1121
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001122 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001123 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1124 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
1126
1127 public void binderDied() {
1128 synchronized (mLocks) {
1129 releaseWifiLockLocked(mBinder);
1130 }
1131 }
1132
1133 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001134 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 }
1136 }
1137
1138 private class LockList {
1139 private List<WifiLock> mList;
1140
1141 private LockList() {
1142 mList = new ArrayList<WifiLock>();
1143 }
1144
1145 private synchronized boolean hasLocks() {
1146 return !mList.isEmpty();
1147 }
1148
1149 private synchronized int getStrongestLockMode() {
1150 if (mList.isEmpty()) {
1151 return WifiManager.WIFI_MODE_FULL;
1152 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001153
1154 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1155 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001157
1158 if (mFullLocksAcquired > mFullLocksReleased) {
1159 return WifiManager.WIFI_MODE_FULL;
1160 }
1161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 return WifiManager.WIFI_MODE_SCAN_ONLY;
1163 }
1164
1165 private void addLock(WifiLock lock) {
1166 if (findLockByBinder(lock.mBinder) < 0) {
1167 mList.add(lock);
1168 }
1169 }
1170
1171 private WifiLock removeLock(IBinder binder) {
1172 int index = findLockByBinder(binder);
1173 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001174 WifiLock ret = mList.remove(index);
1175 ret.unlinkDeathRecipient();
1176 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 } else {
1178 return null;
1179 }
1180 }
1181
1182 private int findLockByBinder(IBinder binder) {
1183 int size = mList.size();
1184 for (int i = size - 1; i >= 0; i--)
1185 if (mList.get(i).mBinder == binder)
1186 return i;
1187 return -1;
1188 }
1189
1190 private void dump(PrintWriter pw) {
1191 for (WifiLock l : mList) {
1192 pw.print(" ");
1193 pw.println(l);
1194 }
1195 }
1196 }
1197
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001198 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001199 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001200 return;
1201 }
1202 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1203 pid, uid, null);
1204 }
1205
1206 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001208 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1209 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1210 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1211 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1212 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 return false;
1214 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001215 if (ws != null && ws.size() == 0) {
1216 ws = null;
1217 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001218 if (ws != null) {
1219 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1220 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001221 if (ws == null) {
1222 ws = new WorkSource(Binder.getCallingUid());
1223 }
1224 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 synchronized (mLocks) {
1226 return acquireWifiLockLocked(wifiLock);
1227 }
1228 }
1229
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001230 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1231 switch(wifiLock.mMode) {
1232 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001233 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001234 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1235 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001236 case WifiManager.WIFI_MODE_SCAN_ONLY:
1237 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1238 break;
1239 }
1240 }
1241
1242 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1243 switch(wifiLock.mMode) {
1244 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001245 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001246 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1247 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001248 case WifiManager.WIFI_MODE_SCAN_ONLY:
1249 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1250 break;
1251 }
1252 }
1253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001255 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001258
The Android Open Source Project10592532009-03-18 17:39:46 -07001259 long ident = Binder.clearCallingIdentity();
1260 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001261 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001262 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001263 case WifiManager.WIFI_MODE_FULL:
1264 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001265 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001266 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1267 ++mFullHighPerfLocksAcquired;
1268 break;
1269
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001270 case WifiManager.WIFI_MODE_SCAN_ONLY:
1271 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001272 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001273 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001274
1275 // Be aggressive about adding new locks into the accounted state...
1276 // we want to over-report rather than under-report.
1277 reportStartWorkSource();
1278
1279 updateWifiState();
1280 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001281 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001282 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001283 } finally {
1284 Binder.restoreCallingIdentity(ident);
1285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 }
1287
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001288 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1289 int uid = Binder.getCallingUid();
1290 int pid = Binder.getCallingPid();
1291 if (ws != null && ws.size() == 0) {
1292 ws = null;
1293 }
1294 if (ws != null) {
1295 enforceWakeSourcePermission(uid, pid);
1296 }
1297 long ident = Binder.clearCallingIdentity();
1298 try {
1299 synchronized (mLocks) {
1300 int index = mLocks.findLockByBinder(lock);
1301 if (index < 0) {
1302 throw new IllegalArgumentException("Wifi lock not active");
1303 }
1304 WifiLock wl = mLocks.mList.get(index);
1305 noteReleaseWifiLock(wl);
1306 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1307 noteAcquireWifiLock(wl);
1308 }
1309 } catch (RemoteException e) {
1310 } finally {
1311 Binder.restoreCallingIdentity(ident);
1312 }
1313 }
1314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 public boolean releaseWifiLock(IBinder lock) {
1316 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1317 synchronized (mLocks) {
1318 return releaseWifiLockLocked(lock);
1319 }
1320 }
1321
1322 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001323 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001324
The Android Open Source Project10592532009-03-18 17:39:46 -07001325 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001326
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001327 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001328
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001329 hadLock = (wifiLock != null);
1330
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001331 long ident = Binder.clearCallingIdentity();
1332 try {
1333 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001334 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001335 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001336 case WifiManager.WIFI_MODE_FULL:
1337 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001338 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001339 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1340 ++mFullHighPerfLocksReleased;
1341 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001342 case WifiManager.WIFI_MODE_SCAN_ONLY:
1343 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001344 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001345 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001346 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001347
1348 // TODO - should this only happen if you hadLock?
1349 updateWifiState();
1350
1351 } catch (RemoteException e) {
1352 } finally {
1353 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001354 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001355
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001356 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001358
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001359 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001360 implements IBinder.DeathRecipient {
1361 String mTag;
1362 int mMode;
1363 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001364 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001365
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001366 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001367 super();
1368 mTag = tag;
1369 mMode = mode;
1370 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001371 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001372 try {
1373 mBinder.linkToDeath(this, 0);
1374 } catch (RemoteException e) {
1375 binderDied();
1376 }
1377 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001378
1379 void unlinkDeathRecipient() {
1380 mBinder.unlinkToDeath(this, 0);
1381 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001382 }
1383
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001384 private class Multicaster extends DeathRecipient {
1385 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001386 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001387 }
1388
1389 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001390 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001391 synchronized (mMulticasters) {
1392 int i = mMulticasters.indexOf(this);
1393 if (i != -1) {
1394 removeMulticasterLocked(i, mMode);
1395 }
1396 }
1397 }
1398
1399 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001400 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001401 }
1402
1403 public int getUid() {
1404 return mMode;
1405 }
1406 }
1407
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001408 public void initializeMulticastFiltering() {
1409 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001410
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001411 synchronized (mMulticasters) {
1412 // if anybody had requested filters be off, leave off
1413 if (mMulticasters.size() != 0) {
1414 return;
1415 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001416 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001417 }
1418 }
1419 }
1420
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001421 public void acquireMulticastLock(IBinder binder, String tag) {
1422 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001423
1424 synchronized (mMulticasters) {
1425 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001426 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001427 // Note that we could call stopPacketFiltering only when
1428 // our new size == 1 (first call), but this function won't
1429 // be called often and by making the stopPacket call each
1430 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001431 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001432 }
1433
1434 int uid = Binder.getCallingUid();
1435 Long ident = Binder.clearCallingIdentity();
1436 try {
1437 mBatteryStats.noteWifiMulticastEnabled(uid);
1438 } catch (RemoteException e) {
1439 } finally {
1440 Binder.restoreCallingIdentity(ident);
1441 }
1442 }
1443
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001444 public void releaseMulticastLock() {
1445 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001446
1447 int uid = Binder.getCallingUid();
1448 synchronized (mMulticasters) {
1449 mMulticastDisabled++;
1450 int size = mMulticasters.size();
1451 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001452 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001453 if ((m != null) && (m.getUid() == uid)) {
1454 removeMulticasterLocked(i, uid);
1455 }
1456 }
1457 }
1458 }
1459
1460 private void removeMulticasterLocked(int i, int uid)
1461 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001462 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001463
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001464 if (removed != null) {
1465 removed.unlinkDeathRecipient();
1466 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001467 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001468 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001469 }
1470
1471 Long ident = Binder.clearCallingIdentity();
1472 try {
1473 mBatteryStats.noteWifiMulticastDisabled(uid);
1474 } catch (RemoteException e) {
1475 } finally {
1476 Binder.restoreCallingIdentity(ident);
1477 }
1478 }
1479
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001480 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001481 enforceAccessPermission();
1482
1483 synchronized (mMulticasters) {
1484 return (mMulticasters.size() > 0);
1485 }
1486 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001487
1488 private void checkAndSetNotification() {
1489 // If we shouldn't place a notification on available networks, then
1490 // don't bother doing any of the following
1491 if (!mNotificationEnabled) return;
1492
1493 State state = mNetworkInfo.getState();
1494 if ((state == NetworkInfo.State.DISCONNECTED)
1495 || (state == NetworkInfo.State.UNKNOWN)) {
1496 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001497 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001498 if (scanResults != null) {
1499 int numOpenNetworks = 0;
1500 for (int i = scanResults.size() - 1; i >= 0; i--) {
1501 ScanResult scanResult = scanResults.get(i);
1502
1503 if (TextUtils.isEmpty(scanResult.capabilities)) {
1504 numOpenNetworks++;
1505 }
1506 }
1507
1508 if (numOpenNetworks > 0) {
1509 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1510 /*
1511 * We've scanned continuously at least
1512 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1513 * probably does not have a remembered network in range,
1514 * since otherwise supplicant would have tried to
1515 * associate and thus resetting this counter.
1516 */
1517 setNotificationVisible(true, numOpenNetworks, false, 0);
1518 }
1519 return;
1520 }
1521 }
1522 }
1523
1524 // No open networks in range, remove the notification
1525 setNotificationVisible(false, 0, false, 0);
1526 }
1527
1528 /**
1529 * Clears variables related to tracking whether a notification has been
1530 * shown recently and clears the current notification.
1531 */
1532 private void resetNotification() {
1533 mNotificationRepeatTime = 0;
1534 mNumScansSinceNetworkStateChange = 0;
1535 setNotificationVisible(false, 0, false, 0);
1536 }
1537
1538 /**
1539 * Display or don't display a notification that there are open Wi-Fi networks.
1540 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1541 * @param numNetworks the number networks seen
1542 * @param force {@code true} to force notification to be shown/not-shown,
1543 * even if it is already shown/not-shown.
1544 * @param delay time in milliseconds after which the notification should be made
1545 * visible or invisible.
1546 */
1547 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1548 int delay) {
1549
1550 // Since we use auto cancel on the notification, when the
1551 // mNetworksAvailableNotificationShown is true, the notification may
1552 // have actually been canceled. However, when it is false we know
1553 // for sure that it is not being shown (it will not be shown any other
1554 // place than here)
1555
1556 // If it should be hidden and it is already hidden, then noop
1557 if (!visible && !mNotificationShown && !force) {
1558 return;
1559 }
1560
1561 NotificationManager notificationManager = (NotificationManager) mContext
1562 .getSystemService(Context.NOTIFICATION_SERVICE);
1563
1564 Message message;
1565 if (visible) {
1566
1567 // Not enough time has passed to show the notification again
1568 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1569 return;
1570 }
1571
1572 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001573 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001574 mNotification = new Notification();
1575 mNotification.when = 0;
1576 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1577 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1578 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1579 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1580 }
1581
1582 CharSequence title = mContext.getResources().getQuantityText(
1583 com.android.internal.R.plurals.wifi_available, numNetworks);
1584 CharSequence details = mContext.getResources().getQuantityText(
1585 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1586 mNotification.tickerText = title;
1587 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1588
1589 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1590
1591 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001592 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001593 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001594 }
1595
Irfan Sheriff0d255342010-07-28 09:35:20 -07001596 mNotificationShown = visible;
1597 }
1598
1599 private class NotificationEnabledSettingObserver extends ContentObserver {
1600
1601 public NotificationEnabledSettingObserver(Handler handler) {
1602 super(handler);
1603 }
1604
1605 public void register() {
1606 ContentResolver cr = mContext.getContentResolver();
1607 cr.registerContentObserver(Settings.Secure.getUriFor(
1608 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1609 mNotificationEnabled = getValue();
1610 }
1611
1612 @Override
1613 public void onChange(boolean selfChange) {
1614 super.onChange(selfChange);
1615
1616 mNotificationEnabled = getValue();
1617 resetNotification();
1618 }
1619
1620 private boolean getValue() {
1621 return Settings.Secure.getInt(mContext.getContentResolver(),
1622 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1623 }
1624 }
1625
1626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627}