blob: 19f56a870a960c596b6bf81d52c75c333c3fd843 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07002 * Copyright (C) 2010 The Android Open Source Project
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080019import android.app.AlarmManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070020import android.app.Notification;
21import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.app.PendingIntent;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070023import android.bluetooth.BluetoothA2dp;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070024import android.bluetooth.BluetoothAdapter;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080025import android.bluetooth.BluetoothDevice;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070026import android.bluetooth.BluetoothProfile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.BroadcastReceiver;
28import android.content.ContentResolver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.net.wifi.IWifiManager;
35import android.net.wifi.WifiInfo;
36import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070037import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.net.wifi.ScanResult;
39import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070040import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080041import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080042import android.net.ConnectivityManager;
43import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070045import android.net.NetworkInfo;
46import android.net.NetworkInfo.State;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070048import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.HandlerThread;
50import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080051import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070052import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070054import android.os.ServiceManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070055import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070057import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080058import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
60import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080062import java.util.Set;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070063import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.io.FileDescriptor;
65import java.io.PrintWriter;
66
The Android Open Source Project10592532009-03-18 17:39:46 -070067import com.android.internal.app.IBatteryStats;
The Android Open Source Project10592532009-03-18 17:39:46 -070068import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080069import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071/**
72 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070073 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 *
75 * @hide
76 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070077//TODO: Clean up multiple locks and implement WifiService
78// as a SM to track soft AP/client/adhoc bring up based
79// on device idle state, airplane mode and boot.
80
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081public class WifiService extends IWifiManager.Stub {
82 private static final String TAG = "WifiService";
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070083 private static final boolean DBG = true;
84
Irfan Sheriff0d255342010-07-28 09:35:20 -070085 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
87 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
89 private AlarmManager mAlarmManager;
90 private PendingIntent mIdleIntent;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070091 private BluetoothA2dp mBluetoothA2dp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 private static final int IDLE_REQUEST = 0;
93 private boolean mScreenOff;
94 private boolean mDeviceIdle;
95 private int mPluggedType;
96
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070097 // true if the user enabled Wifi while in airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070098 private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700101 // some wifi lock statistics
102 private int mFullLocksAcquired;
103 private int mFullLocksReleased;
104 private int mScanLocksAcquired;
105 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700106
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700107 private final List<Multicaster> mMulticasters =
108 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700109 private int mMulticastEnabled;
110 private int mMulticastDisabled;
111
The Android Open Source Project10592532009-03-18 17:39:46 -0700112 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800113
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800114 ConnectivityManager mCm;
115 private String[] mWifiRegexs;
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800118 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
119 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 * the approximate point at which the battery drain caused by Wi-Fi
121 * being enabled but not active exceeds the battery drain caused by
122 * re-establishing a connection to the mobile data network.
123 */
124 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 /**
127 * Number of allowed radio frequency channels in various regulatory domains.
128 * This list is sufficient for 802.11b/g networks (2.4GHz range).
129 */
130 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
131
132 private static final String ACTION_DEVICE_IDLE =
133 "com.android.server.WifiManager.action.DEVICE_IDLE";
134
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700135 private boolean mIsReceiverRegistered = false;
136
Irfan Sheriff0d255342010-07-28 09:35:20 -0700137
138 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
139
140 // Variables relating to the 'available networks' notification
141 /**
142 * The icon to show in the 'available networks' notification. This will also
143 * be the ID of the Notification given to the NotificationManager.
144 */
145 private static final int ICON_NETWORKS_AVAILABLE =
146 com.android.internal.R.drawable.stat_notify_wifi_in_range;
147 /**
148 * When a notification is shown, we wait this amount before possibly showing it again.
149 */
150 private final long NOTIFICATION_REPEAT_DELAY_MS;
151 /**
152 * Whether the user has set the setting to show the 'available networks' notification.
153 */
154 private boolean mNotificationEnabled;
155 /**
156 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
157 */
158 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
159 /**
160 * The {@link System#currentTimeMillis()} must be at least this value for us
161 * to show the notification again.
162 */
163 private long mNotificationRepeatTime;
164 /**
165 * The Notification object given to the NotificationManager.
166 */
167 private Notification mNotification;
168 /**
169 * Whether the notification is being shown, as set by us. That is, if the
170 * user cancels the notification, we will not receive the callback so this
171 * will still be true. We only guarantee if this is false, then the
172 * notification is not showing.
173 */
174 private boolean mNotificationShown;
175 /**
176 * The number of continuous scans that must occur before consider the
177 * supplicant in a scanning state. This allows supplicant to associate with
178 * remembered networks that are in the scan results.
179 */
180 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
181 /**
182 * The number of scans since the last network state change. When this
183 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
184 * supplicant to actually be scanning. When the network state changes to
185 * something other than scanning, we reset this to 0.
186 */
187 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700188
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700189 /**
190 * Temporary for computing UIDS that are responsible for starting WIFI.
191 * Protected by mWifiStateTracker lock.
192 */
193 private final WorkSource mTmpWorkSource = new WorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700194
195 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700197 mWifiStateMachine = new WifiStateMachine(mContext);
198 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700199 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
202 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
203 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
204
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700205 HandlerThread wifiThread = new HandlerThread("WifiService");
206 wifiThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 mContext.registerReceiver(
209 new BroadcastReceiver() {
210 @Override
211 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700212 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700213 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700214 // on airplane disable, restore Wifi if the saved state indicates so
215 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
216 persistWifiEnabled(true);
217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 updateWifiState();
219 }
220 },
221 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
222
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800223 mContext.registerReceiver(
224 new BroadcastReceiver() {
225 @Override
226 public void onReceive(Context context, Intent intent) {
227
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700228 ArrayList<String> available = intent.getStringArrayListExtra(
229 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
230 ArrayList<String> active = intent.getStringArrayListExtra(
231 ConnectivityManager.EXTRA_ACTIVE_TETHER);
232 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800233
234 }
235 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700236
237 IntentFilter filter = new IntentFilter();
238 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
239 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
240 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
241
242 mContext.registerReceiver(
243 new BroadcastReceiver() {
244 @Override
245 public void onReceive(Context context, Intent intent) {
246 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
247 // reset & clear notification on any wifi state change
248 resetNotification();
249 } else if (intent.getAction().equals(
250 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
251 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
252 WifiManager.EXTRA_NETWORK_INFO);
253 // reset & clear notification on a network connect & disconnect
254 switch(mNetworkInfo.getDetailedState()) {
255 case CONNECTED:
256 case DISCONNECTED:
257 resetNotification();
258 break;
259 }
260 } else if (intent.getAction().equals(
261 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
262 checkAndSetNotification();
263 }
264 }
265 }, filter);
266
267 // Setting is in seconds
268 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
269 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
270 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
271 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800272 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800273
Irfan Sheriff7b009782010-03-11 16:37:45 -0800274 /**
275 * Check if Wi-Fi needs to be enabled and start
276 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700277 *
278 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800279 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700280 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700281 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700282 boolean wifiEnabled = !isAirplaneModeOn()
283 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800284 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
285 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700286 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800287 }
288
289 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
290
291 boolean wifiTethered = false;
292 boolean wifiAvailable = false;
293
294 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
295 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
296
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700297 if (mCm == null) {
298 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
299 }
300
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800301 mWifiRegexs = mCm.getTetherableWifiRegexs();
302
303 for (String intf : available) {
304 for (String regex : mWifiRegexs) {
305 if (intf.matches(regex)) {
306
307 InterfaceConfiguration ifcg = null;
308 try {
309 ifcg = service.getInterfaceConfig(intf);
310 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700311 /* IP/netmask: 192.168.43.1/255.255.255.0 */
312 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800313 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
314 ifcg.interfaceFlags = "up";
315
316 service.setInterfaceConfig(intf, ifcg);
317 }
318 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800319 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700320 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800321 return;
322 }
323
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800324 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700325 Slog.e(TAG, "Error tethering on " + intf);
326 setWifiApEnabled(null, false);
327 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800328 }
329 break;
330 }
331 }
332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 }
334
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700335 private boolean testAndClearWifiSavedState() {
336 final ContentResolver cr = mContext.getContentResolver();
337 int wifiSavedState = 0;
338 try {
339 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
340 if(wifiSavedState == 1)
341 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
342 } catch (Settings.SettingNotFoundException e) {
343 ;
344 }
345 return (wifiSavedState == 1);
346 }
347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 private boolean getPersistedWifiEnabled() {
349 final ContentResolver cr = mContext.getContentResolver();
350 try {
351 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
352 } catch (Settings.SettingNotFoundException e) {
353 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
354 return false;
355 }
356 }
357
358 private void persistWifiEnabled(boolean enabled) {
359 final ContentResolver cr = mContext.getContentResolver();
360 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
361 }
362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 /**
364 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700365 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 */
367 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700368 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700369 return mWifiStateMachine.syncPingSupplicant();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 }
371
372 /**
373 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700375 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700377 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 }
379
380 private void enforceAccessPermission() {
381 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
382 "WifiService");
383 }
384
385 private void enforceChangePermission() {
386 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
387 "WifiService");
388
389 }
390
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700391 private void enforceMulticastChangePermission() {
392 mContext.enforceCallingOrSelfPermission(
393 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
394 "WifiService");
395 }
396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700398 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
399 * @param enable {@code true} to enable, {@code false} to disable.
400 * @return {@code true} if the enable/disable operation was
401 * started or is already in the queue.
402 */
403 public synchronized boolean setWifiEnabled(boolean enable) {
404 enforceChangePermission();
405
406 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700407 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700408 }
409
410 // set a flag if the user is enabling Wifi while in airplane mode
411 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
412 mAirplaneModeOverwridden.set(true);
413 }
414
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700415 if (enable) {
416 reportStartWorkSource();
417 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700418 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700419
420 /*
421 * Caller might not have WRITE_SECURE_SETTINGS,
422 * only CHANGE_WIFI_STATE is enforced
423 */
424 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700425 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700426 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700427
428 if (enable) {
429 if (!mIsReceiverRegistered) {
430 registerForBroadcasts();
431 mIsReceiverRegistered = true;
432 }
433 } else if (mIsReceiverRegistered){
434 mContext.unregisterReceiver(mReceiver);
435 mIsReceiverRegistered = false;
436 }
437
438 return true;
439 }
440
441 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 * see {@link WifiManager#getWifiState()}
443 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
444 * {@link WifiManager#WIFI_STATE_DISABLING},
445 * {@link WifiManager#WIFI_STATE_ENABLED},
446 * {@link WifiManager#WIFI_STATE_ENABLING},
447 * {@link WifiManager#WIFI_STATE_UNKNOWN}
448 */
449 public int getWifiEnabledState() {
450 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700451 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 }
453
454 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700455 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800456 * @param wifiConfig SSID, security and channel details as
457 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700458 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800459 * @return {@code true} if the start operation was
460 * started or is already in the queue.
461 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700462 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800463 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800464
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700465 if (enabled) {
466 /* Use default config if there is no existing config */
467 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
468 wifiConfig = new WifiConfiguration();
469 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
470 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
471 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700472 /*
473 * Caller might not have WRITE_SECURE_SETTINGS,
474 * only CHANGE_WIFI_STATE is enforced
475 */
476 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700477 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700478 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800479 }
480
Irfan Sheriff0d255342010-07-28 09:35:20 -0700481 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700482
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800483 return true;
484 }
485
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700486 /**
487 * see {@link WifiManager#getWifiApState()}
488 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
489 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
490 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
491 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
492 * {@link WifiManager#WIFI_AP_STATE_FAILED}
493 */
494 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700495 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700496 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700497 }
498
499 /**
500 * see {@link WifiManager#getWifiApConfiguration()}
501 * @return soft access point configuration
502 */
503 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800504 final ContentResolver cr = mContext.getContentResolver();
505 WifiConfiguration wifiConfig = new WifiConfiguration();
506 int authType;
507 try {
508 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
509 if (wifiConfig.SSID == null)
510 return null;
511 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
512 wifiConfig.allowedKeyManagement.set(authType);
513 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
514 return wifiConfig;
515 } catch (Settings.SettingNotFoundException e) {
516 Slog.e(TAG,"AP settings not found, returning");
517 return null;
518 }
519 }
520
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700521 /**
522 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
523 * @param wifiConfig WifiConfiguration details for soft access point
524 */
525 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700526 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800527 final ContentResolver cr = mContext.getContentResolver();
528 boolean isWpa;
529 if (wifiConfig == null)
530 return;
531 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
532 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
533 Settings.Secure.putInt(cr,
534 Settings.Secure.WIFI_AP_SECURITY,
535 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
536 if (isWpa)
537 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
538 }
539
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800540 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700541 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800542 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700543 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700544 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700545 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800546 }
547
548 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700549 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800550 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700551 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700552 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700553 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800554 }
555
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700556 /**
557 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700558 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700559 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700560 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700561 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800562 }
563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 /**
565 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
566 * @return the list of configured networks
567 */
568 public List<WifiConfiguration> getConfiguredNetworks() {
569 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700570 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800571 }
572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 /**
574 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
575 * @return the supplicant-assigned identifier for the new or updated
576 * network if the operation succeeds, or {@code -1} if it fails
577 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800578 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700580 return mWifiStateMachine.syncAddOrUpdateNetwork(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 }
582
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700583 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
585 * @param netId the integer that identifies the network configuration
586 * to the supplicant
587 * @return {@code true} if the operation succeeded
588 */
589 public boolean removeNetwork(int netId) {
590 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700591 return mWifiStateMachine.syncRemoveNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 }
593
594 /**
595 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
596 * @param netId the integer that identifies the network configuration
597 * to the supplicant
598 * @param disableOthers if true, disable all other networks.
599 * @return {@code true} if the operation succeeded
600 */
601 public boolean enableNetwork(int netId, boolean disableOthers) {
602 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700603 return mWifiStateMachine.syncEnableNetwork(netId, disableOthers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 }
605
606 /**
607 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
608 * @param netId the integer that identifies the network configuration
609 * to the supplicant
610 * @return {@code true} if the operation succeeded
611 */
612 public boolean disableNetwork(int netId) {
613 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700614 return mWifiStateMachine.syncDisableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 }
616
617 /**
618 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
619 * @return the Wi-Fi information, contained in {@link WifiInfo}.
620 */
621 public WifiInfo getConnectionInfo() {
622 enforceAccessPermission();
623 /*
624 * Make sure we have the latest information, by sending
625 * a status request to the supplicant.
626 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700627 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 }
629
630 /**
631 * Return the results of the most recent access point scan, in the form of
632 * a list of {@link ScanResult} objects.
633 * @return the list of results
634 */
635 public List<ScanResult> getScanResults() {
636 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700637 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 }
639
640 /**
641 * Tell the supplicant to persist the current list of configured networks.
642 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700643 *
644 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 */
646 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700647 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700649 return mWifiStateMachine.syncSaveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 }
651
652 /**
653 * Set the number of radio frequency channels that are allowed to be used
654 * in the current regulatory domain. This method should be used only
655 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700656 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 * persisted as a Secure setting.
658 * @param numChannels the number of allowed channels. Must be greater than 0
659 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700660 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
662 * {@code numChannels} is outside the valid range.
663 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700664 public synchronized boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800665 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700666 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -0700668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 /*
670 * Validate the argument. We'd like to let the Wi-Fi driver do this,
671 * but if Wi-Fi isn't currently enabled, that's not possible, and
672 * we want to persist the setting anyway,so that it will take
673 * effect when Wi-Fi does become enabled.
674 */
675 boolean found = false;
676 for (int validChan : sValidRegulatoryChannelCounts) {
677 if (validChan == numChannels) {
678 found = true;
679 break;
680 }
681 }
682 if (!found) {
683 return false;
684 }
685
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700686 if (persist) {
687 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -0700688 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
689 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700690 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700691
Irfan Sheriff0d255342010-07-28 09:35:20 -0700692 mWifiStateMachine.setNumAllowedChannels(numChannels);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700693
694 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 }
696
697 /**
698 * Return the number of frequency channels that are allowed
699 * to be used in the current regulatory domain.
700 * @return the number of allowed channels, or {@code -1} if an error occurs
701 */
702 public int getNumAllowedChannels() {
703 int numChannels;
704
705 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800706
707 /*
708 * If we can't get the value from the driver (e.g., because
709 * Wi-Fi is not currently enabled), get the value from
710 * Settings.
711 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700712 numChannels = mWifiStateMachine.getNumAllowedChannels();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800713 if (numChannels < 0) {
714 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
715 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
716 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 }
718 return numChannels;
719 }
720
721 /**
722 * Return the list of valid values for the number of allowed radio channels
723 * for various regulatory domains.
724 * @return the list of channel counts
725 */
726 public int[] getValidChannelCounts() {
727 enforceAccessPermission();
728 return sValidRegulatoryChannelCounts;
729 }
730
731 /**
732 * Return the DHCP-assigned addresses from the last successful DHCP request,
733 * if any.
734 * @return the DHCP information
735 */
736 public DhcpInfo getDhcpInfo() {
737 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700738 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 }
740
Irfan Sheriff0d255342010-07-28 09:35:20 -0700741 /**
742 * see {@link android.net.wifi.WifiManager#startWifi}
743 *
744 */
745 public void startWifi() {
746 enforceChangePermission();
747 /* TODO: may be add permissions for access only to connectivity service
748 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
749 * of WifiLock & device idle status unless wifi enabled status is toggled
750 */
751
752 mWifiStateMachine.setDriverStart(true);
753 mWifiStateMachine.reconnectCommand();
754 }
755
756 /**
757 * see {@link android.net.wifi.WifiManager#stopWifi}
758 *
759 */
760 public void stopWifi() {
761 enforceChangePermission();
762 /* TODO: may be add permissions for access only to connectivity service
763 * TODO: if a stop is issued, wifi is brought up only by startWifi
764 * unless wifi enabled status is toggled
765 */
766 mWifiStateMachine.setDriverStart(false);
767 }
768
769
770 /**
771 * see {@link android.net.wifi.WifiManager#addToBlacklist}
772 *
773 */
774 public void addToBlacklist(String bssid) {
775 enforceChangePermission();
776
777 mWifiStateMachine.addToBlacklist(bssid);
778 }
779
780 /**
781 * see {@link android.net.wifi.WifiManager#clearBlacklist}
782 *
783 */
784 public void clearBlacklist() {
785 enforceChangePermission();
786
787 mWifiStateMachine.clearBlacklist();
788 }
789
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700790 public void connectNetworkWithId(int networkId) {
791 enforceChangePermission();
792 mWifiStateMachine.connectNetwork(networkId);
793 }
794
795 public void connectNetworkWithConfig(WifiConfiguration config) {
796 enforceChangePermission();
797 mWifiStateMachine.connectNetwork(config);
798 }
799
800 public void saveNetwork(WifiConfiguration config) {
801 enforceChangePermission();
802 mWifiStateMachine.saveNetwork(config);
803 }
804
805 public void forgetNetwork(int netId) {
806 enforceChangePermission();
807 mWifiStateMachine.forgetNetwork(netId);
808 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700809
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700810 public void startWpsPbc(String bssid) {
811 enforceChangePermission();
812 mWifiStateMachine.startWpsPbc(bssid);
813 }
814
815 public void startWpsPin(String bssid, int apPin) {
816 enforceChangePermission();
817 mWifiStateMachine.startWpsPin(bssid, apPin);
818 }
819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
821 @Override
822 public void onReceive(Context context, Intent intent) {
823 String action = intent.getAction();
824
Doug Zongker43866e02010-01-07 12:09:54 -0800825 long idleMillis =
826 Settings.Secure.getLong(mContext.getContentResolver(),
827 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800829 Settings.System.getInt(mContext.getContentResolver(),
830 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800832 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 mAlarmManager.cancel(mIdleIntent);
834 mDeviceIdle = false;
835 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700836 // Once the screen is on, we are not keeping WIFI running
837 // because of any locks so clear that tracking immediately.
838 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700839 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800841 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700843 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 /*
845 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
846 * AND the "stay on while plugged in" setting doesn't match the
847 * current power conditions (i.e, not plugged in, plugged in to USB,
848 * or plugged in to AC).
849 */
850 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700851 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700852 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700853 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700854 // we don't have time to track down for this release. Delay instead,
855 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700856 // TODO - fix the race conditions and switch back to the immediate turn-off
857 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -0800858 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700859 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
860 // // do not keep Wifi awake when screen is off if Wifi is not associated
861 // mDeviceIdle = true;
862 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400863 } else {
864 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800865 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400866 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 }
869 /* we can return now -- there's nothing to do until we get the idle intent back */
870 return;
871 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800872 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700874 reportStartWorkSource();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
876 /*
877 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
878 * AND we are transitioning from a state in which the device was supposed
879 * to stay awake to a state in which it is not supposed to stay awake.
880 * If "stay awake" state is not changing, we do nothing, to avoid resetting
881 * the already-set timer.
882 */
883 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800884 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
886 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
887 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800888 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
890 mPluggedType = pluggedType;
891 return;
892 }
893 mPluggedType = pluggedType;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700894 } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
895 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
896 BluetoothA2dp.STATE_NOT_PLAYING);
897 mWifiStateMachine.setBluetoothScanMode(state == BluetoothA2dp.STATE_PLAYING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 } else {
899 return;
900 }
901
902 updateWifiState();
903 }
904
905 /**
906 * Determines whether the Wi-Fi chipset should stay awake or be put to
907 * sleep. Looks at the setting for the sleep policy and the current
908 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800909 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 * @see #shouldDeviceStayAwake(int, int)
911 */
912 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
913 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
914 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
915
916 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
917 // Never sleep
918 return true;
919 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
920 (pluggedType != 0)) {
921 // Never sleep while plugged, and we're plugged
922 return true;
923 } else {
924 // Default
925 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
926 }
927 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 /**
930 * Determine whether the bit value corresponding to {@code pluggedType} is set in
931 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
932 * of {@code 0} isn't really a plugged type, but rather an indication that the
933 * device isn't plugged in at all, there is no bit value corresponding to a
934 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700935 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 * @param stayAwakeConditions a bit string specifying which "plugged types" should
937 * keep the device (and hence Wi-Fi) awake.
938 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
939 * being made
940 * @return {@code true} if {@code pluggedType} indicates that the device is
941 * supposed to stay awake, {@code false} otherwise.
942 */
943 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
944 return (stayAwakeConditions & pluggedType) != 0;
945 }
946 };
947
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700948 private synchronized void reportStartWorkSource() {
949 mTmpWorkSource.clear();
950 if (mDeviceIdle) {
951 for (int i=0; i<mLocks.mList.size(); i++) {
952 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700953 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700954 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700955 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700956 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 private void updateWifiState() {
959 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700960 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 boolean lockHeld = mLocks.hasLocks();
962 int strongestLockMode;
963 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
964 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
965 if (mDeviceIdle && lockHeld) {
966 strongestLockMode = mLocks.getStrongestLockMode();
967 } else {
968 strongestLockMode = WifiManager.WIFI_MODE_FULL;
969 }
970
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700971 /* Disable tethering when airplane mode is enabled */
972 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700973 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700974 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700975
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700976 if (wifiShouldBeEnabled) {
977 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700978 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700979 mWifiStateMachine.setWifiEnabled(true);
980 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700981 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700982 mWifiStateMachine.setDriverStart(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700984 mWifiStateMachine.requestCmWakeLock();
985 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700987 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700988 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
990 }
991
992 private void registerForBroadcasts() {
993 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
995 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
996 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
997 intentFilter.addAction(ACTION_DEVICE_IDLE);
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700998 intentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 mContext.registerReceiver(mReceiver, intentFilter);
1000 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 private boolean isAirplaneSensitive() {
1003 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1004 Settings.System.AIRPLANE_MODE_RADIOS);
1005 return airplaneModeRadios == null
1006 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1007 }
1008
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001009 private boolean isAirplaneToggleable() {
1010 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1011 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1012 return toggleableRadios != null
1013 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1014 }
1015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 /**
1017 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1018 * currently on.
1019 * @return {@code true} if airplane mode is on.
1020 */
1021 private boolean isAirplaneModeOn() {
1022 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1023 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1024 }
1025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 @Override
1027 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1028 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1029 != PackageManager.PERMISSION_GRANTED) {
1030 pw.println("Permission Denial: can't dump WifiService from from pid="
1031 + Binder.getCallingPid()
1032 + ", uid=" + Binder.getCallingUid());
1033 return;
1034 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001035 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 pw.println("Stay-awake conditions: " +
1037 Settings.System.getInt(mContext.getContentResolver(),
1038 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1039 pw.println();
1040
1041 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001042 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 pw.println();
1044 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001045 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 if (scanResults != null && scanResults.size() != 0) {
1047 pw.println(" BSSID Frequency RSSI Flags SSID");
1048 for (ScanResult r : scanResults) {
1049 pw.printf(" %17s %9d %5d %-16s %s%n",
1050 r.BSSID,
1051 r.frequency,
1052 r.level,
1053 r.capabilities,
1054 r.SSID == null ? "" : r.SSID);
1055 }
1056 }
1057 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001058 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1059 mScanLocksAcquired + " scan");
1060 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1061 mScanLocksReleased + " scan");
1062 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 pw.println("Locks held:");
1064 mLocks.dump(pw);
1065 }
1066
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001067 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001068 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1069 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 }
1071
1072 public void binderDied() {
1073 synchronized (mLocks) {
1074 releaseWifiLockLocked(mBinder);
1075 }
1076 }
1077
1078 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001079 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 }
1081 }
1082
1083 private class LockList {
1084 private List<WifiLock> mList;
1085
1086 private LockList() {
1087 mList = new ArrayList<WifiLock>();
1088 }
1089
1090 private synchronized boolean hasLocks() {
1091 return !mList.isEmpty();
1092 }
1093
1094 private synchronized int getStrongestLockMode() {
1095 if (mList.isEmpty()) {
1096 return WifiManager.WIFI_MODE_FULL;
1097 }
1098 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001099 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 return WifiManager.WIFI_MODE_FULL;
1101 }
1102 }
1103 return WifiManager.WIFI_MODE_SCAN_ONLY;
1104 }
1105
1106 private void addLock(WifiLock lock) {
1107 if (findLockByBinder(lock.mBinder) < 0) {
1108 mList.add(lock);
1109 }
1110 }
1111
1112 private WifiLock removeLock(IBinder binder) {
1113 int index = findLockByBinder(binder);
1114 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001115 WifiLock ret = mList.remove(index);
1116 ret.unlinkDeathRecipient();
1117 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 } else {
1119 return null;
1120 }
1121 }
1122
1123 private int findLockByBinder(IBinder binder) {
1124 int size = mList.size();
1125 for (int i = size - 1; i >= 0; i--)
1126 if (mList.get(i).mBinder == binder)
1127 return i;
1128 return -1;
1129 }
1130
1131 private void dump(PrintWriter pw) {
1132 for (WifiLock l : mList) {
1133 pw.print(" ");
1134 pw.println(l);
1135 }
1136 }
1137 }
1138
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001139 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001140 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001141 return;
1142 }
1143 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1144 pid, uid, null);
1145 }
1146
1147 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1149 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1150 return false;
1151 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001152 if (ws != null) {
1153 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1154 }
1155 if (ws != null && ws.size() == 0) {
1156 ws = null;
1157 }
1158 if (ws == null) {
1159 ws = new WorkSource(Binder.getCallingUid());
1160 }
1161 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 synchronized (mLocks) {
1163 return acquireWifiLockLocked(wifiLock);
1164 }
1165 }
1166
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001167 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1168 switch(wifiLock.mMode) {
1169 case WifiManager.WIFI_MODE_FULL:
1170 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1171 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001172 case WifiManager.WIFI_MODE_SCAN_ONLY:
1173 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1174 break;
1175 }
1176 }
1177
1178 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1179 switch(wifiLock.mMode) {
1180 case WifiManager.WIFI_MODE_FULL:
1181 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1182 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001183 case WifiManager.WIFI_MODE_SCAN_ONLY:
1184 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1185 break;
1186 }
1187 }
1188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001190 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001193
The Android Open Source Project10592532009-03-18 17:39:46 -07001194 long ident = Binder.clearCallingIdentity();
1195 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001196 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001197 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001198 case WifiManager.WIFI_MODE_FULL:
1199 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001200 break;
1201 case WifiManager.WIFI_MODE_SCAN_ONLY:
1202 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001203 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001204 }
1205 } catch (RemoteException e) {
1206 } finally {
1207 Binder.restoreCallingIdentity(ident);
1208 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001209
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001210 // Be aggressive about adding new locks into the accounted state...
1211 // we want to over-report rather than under-report.
1212 reportStartWorkSource();
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 updateWifiState();
1215 return true;
1216 }
1217
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001218 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1219 int uid = Binder.getCallingUid();
1220 int pid = Binder.getCallingPid();
1221 if (ws != null && ws.size() == 0) {
1222 ws = null;
1223 }
1224 if (ws != null) {
1225 enforceWakeSourcePermission(uid, pid);
1226 }
1227 long ident = Binder.clearCallingIdentity();
1228 try {
1229 synchronized (mLocks) {
1230 int index = mLocks.findLockByBinder(lock);
1231 if (index < 0) {
1232 throw new IllegalArgumentException("Wifi lock not active");
1233 }
1234 WifiLock wl = mLocks.mList.get(index);
1235 noteReleaseWifiLock(wl);
1236 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1237 noteAcquireWifiLock(wl);
1238 }
1239 } catch (RemoteException e) {
1240 } finally {
1241 Binder.restoreCallingIdentity(ident);
1242 }
1243 }
1244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 public boolean releaseWifiLock(IBinder lock) {
1246 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1247 synchronized (mLocks) {
1248 return releaseWifiLockLocked(lock);
1249 }
1250 }
1251
1252 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001253 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001254
The Android Open Source Project10592532009-03-18 17:39:46 -07001255 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001256
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001257 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001258
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001259 hadLock = (wifiLock != null);
1260
1261 if (hadLock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001262 long ident = Binder.clearCallingIdentity();
1263 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001264 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001265 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001266 case WifiManager.WIFI_MODE_FULL:
1267 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001268 break;
1269 case WifiManager.WIFI_MODE_SCAN_ONLY:
1270 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001271 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001272 }
1273 } catch (RemoteException e) {
1274 } finally {
1275 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001276 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001277 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001278 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001280 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001282
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001283 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001284 implements IBinder.DeathRecipient {
1285 String mTag;
1286 int mMode;
1287 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001288 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001289
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001290 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001291 super();
1292 mTag = tag;
1293 mMode = mode;
1294 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001295 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001296 try {
1297 mBinder.linkToDeath(this, 0);
1298 } catch (RemoteException e) {
1299 binderDied();
1300 }
1301 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001302
1303 void unlinkDeathRecipient() {
1304 mBinder.unlinkToDeath(this, 0);
1305 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001306 }
1307
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001308 private class Multicaster extends DeathRecipient {
1309 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001310 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001311 }
1312
1313 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001314 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001315 synchronized (mMulticasters) {
1316 int i = mMulticasters.indexOf(this);
1317 if (i != -1) {
1318 removeMulticasterLocked(i, mMode);
1319 }
1320 }
1321 }
1322
1323 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001324 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001325 }
1326
1327 public int getUid() {
1328 return mMode;
1329 }
1330 }
1331
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001332 public void initializeMulticastFiltering() {
1333 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001334
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001335 synchronized (mMulticasters) {
1336 // if anybody had requested filters be off, leave off
1337 if (mMulticasters.size() != 0) {
1338 return;
1339 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001340 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001341 }
1342 }
1343 }
1344
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001345 public void acquireMulticastLock(IBinder binder, String tag) {
1346 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001347
1348 synchronized (mMulticasters) {
1349 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001350 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001351 // Note that we could call stopPacketFiltering only when
1352 // our new size == 1 (first call), but this function won't
1353 // be called often and by making the stopPacket call each
1354 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001355 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001356 }
1357
1358 int uid = Binder.getCallingUid();
1359 Long ident = Binder.clearCallingIdentity();
1360 try {
1361 mBatteryStats.noteWifiMulticastEnabled(uid);
1362 } catch (RemoteException e) {
1363 } finally {
1364 Binder.restoreCallingIdentity(ident);
1365 }
1366 }
1367
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001368 public void releaseMulticastLock() {
1369 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001370
1371 int uid = Binder.getCallingUid();
1372 synchronized (mMulticasters) {
1373 mMulticastDisabled++;
1374 int size = mMulticasters.size();
1375 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001376 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001377 if ((m != null) && (m.getUid() == uid)) {
1378 removeMulticasterLocked(i, uid);
1379 }
1380 }
1381 }
1382 }
1383
1384 private void removeMulticasterLocked(int i, int uid)
1385 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001386 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001387
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001388 if (removed != null) {
1389 removed.unlinkDeathRecipient();
1390 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001391 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001392 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001393 }
1394
1395 Long ident = Binder.clearCallingIdentity();
1396 try {
1397 mBatteryStats.noteWifiMulticastDisabled(uid);
1398 } catch (RemoteException e) {
1399 } finally {
1400 Binder.restoreCallingIdentity(ident);
1401 }
1402 }
1403
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001404 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001405 enforceAccessPermission();
1406
1407 synchronized (mMulticasters) {
1408 return (mMulticasters.size() > 0);
1409 }
1410 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001411
1412 private void checkAndSetNotification() {
1413 // If we shouldn't place a notification on available networks, then
1414 // don't bother doing any of the following
1415 if (!mNotificationEnabled) return;
1416
1417 State state = mNetworkInfo.getState();
1418 if ((state == NetworkInfo.State.DISCONNECTED)
1419 || (state == NetworkInfo.State.UNKNOWN)) {
1420 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001421 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001422 if (scanResults != null) {
1423 int numOpenNetworks = 0;
1424 for (int i = scanResults.size() - 1; i >= 0; i--) {
1425 ScanResult scanResult = scanResults.get(i);
1426
1427 if (TextUtils.isEmpty(scanResult.capabilities)) {
1428 numOpenNetworks++;
1429 }
1430 }
1431
1432 if (numOpenNetworks > 0) {
1433 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1434 /*
1435 * We've scanned continuously at least
1436 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1437 * probably does not have a remembered network in range,
1438 * since otherwise supplicant would have tried to
1439 * associate and thus resetting this counter.
1440 */
1441 setNotificationVisible(true, numOpenNetworks, false, 0);
1442 }
1443 return;
1444 }
1445 }
1446 }
1447
1448 // No open networks in range, remove the notification
1449 setNotificationVisible(false, 0, false, 0);
1450 }
1451
1452 /**
1453 * Clears variables related to tracking whether a notification has been
1454 * shown recently and clears the current notification.
1455 */
1456 private void resetNotification() {
1457 mNotificationRepeatTime = 0;
1458 mNumScansSinceNetworkStateChange = 0;
1459 setNotificationVisible(false, 0, false, 0);
1460 }
1461
1462 /**
1463 * Display or don't display a notification that there are open Wi-Fi networks.
1464 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1465 * @param numNetworks the number networks seen
1466 * @param force {@code true} to force notification to be shown/not-shown,
1467 * even if it is already shown/not-shown.
1468 * @param delay time in milliseconds after which the notification should be made
1469 * visible or invisible.
1470 */
1471 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1472 int delay) {
1473
1474 // Since we use auto cancel on the notification, when the
1475 // mNetworksAvailableNotificationShown is true, the notification may
1476 // have actually been canceled. However, when it is false we know
1477 // for sure that it is not being shown (it will not be shown any other
1478 // place than here)
1479
1480 // If it should be hidden and it is already hidden, then noop
1481 if (!visible && !mNotificationShown && !force) {
1482 return;
1483 }
1484
1485 NotificationManager notificationManager = (NotificationManager) mContext
1486 .getSystemService(Context.NOTIFICATION_SERVICE);
1487
1488 Message message;
1489 if (visible) {
1490
1491 // Not enough time has passed to show the notification again
1492 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1493 return;
1494 }
1495
1496 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001497 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001498 mNotification = new Notification();
1499 mNotification.when = 0;
1500 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1501 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1502 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1503 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1504 }
1505
1506 CharSequence title = mContext.getResources().getQuantityText(
1507 com.android.internal.R.plurals.wifi_available, numNetworks);
1508 CharSequence details = mContext.getResources().getQuantityText(
1509 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1510 mNotification.tickerText = title;
1511 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1512
1513 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1514
1515 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001516 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001517 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001518 }
1519
Irfan Sheriff0d255342010-07-28 09:35:20 -07001520 mNotificationShown = visible;
1521 }
1522
1523 private class NotificationEnabledSettingObserver extends ContentObserver {
1524
1525 public NotificationEnabledSettingObserver(Handler handler) {
1526 super(handler);
1527 }
1528
1529 public void register() {
1530 ContentResolver cr = mContext.getContentResolver();
1531 cr.registerContentObserver(Settings.Secure.getUriFor(
1532 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1533 mNotificationEnabled = getValue();
1534 }
1535
1536 @Override
1537 public void onChange(boolean selfChange) {
1538 super.onChange(selfChange);
1539
1540 mNotificationEnabled = getValue();
1541 resetNotification();
1542 }
1543
1544 private boolean getValue() {
1545 return Settings.Secure.getInt(mContext.getContentResolver(),
1546 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1547 }
1548 }
1549
1550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551}