blob: ff703fda7064338d4e44293790ca81853148f7df [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 Sheriff4f5f7c92010-10-14 17:01:27 -0700880 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400882 if (DBG) {
883 Slog.d(TAG, "ACTION_SCREEN_OFF");
884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700886 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 /*
888 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
889 * AND the "stay on while plugged in" setting doesn't match the
890 * current power conditions (i.e, not plugged in, plugged in to USB,
891 * or plugged in to AC).
892 */
893 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700894 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700895 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700896 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700897 // we don't have time to track down for this release. Delay instead,
898 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700899 // TODO - fix the race conditions and switch back to the immediate turn-off
900 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400901 if (DBG) {
902 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
903 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700904 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
905 // // do not keep Wifi awake when screen is off if Wifi is not associated
906 // mDeviceIdle = true;
907 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400908 } else {
909 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400910 if (DBG) {
911 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
912 + "ms");
913 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400914 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400918 if (DBG) {
919 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700922 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700923 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
925 /*
926 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
927 * AND we are transitioning from a state in which the device was supposed
928 * to stay awake to a state in which it is not supposed to stay awake.
929 * If "stay awake" state is not changing, we do nothing, to avoid resetting
930 * the already-set timer.
931 */
932 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400933 if (DBG) {
934 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
937 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
938 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400939 if (DBG) {
940 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 }
944 mPluggedType = pluggedType;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700945 } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
946 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
947 BluetoothA2dp.STATE_NOT_PLAYING);
948 mWifiStateMachine.setBluetoothScanMode(state == BluetoothA2dp.STATE_PLAYING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 }
951
952 /**
953 * Determines whether the Wi-Fi chipset should stay awake or be put to
954 * sleep. Looks at the setting for the sleep policy and the current
955 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800956 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 * @see #shouldDeviceStayAwake(int, int)
958 */
959 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
960 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
961 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
962
963 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
964 // Never sleep
965 return true;
966 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
967 (pluggedType != 0)) {
968 // Never sleep while plugged, and we're plugged
969 return true;
970 } else {
971 // Default
972 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
973 }
974 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 /**
977 * Determine whether the bit value corresponding to {@code pluggedType} is set in
978 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
979 * of {@code 0} isn't really a plugged type, but rather an indication that the
980 * device isn't plugged in at all, there is no bit value corresponding to a
981 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700982 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 * @param stayAwakeConditions a bit string specifying which "plugged types" should
984 * keep the device (and hence Wi-Fi) awake.
985 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
986 * being made
987 * @return {@code true} if {@code pluggedType} indicates that the device is
988 * supposed to stay awake, {@code false} otherwise.
989 */
990 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
991 return (stayAwakeConditions & pluggedType) != 0;
992 }
993 };
994
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700995 private synchronized void reportStartWorkSource() {
996 mTmpWorkSource.clear();
997 if (mDeviceIdle) {
998 for (int i=0; i<mLocks.mList.size(); i++) {
999 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001000 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001001 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001002 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001003 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 private void updateWifiState() {
1006 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001007 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001009 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
1011 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001012
1013 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001015 }
1016 /* If device is not idle, lockmode cannot be scan only */
1017 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1019 }
1020
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001021 /* Disable tethering when airplane mode is enabled */
1022 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001023 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001024 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001025
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001026 if (wifiShouldBeEnabled) {
1027 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001028 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001029 mWifiStateMachine.setWifiEnabled(true);
1030 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001031 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001032 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001033 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1034 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001036 mWifiStateMachine.requestCmWakeLock();
1037 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001039 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001040 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
1042 }
1043
1044 private void registerForBroadcasts() {
1045 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1047 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1048 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1049 intentFilter.addAction(ACTION_DEVICE_IDLE);
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}