blob: 55b7c9e5824f551f8c0c09211bfb051af5d0f690 [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);
884 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
885 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
886 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800887 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
889 mPluggedType = pluggedType;
890 return;
891 }
892 mPluggedType = pluggedType;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700893 } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
894 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
895 BluetoothA2dp.STATE_NOT_PLAYING);
896 mWifiStateMachine.setBluetoothScanMode(state == BluetoothA2dp.STATE_PLAYING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 } else {
898 return;
899 }
900
901 updateWifiState();
902 }
903
904 /**
905 * Determines whether the Wi-Fi chipset should stay awake or be put to
906 * sleep. Looks at the setting for the sleep policy and the current
907 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800908 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 * @see #shouldDeviceStayAwake(int, int)
910 */
911 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
912 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
913 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
914
915 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
916 // Never sleep
917 return true;
918 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
919 (pluggedType != 0)) {
920 // Never sleep while plugged, and we're plugged
921 return true;
922 } else {
923 // Default
924 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
925 }
926 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 /**
929 * Determine whether the bit value corresponding to {@code pluggedType} is set in
930 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
931 * of {@code 0} isn't really a plugged type, but rather an indication that the
932 * device isn't plugged in at all, there is no bit value corresponding to a
933 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700934 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 * @param stayAwakeConditions a bit string specifying which "plugged types" should
936 * keep the device (and hence Wi-Fi) awake.
937 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
938 * being made
939 * @return {@code true} if {@code pluggedType} indicates that the device is
940 * supposed to stay awake, {@code false} otherwise.
941 */
942 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
943 return (stayAwakeConditions & pluggedType) != 0;
944 }
945 };
946
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700947 private synchronized void reportStartWorkSource() {
948 mTmpWorkSource.clear();
949 if (mDeviceIdle) {
950 for (int i=0; i<mLocks.mList.size(); i++) {
951 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700952 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700953 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700954 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700955 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 private void updateWifiState() {
958 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700959 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 boolean lockHeld = mLocks.hasLocks();
961 int strongestLockMode;
962 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
963 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
964 if (mDeviceIdle && lockHeld) {
965 strongestLockMode = mLocks.getStrongestLockMode();
966 } else {
967 strongestLockMode = WifiManager.WIFI_MODE_FULL;
968 }
969
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700970 /* Disable tethering when airplane mode is enabled */
971 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700972 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700973 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700974
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700975 if (wifiShouldBeEnabled) {
976 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700977 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700978 mWifiStateMachine.setWifiEnabled(true);
979 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700980 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700981 mWifiStateMachine.setDriverStart(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700983 mWifiStateMachine.requestCmWakeLock();
984 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700986 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700987 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
989 }
990
991 private void registerForBroadcasts() {
992 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
994 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
995 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
996 intentFilter.addAction(ACTION_DEVICE_IDLE);
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700997 intentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 mContext.registerReceiver(mReceiver, intentFilter);
999 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 private boolean isAirplaneSensitive() {
1002 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1003 Settings.System.AIRPLANE_MODE_RADIOS);
1004 return airplaneModeRadios == null
1005 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1006 }
1007
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001008 private boolean isAirplaneToggleable() {
1009 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1010 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1011 return toggleableRadios != null
1012 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1013 }
1014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 /**
1016 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1017 * currently on.
1018 * @return {@code true} if airplane mode is on.
1019 */
1020 private boolean isAirplaneModeOn() {
1021 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1022 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1023 }
1024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 @Override
1026 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1027 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1028 != PackageManager.PERMISSION_GRANTED) {
1029 pw.println("Permission Denial: can't dump WifiService from from pid="
1030 + Binder.getCallingPid()
1031 + ", uid=" + Binder.getCallingUid());
1032 return;
1033 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001034 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 pw.println("Stay-awake conditions: " +
1036 Settings.System.getInt(mContext.getContentResolver(),
1037 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1038 pw.println();
1039
1040 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001041 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 pw.println();
1043 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001044 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 if (scanResults != null && scanResults.size() != 0) {
1046 pw.println(" BSSID Frequency RSSI Flags SSID");
1047 for (ScanResult r : scanResults) {
1048 pw.printf(" %17s %9d %5d %-16s %s%n",
1049 r.BSSID,
1050 r.frequency,
1051 r.level,
1052 r.capabilities,
1053 r.SSID == null ? "" : r.SSID);
1054 }
1055 }
1056 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001057 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1058 mScanLocksAcquired + " scan");
1059 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1060 mScanLocksReleased + " scan");
1061 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 pw.println("Locks held:");
1063 mLocks.dump(pw);
1064 }
1065
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001066 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001067 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1068 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
1070
1071 public void binderDied() {
1072 synchronized (mLocks) {
1073 releaseWifiLockLocked(mBinder);
1074 }
1075 }
1076
1077 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001078 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 }
1080 }
1081
1082 private class LockList {
1083 private List<WifiLock> mList;
1084
1085 private LockList() {
1086 mList = new ArrayList<WifiLock>();
1087 }
1088
1089 private synchronized boolean hasLocks() {
1090 return !mList.isEmpty();
1091 }
1092
1093 private synchronized int getStrongestLockMode() {
1094 if (mList.isEmpty()) {
1095 return WifiManager.WIFI_MODE_FULL;
1096 }
1097 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001098 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 return WifiManager.WIFI_MODE_FULL;
1100 }
1101 }
1102 return WifiManager.WIFI_MODE_SCAN_ONLY;
1103 }
1104
1105 private void addLock(WifiLock lock) {
1106 if (findLockByBinder(lock.mBinder) < 0) {
1107 mList.add(lock);
1108 }
1109 }
1110
1111 private WifiLock removeLock(IBinder binder) {
1112 int index = findLockByBinder(binder);
1113 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001114 WifiLock ret = mList.remove(index);
1115 ret.unlinkDeathRecipient();
1116 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 } else {
1118 return null;
1119 }
1120 }
1121
1122 private int findLockByBinder(IBinder binder) {
1123 int size = mList.size();
1124 for (int i = size - 1; i >= 0; i--)
1125 if (mList.get(i).mBinder == binder)
1126 return i;
1127 return -1;
1128 }
1129
1130 private void dump(PrintWriter pw) {
1131 for (WifiLock l : mList) {
1132 pw.print(" ");
1133 pw.println(l);
1134 }
1135 }
1136 }
1137
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001138 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001139 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001140 return;
1141 }
1142 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1143 pid, uid, null);
1144 }
1145
1146 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1148 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1149 return false;
1150 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001151 if (ws != null && ws.size() == 0) {
1152 ws = null;
1153 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001154 if (ws != null) {
1155 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1156 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001157 if (ws == null) {
1158 ws = new WorkSource(Binder.getCallingUid());
1159 }
1160 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 synchronized (mLocks) {
1162 return acquireWifiLockLocked(wifiLock);
1163 }
1164 }
1165
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001166 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1167 switch(wifiLock.mMode) {
1168 case WifiManager.WIFI_MODE_FULL:
1169 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1170 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001171 case WifiManager.WIFI_MODE_SCAN_ONLY:
1172 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1173 break;
1174 }
1175 }
1176
1177 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1178 switch(wifiLock.mMode) {
1179 case WifiManager.WIFI_MODE_FULL:
1180 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1181 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001182 case WifiManager.WIFI_MODE_SCAN_ONLY:
1183 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1184 break;
1185 }
1186 }
1187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001189 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001192
The Android Open Source Project10592532009-03-18 17:39:46 -07001193 long ident = Binder.clearCallingIdentity();
1194 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001195 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001196 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001197 case WifiManager.WIFI_MODE_FULL:
1198 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001199 break;
1200 case WifiManager.WIFI_MODE_SCAN_ONLY:
1201 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001202 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001203 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001204
1205 // Be aggressive about adding new locks into the accounted state...
1206 // we want to over-report rather than under-report.
1207 reportStartWorkSource();
1208
1209 updateWifiState();
1210 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001211 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001212 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001213 } finally {
1214 Binder.restoreCallingIdentity(ident);
1215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
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
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001261 long ident = Binder.clearCallingIdentity();
1262 try {
1263 if (hadLock) {
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 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001273 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001274
1275 // TODO - should this only happen if you hadLock?
1276 updateWifiState();
1277
1278 } catch (RemoteException e) {
1279 } finally {
1280 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001281 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001282
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001283 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001285
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001286 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001287 implements IBinder.DeathRecipient {
1288 String mTag;
1289 int mMode;
1290 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001291 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001292
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001293 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001294 super();
1295 mTag = tag;
1296 mMode = mode;
1297 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001298 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001299 try {
1300 mBinder.linkToDeath(this, 0);
1301 } catch (RemoteException e) {
1302 binderDied();
1303 }
1304 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001305
1306 void unlinkDeathRecipient() {
1307 mBinder.unlinkToDeath(this, 0);
1308 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001309 }
1310
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001311 private class Multicaster extends DeathRecipient {
1312 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001313 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001314 }
1315
1316 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001317 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001318 synchronized (mMulticasters) {
1319 int i = mMulticasters.indexOf(this);
1320 if (i != -1) {
1321 removeMulticasterLocked(i, mMode);
1322 }
1323 }
1324 }
1325
1326 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001327 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001328 }
1329
1330 public int getUid() {
1331 return mMode;
1332 }
1333 }
1334
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001335 public void initializeMulticastFiltering() {
1336 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001337
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001338 synchronized (mMulticasters) {
1339 // if anybody had requested filters be off, leave off
1340 if (mMulticasters.size() != 0) {
1341 return;
1342 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001343 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001344 }
1345 }
1346 }
1347
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001348 public void acquireMulticastLock(IBinder binder, String tag) {
1349 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001350
1351 synchronized (mMulticasters) {
1352 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001353 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001354 // Note that we could call stopPacketFiltering only when
1355 // our new size == 1 (first call), but this function won't
1356 // be called often and by making the stopPacket call each
1357 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001358 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001359 }
1360
1361 int uid = Binder.getCallingUid();
1362 Long ident = Binder.clearCallingIdentity();
1363 try {
1364 mBatteryStats.noteWifiMulticastEnabled(uid);
1365 } catch (RemoteException e) {
1366 } finally {
1367 Binder.restoreCallingIdentity(ident);
1368 }
1369 }
1370
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001371 public void releaseMulticastLock() {
1372 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001373
1374 int uid = Binder.getCallingUid();
1375 synchronized (mMulticasters) {
1376 mMulticastDisabled++;
1377 int size = mMulticasters.size();
1378 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001379 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001380 if ((m != null) && (m.getUid() == uid)) {
1381 removeMulticasterLocked(i, uid);
1382 }
1383 }
1384 }
1385 }
1386
1387 private void removeMulticasterLocked(int i, int uid)
1388 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001389 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001390
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001391 if (removed != null) {
1392 removed.unlinkDeathRecipient();
1393 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001394 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001395 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001396 }
1397
1398 Long ident = Binder.clearCallingIdentity();
1399 try {
1400 mBatteryStats.noteWifiMulticastDisabled(uid);
1401 } catch (RemoteException e) {
1402 } finally {
1403 Binder.restoreCallingIdentity(ident);
1404 }
1405 }
1406
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001407 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001408 enforceAccessPermission();
1409
1410 synchronized (mMulticasters) {
1411 return (mMulticasters.size() > 0);
1412 }
1413 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001414
1415 private void checkAndSetNotification() {
1416 // If we shouldn't place a notification on available networks, then
1417 // don't bother doing any of the following
1418 if (!mNotificationEnabled) return;
1419
1420 State state = mNetworkInfo.getState();
1421 if ((state == NetworkInfo.State.DISCONNECTED)
1422 || (state == NetworkInfo.State.UNKNOWN)) {
1423 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001424 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001425 if (scanResults != null) {
1426 int numOpenNetworks = 0;
1427 for (int i = scanResults.size() - 1; i >= 0; i--) {
1428 ScanResult scanResult = scanResults.get(i);
1429
1430 if (TextUtils.isEmpty(scanResult.capabilities)) {
1431 numOpenNetworks++;
1432 }
1433 }
1434
1435 if (numOpenNetworks > 0) {
1436 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1437 /*
1438 * We've scanned continuously at least
1439 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1440 * probably does not have a remembered network in range,
1441 * since otherwise supplicant would have tried to
1442 * associate and thus resetting this counter.
1443 */
1444 setNotificationVisible(true, numOpenNetworks, false, 0);
1445 }
1446 return;
1447 }
1448 }
1449 }
1450
1451 // No open networks in range, remove the notification
1452 setNotificationVisible(false, 0, false, 0);
1453 }
1454
1455 /**
1456 * Clears variables related to tracking whether a notification has been
1457 * shown recently and clears the current notification.
1458 */
1459 private void resetNotification() {
1460 mNotificationRepeatTime = 0;
1461 mNumScansSinceNetworkStateChange = 0;
1462 setNotificationVisible(false, 0, false, 0);
1463 }
1464
1465 /**
1466 * Display or don't display a notification that there are open Wi-Fi networks.
1467 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1468 * @param numNetworks the number networks seen
1469 * @param force {@code true} to force notification to be shown/not-shown,
1470 * even if it is already shown/not-shown.
1471 * @param delay time in milliseconds after which the notification should be made
1472 * visible or invisible.
1473 */
1474 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1475 int delay) {
1476
1477 // Since we use auto cancel on the notification, when the
1478 // mNetworksAvailableNotificationShown is true, the notification may
1479 // have actually been canceled. However, when it is false we know
1480 // for sure that it is not being shown (it will not be shown any other
1481 // place than here)
1482
1483 // If it should be hidden and it is already hidden, then noop
1484 if (!visible && !mNotificationShown && !force) {
1485 return;
1486 }
1487
1488 NotificationManager notificationManager = (NotificationManager) mContext
1489 .getSystemService(Context.NOTIFICATION_SERVICE);
1490
1491 Message message;
1492 if (visible) {
1493
1494 // Not enough time has passed to show the notification again
1495 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1496 return;
1497 }
1498
1499 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001500 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001501 mNotification = new Notification();
1502 mNotification.when = 0;
1503 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1504 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1505 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1506 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1507 }
1508
1509 CharSequence title = mContext.getResources().getQuantityText(
1510 com.android.internal.R.plurals.wifi_available, numNetworks);
1511 CharSequence details = mContext.getResources().getQuantityText(
1512 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1513 mNotification.tickerText = title;
1514 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1515
1516 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1517
1518 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001519 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001520 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001521 }
1522
Irfan Sheriff0d255342010-07-28 09:35:20 -07001523 mNotificationShown = visible;
1524 }
1525
1526 private class NotificationEnabledSettingObserver extends ContentObserver {
1527
1528 public NotificationEnabledSettingObserver(Handler handler) {
1529 super(handler);
1530 }
1531
1532 public void register() {
1533 ContentResolver cr = mContext.getContentResolver();
1534 cr.registerContentObserver(Settings.Secure.getUriFor(
1535 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1536 mNotificationEnabled = getValue();
1537 }
1538
1539 @Override
1540 public void onChange(boolean selfChange) {
1541 super.onChange(selfChange);
1542
1543 mNotificationEnabled = getValue();
1544 resetNotification();
1545 }
1546
1547 private boolean getValue() {
1548 return Settings.Secure.getInt(mContext.getContentResolver(),
1549 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1550 }
1551 }
1552
1553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554}