blob: b43b33e4f9ce42d44ec8f45d809a5ce6e153defc [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 Ganesh084c6652009-12-07 10:58:18 -080024import android.bluetooth.BluetoothDevice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.BroadcastReceiver;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070031import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.net.wifi.IWifiManager;
33import android.net.wifi.WifiInfo;
34import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070035import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.wifi.ScanResult;
37import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070038import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080039import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080040import android.net.ConnectivityManager;
41import android.net.InterfaceConfiguration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070043import android.net.NetworkInfo;
44import android.net.NetworkInfo.State;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070046import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.HandlerThread;
48import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080049import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070050import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070052import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070054import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080055import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
57import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080059import java.util.Set;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070060import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.io.FileDescriptor;
62import java.io.PrintWriter;
63
The Android Open Source Project10592532009-03-18 17:39:46 -070064import com.android.internal.app.IBatteryStats;
The Android Open Source Project10592532009-03-18 17:39:46 -070065import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080066import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068/**
69 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070070 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 *
72 * @hide
73 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070074//TODO: Clean up multiple locks and implement WifiService
75// as a SM to track soft AP/client/adhoc bring up based
76// on device idle state, airplane mode and boot.
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078public class WifiService extends IWifiManager.Stub {
79 private static final String TAG = "WifiService";
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070080 private static final boolean DBG = true;
81
Irfan Sheriff0d255342010-07-28 09:35:20 -070082 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
84 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
86 private AlarmManager mAlarmManager;
87 private PendingIntent mIdleIntent;
88 private static final int IDLE_REQUEST = 0;
89 private boolean mScreenOff;
90 private boolean mDeviceIdle;
91 private int mPluggedType;
92
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070093 // true if the user enabled Wifi while in airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070094 private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -070097 // some wifi lock statistics
98 private int mFullLocksAcquired;
99 private int mFullLocksReleased;
100 private int mScanLocksAcquired;
101 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700102
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700103 private final List<Multicaster> mMulticasters =
104 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700105 private int mMulticastEnabled;
106 private int mMulticastDisabled;
107
The Android Open Source Project10592532009-03-18 17:39:46 -0700108 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800109
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800110 ConnectivityManager mCm;
111 private String[] mWifiRegexs;
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800114 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
115 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 * the approximate point at which the battery drain caused by Wi-Fi
117 * being enabled but not active exceeds the battery drain caused by
118 * re-establishing a connection to the mobile data network.
119 */
120 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 /**
123 * Number of allowed radio frequency channels in various regulatory domains.
124 * This list is sufficient for 802.11b/g networks (2.4GHz range).
125 */
126 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
127
128 private static final String ACTION_DEVICE_IDLE =
129 "com.android.server.WifiManager.action.DEVICE_IDLE";
130
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700131 private boolean mIsReceiverRegistered = false;
132
Irfan Sheriff0d255342010-07-28 09:35:20 -0700133
134 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
135
136 // Variables relating to the 'available networks' notification
137 /**
138 * The icon to show in the 'available networks' notification. This will also
139 * be the ID of the Notification given to the NotificationManager.
140 */
141 private static final int ICON_NETWORKS_AVAILABLE =
142 com.android.internal.R.drawable.stat_notify_wifi_in_range;
143 /**
144 * When a notification is shown, we wait this amount before possibly showing it again.
145 */
146 private final long NOTIFICATION_REPEAT_DELAY_MS;
147 /**
148 * Whether the user has set the setting to show the 'available networks' notification.
149 */
150 private boolean mNotificationEnabled;
151 /**
152 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
153 */
154 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
155 /**
156 * The {@link System#currentTimeMillis()} must be at least this value for us
157 * to show the notification again.
158 */
159 private long mNotificationRepeatTime;
160 /**
161 * The Notification object given to the NotificationManager.
162 */
163 private Notification mNotification;
164 /**
165 * Whether the notification is being shown, as set by us. That is, if the
166 * user cancels the notification, we will not receive the callback so this
167 * will still be true. We only guarantee if this is false, then the
168 * notification is not showing.
169 */
170 private boolean mNotificationShown;
171 /**
172 * The number of continuous scans that must occur before consider the
173 * supplicant in a scanning state. This allows supplicant to associate with
174 * remembered networks that are in the scan results.
175 */
176 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
177 /**
178 * The number of scans since the last network state change. When this
179 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
180 * supplicant to actually be scanning. When the network state changes to
181 * something other than scanning, we reset this to 0.
182 */
183 private int mNumScansSinceNetworkStateChange;
184
185
186 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700188 mWifiStateMachine = new WifiStateMachine(mContext);
189 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700190 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
193 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
194 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
195
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700196 HandlerThread wifiThread = new HandlerThread("WifiService");
197 wifiThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 mContext.registerReceiver(
200 new BroadcastReceiver() {
201 @Override
202 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700203 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700204 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700205 // on airplane disable, restore Wifi if the saved state indicates so
206 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
207 persistWifiEnabled(true);
208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 updateWifiState();
210 }
211 },
212 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
213
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800214 mContext.registerReceiver(
215 new BroadcastReceiver() {
216 @Override
217 public void onReceive(Context context, Intent intent) {
218
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700219 ArrayList<String> available = intent.getStringArrayListExtra(
220 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
221 ArrayList<String> active = intent.getStringArrayListExtra(
222 ConnectivityManager.EXTRA_ACTIVE_TETHER);
223 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800224
225 }
226 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700227
228 IntentFilter filter = new IntentFilter();
229 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
230 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
231 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
232
233 mContext.registerReceiver(
234 new BroadcastReceiver() {
235 @Override
236 public void onReceive(Context context, Intent intent) {
237 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
238 // reset & clear notification on any wifi state change
239 resetNotification();
240 } else if (intent.getAction().equals(
241 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
242 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
243 WifiManager.EXTRA_NETWORK_INFO);
244 // reset & clear notification on a network connect & disconnect
245 switch(mNetworkInfo.getDetailedState()) {
246 case CONNECTED:
247 case DISCONNECTED:
248 resetNotification();
249 break;
250 }
251 } else if (intent.getAction().equals(
252 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
253 checkAndSetNotification();
254 }
255 }
256 }, filter);
257
258 // Setting is in seconds
259 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
260 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
261 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
262 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800263 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800264
Irfan Sheriff7b009782010-03-11 16:37:45 -0800265 /**
266 * Check if Wi-Fi needs to be enabled and start
267 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700268 *
269 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800270 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700271 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700272 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700273 boolean wifiEnabled = !isAirplaneModeOn()
274 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800275 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
276 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700277 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800278 }
279
280 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
281
282 boolean wifiTethered = false;
283 boolean wifiAvailable = false;
284
285 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
286 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
287
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700288 if (mCm == null) {
289 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
290 }
291
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800292 mWifiRegexs = mCm.getTetherableWifiRegexs();
293
294 for (String intf : available) {
295 for (String regex : mWifiRegexs) {
296 if (intf.matches(regex)) {
297
298 InterfaceConfiguration ifcg = null;
299 try {
300 ifcg = service.getInterfaceConfig(intf);
301 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700302 /* IP/netmask: 192.168.43.1/255.255.255.0 */
303 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800304 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
305 ifcg.interfaceFlags = "up";
306
307 service.setInterfaceConfig(intf, ifcg);
308 }
309 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800310 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700311 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800312 return;
313 }
314
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800315 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700316 Slog.e(TAG, "Error tethering on " + intf);
317 setWifiApEnabled(null, false);
318 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800319 }
320 break;
321 }
322 }
323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 }
325
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700326 private boolean testAndClearWifiSavedState() {
327 final ContentResolver cr = mContext.getContentResolver();
328 int wifiSavedState = 0;
329 try {
330 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
331 if(wifiSavedState == 1)
332 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
333 } catch (Settings.SettingNotFoundException e) {
334 ;
335 }
336 return (wifiSavedState == 1);
337 }
338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 private boolean getPersistedWifiEnabled() {
340 final ContentResolver cr = mContext.getContentResolver();
341 try {
342 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
343 } catch (Settings.SettingNotFoundException e) {
344 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
345 return false;
346 }
347 }
348
349 private void persistWifiEnabled(boolean enabled) {
350 final ContentResolver cr = mContext.getContentResolver();
351 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
352 }
353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 /**
355 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700356 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 */
358 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700359 enforceAccessPermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700360 return mWifiStateMachine.pingSupplicant();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 }
362
363 /**
364 * see {@link android.net.wifi.WifiManager#startScan()}
365 * @return {@code true} if the operation succeeds
366 */
Mike Lockwooda5ec95c2009-07-08 17:11:17 -0400367 public boolean startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700369 return mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 }
371
372 private void enforceAccessPermission() {
373 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
374 "WifiService");
375 }
376
377 private void enforceChangePermission() {
378 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
379 "WifiService");
380
381 }
382
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700383 private void enforceMulticastChangePermission() {
384 mContext.enforceCallingOrSelfPermission(
385 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
386 "WifiService");
387 }
388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700390 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
391 * @param enable {@code true} to enable, {@code false} to disable.
392 * @return {@code true} if the enable/disable operation was
393 * started or is already in the queue.
394 */
395 public synchronized boolean setWifiEnabled(boolean enable) {
396 enforceChangePermission();
397
398 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700399 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700400 }
401
402 // set a flag if the user is enabling Wifi while in airplane mode
403 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
404 mAirplaneModeOverwridden.set(true);
405 }
406
Irfan Sheriff0d255342010-07-28 09:35:20 -0700407 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700408 persistWifiEnabled(enable);
409
410 if (enable) {
411 if (!mIsReceiverRegistered) {
412 registerForBroadcasts();
413 mIsReceiverRegistered = true;
414 }
415 } else if (mIsReceiverRegistered){
416 mContext.unregisterReceiver(mReceiver);
417 mIsReceiverRegistered = false;
418 }
419
420 return true;
421 }
422
423 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 * see {@link WifiManager#getWifiState()}
425 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
426 * {@link WifiManager#WIFI_STATE_DISABLING},
427 * {@link WifiManager#WIFI_STATE_ENABLED},
428 * {@link WifiManager#WIFI_STATE_ENABLING},
429 * {@link WifiManager#WIFI_STATE_UNKNOWN}
430 */
431 public int getWifiEnabledState() {
432 enforceAccessPermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700433 return mWifiStateMachine.getWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 }
435
436 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700437 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800438 * @param wifiConfig SSID, security and channel details as
439 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700440 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800441 * @return {@code true} if the start operation was
442 * started or is already in the queue.
443 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700444 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800445 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800446
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700447 if (enabled) {
448 /* Use default config if there is no existing config */
449 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
450 wifiConfig = new WifiConfiguration();
451 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
452 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
453 }
454 setWifiApConfiguration(wifiConfig);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800455 }
456
Irfan Sheriff0d255342010-07-28 09:35:20 -0700457 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700458
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800459 return true;
460 }
461
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700462 /**
463 * see {@link WifiManager#getWifiApState()}
464 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
465 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
466 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
467 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
468 * {@link WifiManager#WIFI_AP_STATE_FAILED}
469 */
470 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700471 enforceAccessPermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700472 return mWifiStateMachine.getWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700473 }
474
475 /**
476 * see {@link WifiManager#getWifiApConfiguration()}
477 * @return soft access point configuration
478 */
479 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800480 final ContentResolver cr = mContext.getContentResolver();
481 WifiConfiguration wifiConfig = new WifiConfiguration();
482 int authType;
483 try {
484 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
485 if (wifiConfig.SSID == null)
486 return null;
487 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
488 wifiConfig.allowedKeyManagement.set(authType);
489 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
490 return wifiConfig;
491 } catch (Settings.SettingNotFoundException e) {
492 Slog.e(TAG,"AP settings not found, returning");
493 return null;
494 }
495 }
496
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700497 /**
498 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
499 * @param wifiConfig WifiConfiguration details for soft access point
500 */
501 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700502 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800503 final ContentResolver cr = mContext.getContentResolver();
504 boolean isWpa;
505 if (wifiConfig == null)
506 return;
507 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
508 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
509 Settings.Secure.putInt(cr,
510 Settings.Secure.WIFI_AP_SECURITY,
511 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
512 if (isWpa)
513 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
514 }
515
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800516 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700517 * see {@link android.net.wifi.WifiManager#disconnect()}
518 * @return {@code true} if the operation succeeds
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800519 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700520 public boolean disconnect() {
521 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700522 return mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800523 }
524
525 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700526 * see {@link android.net.wifi.WifiManager#reconnect()}
527 * @return {@code true} if the operation succeeds
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800528 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700529 public boolean reconnect() {
530 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700531 return mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800532 }
533
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700534 /**
535 * see {@link android.net.wifi.WifiManager#reassociate()}
536 * @return {@code true} if the operation succeeds
537 */
538 public boolean reassociate() {
539 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700540 return mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800541 }
542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 /**
544 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
545 * @return the list of configured networks
546 */
547 public List<WifiConfiguration> getConfiguredNetworks() {
548 enforceAccessPermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700549 return mWifiStateMachine.getConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800550 }
551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 /**
553 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
554 * @return the supplicant-assigned identifier for the new or updated
555 * network if the operation succeeds, or {@code -1} if it fails
556 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800557 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700559 return mWifiStateMachine.addOrUpdateNetwork(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 }
561
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700562 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
564 * @param netId the integer that identifies the network configuration
565 * to the supplicant
566 * @return {@code true} if the operation succeeded
567 */
568 public boolean removeNetwork(int netId) {
569 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700570 return mWifiStateMachine.removeNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 }
572
573 /**
574 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
575 * @param netId the integer that identifies the network configuration
576 * to the supplicant
577 * @param disableOthers if true, disable all other networks.
578 * @return {@code true} if the operation succeeded
579 */
580 public boolean enableNetwork(int netId, boolean disableOthers) {
581 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700582 return mWifiStateMachine.enableNetwork(netId, disableOthers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 }
584
585 /**
586 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
587 * @param netId the integer that identifies the network configuration
588 * to the supplicant
589 * @return {@code true} if the operation succeeded
590 */
591 public boolean disableNetwork(int netId) {
592 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700593 return mWifiStateMachine.disableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 }
595
596 /**
597 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
598 * @return the Wi-Fi information, contained in {@link WifiInfo}.
599 */
600 public WifiInfo getConnectionInfo() {
601 enforceAccessPermission();
602 /*
603 * Make sure we have the latest information, by sending
604 * a status request to the supplicant.
605 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700606 return mWifiStateMachine.requestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 }
608
609 /**
610 * Return the results of the most recent access point scan, in the form of
611 * a list of {@link ScanResult} objects.
612 * @return the list of results
613 */
614 public List<ScanResult> getScanResults() {
615 enforceAccessPermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700616 return mWifiStateMachine.getScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 }
618
619 /**
620 * Tell the supplicant to persist the current list of configured networks.
621 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700622 *
623 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 */
625 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700626 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700628 return mWifiStateMachine.saveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 }
630
631 /**
632 * Set the number of radio frequency channels that are allowed to be used
633 * in the current regulatory domain. This method should be used only
634 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700635 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 * persisted as a Secure setting.
637 * @param numChannels the number of allowed channels. Must be greater than 0
638 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700639 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
641 * {@code numChannels} is outside the valid range.
642 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700643 public synchronized boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800644 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700645 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -0700647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 /*
649 * Validate the argument. We'd like to let the Wi-Fi driver do this,
650 * but if Wi-Fi isn't currently enabled, that's not possible, and
651 * we want to persist the setting anyway,so that it will take
652 * effect when Wi-Fi does become enabled.
653 */
654 boolean found = false;
655 for (int validChan : sValidRegulatoryChannelCounts) {
656 if (validChan == numChannels) {
657 found = true;
658 break;
659 }
660 }
661 if (!found) {
662 return false;
663 }
664
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700665 if (persist) {
666 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -0700667 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
668 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700669 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700670
Irfan Sheriff0d255342010-07-28 09:35:20 -0700671 mWifiStateMachine.setNumAllowedChannels(numChannels);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700672
673 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 }
675
676 /**
677 * Return the number of frequency channels that are allowed
678 * to be used in the current regulatory domain.
679 * @return the number of allowed channels, or {@code -1} if an error occurs
680 */
681 public int getNumAllowedChannels() {
682 int numChannels;
683
684 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800685
686 /*
687 * If we can't get the value from the driver (e.g., because
688 * Wi-Fi is not currently enabled), get the value from
689 * Settings.
690 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700691 numChannels = mWifiStateMachine.getNumAllowedChannels();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800692 if (numChannels < 0) {
693 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
694 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
695 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 }
697 return numChannels;
698 }
699
700 /**
701 * Return the list of valid values for the number of allowed radio channels
702 * for various regulatory domains.
703 * @return the list of channel counts
704 */
705 public int[] getValidChannelCounts() {
706 enforceAccessPermission();
707 return sValidRegulatoryChannelCounts;
708 }
709
710 /**
711 * Return the DHCP-assigned addresses from the last successful DHCP request,
712 * if any.
713 * @return the DHCP information
714 */
715 public DhcpInfo getDhcpInfo() {
716 enforceAccessPermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700717 return mWifiStateMachine.getDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 }
719
Irfan Sheriff0d255342010-07-28 09:35:20 -0700720 /**
721 * see {@link android.net.wifi.WifiManager#startWifi}
722 *
723 */
724 public void startWifi() {
725 enforceChangePermission();
726 /* TODO: may be add permissions for access only to connectivity service
727 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
728 * of WifiLock & device idle status unless wifi enabled status is toggled
729 */
730
731 mWifiStateMachine.setDriverStart(true);
732 mWifiStateMachine.reconnectCommand();
733 }
734
735 /**
736 * see {@link android.net.wifi.WifiManager#stopWifi}
737 *
738 */
739 public void stopWifi() {
740 enforceChangePermission();
741 /* TODO: may be add permissions for access only to connectivity service
742 * TODO: if a stop is issued, wifi is brought up only by startWifi
743 * unless wifi enabled status is toggled
744 */
745 mWifiStateMachine.setDriverStart(false);
746 }
747
748
749 /**
750 * see {@link android.net.wifi.WifiManager#addToBlacklist}
751 *
752 */
753 public void addToBlacklist(String bssid) {
754 enforceChangePermission();
755
756 mWifiStateMachine.addToBlacklist(bssid);
757 }
758
759 /**
760 * see {@link android.net.wifi.WifiManager#clearBlacklist}
761 *
762 */
763 public void clearBlacklist() {
764 enforceChangePermission();
765
766 mWifiStateMachine.clearBlacklist();
767 }
768
769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
771 @Override
772 public void onReceive(Context context, Intent intent) {
773 String action = intent.getAction();
774
Doug Zongker43866e02010-01-07 12:09:54 -0800775 long idleMillis =
776 Settings.Secure.getLong(mContext.getContentResolver(),
777 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800779 Settings.System.getInt(mContext.getContentResolver(),
780 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800782 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 mAlarmManager.cancel(mIdleIntent);
784 mDeviceIdle = false;
785 mScreenOff = false;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700786 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800788 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700790 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 /*
792 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
793 * AND the "stay on while plugged in" setting doesn't match the
794 * current power conditions (i.e, not plugged in, plugged in to USB,
795 * or plugged in to AC).
796 */
797 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700798 WifiInfo info = mWifiStateMachine.requestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700799 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700800 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700801 // we don't have time to track down for this release. Delay instead,
802 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700803 // TODO - fix the race conditions and switch back to the immediate turn-off
804 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -0800805 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700806 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
807 // // do not keep Wifi awake when screen is off if Wifi is not associated
808 // mDeviceIdle = true;
809 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400810 } else {
811 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800812 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400813 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
816 /* we can return now -- there's nothing to do until we get the idle intent back */
817 return;
818 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800819 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 mDeviceIdle = true;
821 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
822 /*
823 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
824 * AND we are transitioning from a state in which the device was supposed
825 * to stay awake to a state in which it is not supposed to stay awake.
826 * If "stay awake" state is not changing, we do nothing, to avoid resetting
827 * the already-set timer.
828 */
829 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800830 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
832 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
833 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800834 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
836 mPluggedType = pluggedType;
837 return;
838 }
839 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -0700840 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800841 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
842 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
843 boolean isBluetoothPlaying = false;
844 for (BluetoothDevice sink : sinks) {
845 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
846 isBluetoothPlaying = true;
847 }
848 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700849 mWifiStateMachine.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 } else {
852 return;
853 }
854
855 updateWifiState();
856 }
857
858 /**
859 * Determines whether the Wi-Fi chipset should stay awake or be put to
860 * sleep. Looks at the setting for the sleep policy and the current
861 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800862 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 * @see #shouldDeviceStayAwake(int, int)
864 */
865 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
866 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
867 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
868
869 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
870 // Never sleep
871 return true;
872 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
873 (pluggedType != 0)) {
874 // Never sleep while plugged, and we're plugged
875 return true;
876 } else {
877 // Default
878 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
879 }
880 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 /**
883 * Determine whether the bit value corresponding to {@code pluggedType} is set in
884 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
885 * of {@code 0} isn't really a plugged type, but rather an indication that the
886 * device isn't plugged in at all, there is no bit value corresponding to a
887 * {@code pluggedType} value of {@code 0}. That is why we shift by
888 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
889 * @param stayAwakeConditions a bit string specifying which "plugged types" should
890 * keep the device (and hence Wi-Fi) awake.
891 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
892 * being made
893 * @return {@code true} if {@code pluggedType} indicates that the device is
894 * supposed to stay awake, {@code false} otherwise.
895 */
896 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
897 return (stayAwakeConditions & pluggedType) != 0;
898 }
899 };
900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 private void updateWifiState() {
902 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700903 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 boolean lockHeld = mLocks.hasLocks();
905 int strongestLockMode;
906 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
907 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
908 if (mDeviceIdle && lockHeld) {
909 strongestLockMode = mLocks.getStrongestLockMode();
910 } else {
911 strongestLockMode = WifiManager.WIFI_MODE_FULL;
912 }
913
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700914 /* Disable tethering when airplane mode is enabled */
915 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700916 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700917 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700918
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700919 if (wifiShouldBeEnabled) {
920 if (wifiShouldBeStarted) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700921 mWifiStateMachine.setWifiEnabled(true);
922 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700923 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700924 mWifiStateMachine.setDriverStart(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700926 mWifiStateMachine.requestCmWakeLock();
927 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700929 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700930 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
932 }
933
934 private void registerForBroadcasts() {
935 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
937 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
938 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
939 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -0700940 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 mContext.registerReceiver(mReceiver, intentFilter);
942 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 private boolean isAirplaneSensitive() {
945 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
946 Settings.System.AIRPLANE_MODE_RADIOS);
947 return airplaneModeRadios == null
948 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
949 }
950
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700951 private boolean isAirplaneToggleable() {
952 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
953 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
954 return toggleableRadios != null
955 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
956 }
957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 /**
959 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
960 * currently on.
961 * @return {@code true} if airplane mode is on.
962 */
963 private boolean isAirplaneModeOn() {
964 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
965 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
966 }
967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 @Override
969 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
970 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
971 != PackageManager.PERMISSION_GRANTED) {
972 pw.println("Permission Denial: can't dump WifiService from from pid="
973 + Binder.getCallingPid()
974 + ", uid=" + Binder.getCallingUid());
975 return;
976 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700977 pw.println("Wi-Fi is " + mWifiStateMachine.getWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 pw.println("Stay-awake conditions: " +
979 Settings.System.getInt(mContext.getContentResolver(),
980 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
981 pw.println();
982
983 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -0700984 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 pw.println();
986 pw.println("Latest scan results:");
Irfan Sheriff0d255342010-07-28 09:35:20 -0700987 List<ScanResult> scanResults = mWifiStateMachine.getScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 if (scanResults != null && scanResults.size() != 0) {
989 pw.println(" BSSID Frequency RSSI Flags SSID");
990 for (ScanResult r : scanResults) {
991 pw.printf(" %17s %9d %5d %-16s %s%n",
992 r.BSSID,
993 r.frequency,
994 r.level,
995 r.capabilities,
996 r.SSID == null ? "" : r.SSID);
997 }
998 }
999 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001000 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1001 mScanLocksAcquired + " scan");
1002 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1003 mScanLocksReleased + " scan");
1004 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 pw.println("Locks held:");
1006 mLocks.dump(pw);
1007 }
1008
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001009 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001011 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
1013
1014 public void binderDied() {
1015 synchronized (mLocks) {
1016 releaseWifiLockLocked(mBinder);
1017 }
1018 }
1019
1020 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001021 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 }
1023 }
1024
1025 private class LockList {
1026 private List<WifiLock> mList;
1027
1028 private LockList() {
1029 mList = new ArrayList<WifiLock>();
1030 }
1031
1032 private synchronized boolean hasLocks() {
1033 return !mList.isEmpty();
1034 }
1035
1036 private synchronized int getStrongestLockMode() {
1037 if (mList.isEmpty()) {
1038 return WifiManager.WIFI_MODE_FULL;
1039 }
1040 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001041 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 return WifiManager.WIFI_MODE_FULL;
1043 }
1044 }
1045 return WifiManager.WIFI_MODE_SCAN_ONLY;
1046 }
1047
1048 private void addLock(WifiLock lock) {
1049 if (findLockByBinder(lock.mBinder) < 0) {
1050 mList.add(lock);
1051 }
1052 }
1053
1054 private WifiLock removeLock(IBinder binder) {
1055 int index = findLockByBinder(binder);
1056 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001057 WifiLock ret = mList.remove(index);
1058 ret.unlinkDeathRecipient();
1059 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 } else {
1061 return null;
1062 }
1063 }
1064
1065 private int findLockByBinder(IBinder binder) {
1066 int size = mList.size();
1067 for (int i = size - 1; i >= 0; i--)
1068 if (mList.get(i).mBinder == binder)
1069 return i;
1070 return -1;
1071 }
1072
1073 private void dump(PrintWriter pw) {
1074 for (WifiLock l : mList) {
1075 pw.print(" ");
1076 pw.println(l);
1077 }
1078 }
1079 }
1080
1081 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1082 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1083 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1084 return false;
1085 }
1086 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1087 synchronized (mLocks) {
1088 return acquireWifiLockLocked(wifiLock);
1089 }
1090 }
1091
1092 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001093 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001096
The Android Open Source Project10592532009-03-18 17:39:46 -07001097 int uid = Binder.getCallingUid();
1098 long ident = Binder.clearCallingIdentity();
1099 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001100 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001101 case WifiManager.WIFI_MODE_FULL:
1102 ++mFullLocksAcquired;
1103 mBatteryStats.noteFullWifiLockAcquired(uid);
1104 break;
1105 case WifiManager.WIFI_MODE_SCAN_ONLY:
1106 ++mScanLocksAcquired;
1107 mBatteryStats.noteScanWifiLockAcquired(uid);
1108 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001109 }
1110 } catch (RemoteException e) {
1111 } finally {
1112 Binder.restoreCallingIdentity(ident);
1113 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 updateWifiState();
1116 return true;
1117 }
1118
1119 public boolean releaseWifiLock(IBinder lock) {
1120 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1121 synchronized (mLocks) {
1122 return releaseWifiLockLocked(lock);
1123 }
1124 }
1125
1126 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001127 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001128
The Android Open Source Project10592532009-03-18 17:39:46 -07001129 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001130
Joe Onorato8a9b2202010-02-26 18:56:32 -08001131 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001132
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001133 hadLock = (wifiLock != null);
1134
1135 if (hadLock) {
1136 int uid = Binder.getCallingUid();
1137 long ident = Binder.clearCallingIdentity();
1138 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001139 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001140 case WifiManager.WIFI_MODE_FULL:
1141 ++mFullLocksReleased;
1142 mBatteryStats.noteFullWifiLockReleased(uid);
1143 break;
1144 case WifiManager.WIFI_MODE_SCAN_ONLY:
1145 ++mScanLocksReleased;
1146 mBatteryStats.noteScanWifiLockReleased(uid);
1147 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001148 }
1149 } catch (RemoteException e) {
1150 } finally {
1151 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001152 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001153 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001154 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001156 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001158
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001159 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001160 implements IBinder.DeathRecipient {
1161 String mTag;
1162 int mMode;
1163 IBinder mBinder;
1164
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001165 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001166 super();
1167 mTag = tag;
1168 mMode = mode;
1169 mBinder = binder;
1170 try {
1171 mBinder.linkToDeath(this, 0);
1172 } catch (RemoteException e) {
1173 binderDied();
1174 }
1175 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001176
1177 void unlinkDeathRecipient() {
1178 mBinder.unlinkToDeath(this, 0);
1179 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001180 }
1181
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001182 private class Multicaster extends DeathRecipient {
1183 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001184 super(Binder.getCallingUid(), tag, binder);
1185 }
1186
1187 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001188 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001189 synchronized (mMulticasters) {
1190 int i = mMulticasters.indexOf(this);
1191 if (i != -1) {
1192 removeMulticasterLocked(i, mMode);
1193 }
1194 }
1195 }
1196
1197 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001198 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001199 }
1200
1201 public int getUid() {
1202 return mMode;
1203 }
1204 }
1205
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001206 public void initializeMulticastFiltering() {
1207 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001208
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001209 synchronized (mMulticasters) {
1210 // if anybody had requested filters be off, leave off
1211 if (mMulticasters.size() != 0) {
1212 return;
1213 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001214 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001215 }
1216 }
1217 }
1218
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001219 public void acquireMulticastLock(IBinder binder, String tag) {
1220 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001221
1222 synchronized (mMulticasters) {
1223 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001224 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001225 // Note that we could call stopPacketFiltering only when
1226 // our new size == 1 (first call), but this function won't
1227 // be called often and by making the stopPacket call each
1228 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001229 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001230 }
1231
1232 int uid = Binder.getCallingUid();
1233 Long ident = Binder.clearCallingIdentity();
1234 try {
1235 mBatteryStats.noteWifiMulticastEnabled(uid);
1236 } catch (RemoteException e) {
1237 } finally {
1238 Binder.restoreCallingIdentity(ident);
1239 }
1240 }
1241
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001242 public void releaseMulticastLock() {
1243 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001244
1245 int uid = Binder.getCallingUid();
1246 synchronized (mMulticasters) {
1247 mMulticastDisabled++;
1248 int size = mMulticasters.size();
1249 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001250 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001251 if ((m != null) && (m.getUid() == uid)) {
1252 removeMulticasterLocked(i, uid);
1253 }
1254 }
1255 }
1256 }
1257
1258 private void removeMulticasterLocked(int i, int uid)
1259 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001260 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001261
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001262 if (removed != null) {
1263 removed.unlinkDeathRecipient();
1264 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001265 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001266 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001267 }
1268
1269 Long ident = Binder.clearCallingIdentity();
1270 try {
1271 mBatteryStats.noteWifiMulticastDisabled(uid);
1272 } catch (RemoteException e) {
1273 } finally {
1274 Binder.restoreCallingIdentity(ident);
1275 }
1276 }
1277
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001278 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001279 enforceAccessPermission();
1280
1281 synchronized (mMulticasters) {
1282 return (mMulticasters.size() > 0);
1283 }
1284 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001285
1286 private void checkAndSetNotification() {
1287 // If we shouldn't place a notification on available networks, then
1288 // don't bother doing any of the following
1289 if (!mNotificationEnabled) return;
1290
1291 State state = mNetworkInfo.getState();
1292 if ((state == NetworkInfo.State.DISCONNECTED)
1293 || (state == NetworkInfo.State.UNKNOWN)) {
1294 // Look for an open network
1295 List<ScanResult> scanResults = mWifiStateMachine.getScanResultsList();
1296 if (scanResults != null) {
1297 int numOpenNetworks = 0;
1298 for (int i = scanResults.size() - 1; i >= 0; i--) {
1299 ScanResult scanResult = scanResults.get(i);
1300
1301 if (TextUtils.isEmpty(scanResult.capabilities)) {
1302 numOpenNetworks++;
1303 }
1304 }
1305
1306 if (numOpenNetworks > 0) {
1307 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1308 /*
1309 * We've scanned continuously at least
1310 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1311 * probably does not have a remembered network in range,
1312 * since otherwise supplicant would have tried to
1313 * associate and thus resetting this counter.
1314 */
1315 setNotificationVisible(true, numOpenNetworks, false, 0);
1316 }
1317 return;
1318 }
1319 }
1320 }
1321
1322 // No open networks in range, remove the notification
1323 setNotificationVisible(false, 0, false, 0);
1324 }
1325
1326 /**
1327 * Clears variables related to tracking whether a notification has been
1328 * shown recently and clears the current notification.
1329 */
1330 private void resetNotification() {
1331 mNotificationRepeatTime = 0;
1332 mNumScansSinceNetworkStateChange = 0;
1333 setNotificationVisible(false, 0, false, 0);
1334 }
1335
1336 /**
1337 * Display or don't display a notification that there are open Wi-Fi networks.
1338 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1339 * @param numNetworks the number networks seen
1340 * @param force {@code true} to force notification to be shown/not-shown,
1341 * even if it is already shown/not-shown.
1342 * @param delay time in milliseconds after which the notification should be made
1343 * visible or invisible.
1344 */
1345 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1346 int delay) {
1347
1348 // Since we use auto cancel on the notification, when the
1349 // mNetworksAvailableNotificationShown is true, the notification may
1350 // have actually been canceled. However, when it is false we know
1351 // for sure that it is not being shown (it will not be shown any other
1352 // place than here)
1353
1354 // If it should be hidden and it is already hidden, then noop
1355 if (!visible && !mNotificationShown && !force) {
1356 return;
1357 }
1358
1359 NotificationManager notificationManager = (NotificationManager) mContext
1360 .getSystemService(Context.NOTIFICATION_SERVICE);
1361
1362 Message message;
1363 if (visible) {
1364
1365 // Not enough time has passed to show the notification again
1366 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1367 return;
1368 }
1369
1370 if (mNotification == null) {
1371 // Cache the Notification mainly so we can remove the
1372 // EVENT_NOTIFICATION_CHANGED message with this Notification from
1373 // the queue later
1374 mNotification = new Notification();
1375 mNotification.when = 0;
1376 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1377 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1378 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1379 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1380 }
1381
1382 CharSequence title = mContext.getResources().getQuantityText(
1383 com.android.internal.R.plurals.wifi_available, numNetworks);
1384 CharSequence details = mContext.getResources().getQuantityText(
1385 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1386 mNotification.tickerText = title;
1387 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1388
1389 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1390
1391 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
1392 /*
1393 * TODO: Clean up connectivity service & remove this
1394 */
1395 /* message = mCsHandler.obtainMessage(EVENT_NOTIFICATION_CHANGED, 1,
1396 ICON_NETWORKS_AVAILABLE, mNotification); */
1397
1398
1399 } else {
1400
1401 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
1402 /*
1403 * TODO: Clean up connectivity service & remove this
1404 */
1405 /*
1406 // Remove any pending messages to show the notification
1407 mCsHandler.removeMessages(EVENT_NOTIFICATION_CHANGED, mNotification);
1408
1409 message = mCsHandler.obtainMessage(EVENT_NOTIFICATION_CHANGED, 0,
1410 ICON_NETWORKS_AVAILABLE);
1411 */
1412 }
1413
1414 //mCsHandler.sendMessageDelayed(message, delay);
1415
1416 mNotificationShown = visible;
1417 }
1418
1419 private class NotificationEnabledSettingObserver extends ContentObserver {
1420
1421 public NotificationEnabledSettingObserver(Handler handler) {
1422 super(handler);
1423 }
1424
1425 public void register() {
1426 ContentResolver cr = mContext.getContentResolver();
1427 cr.registerContentObserver(Settings.Secure.getUriFor(
1428 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1429 mNotificationEnabled = getValue();
1430 }
1431
1432 @Override
1433 public void onChange(boolean selfChange) {
1434 super.onChange(selfChange);
1435
1436 mNotificationEnabled = getValue();
1437 resetNotification();
1438 }
1439
1440 private boolean getValue() {
1441 return Settings.Secure.getInt(mContext.getContentResolver(),
1442 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1443 }
1444 }
1445
1446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447}