blob: 064d47f639c83888ccf451188c7d2016947812ab [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
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700769 public void connectNetworkWithId(int networkId) {
770 enforceChangePermission();
771 mWifiStateMachine.connectNetwork(networkId);
772 }
773
774 public void connectNetworkWithConfig(WifiConfiguration config) {
775 enforceChangePermission();
776 mWifiStateMachine.connectNetwork(config);
777 }
778
779 public void saveNetwork(WifiConfiguration config) {
780 enforceChangePermission();
781 mWifiStateMachine.saveNetwork(config);
782 }
783
784 public void forgetNetwork(int netId) {
785 enforceChangePermission();
786 mWifiStateMachine.forgetNetwork(netId);
787 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
790 @Override
791 public void onReceive(Context context, Intent intent) {
792 String action = intent.getAction();
793
Doug Zongker43866e02010-01-07 12:09:54 -0800794 long idleMillis =
795 Settings.Secure.getLong(mContext.getContentResolver(),
796 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800798 Settings.System.getInt(mContext.getContentResolver(),
799 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800801 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 mAlarmManager.cancel(mIdleIntent);
803 mDeviceIdle = false;
804 mScreenOff = false;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700805 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800807 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700809 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 /*
811 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
812 * AND the "stay on while plugged in" setting doesn't match the
813 * current power conditions (i.e, not plugged in, plugged in to USB,
814 * or plugged in to AC).
815 */
816 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700817 WifiInfo info = mWifiStateMachine.requestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700818 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700819 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700820 // we don't have time to track down for this release. Delay instead,
821 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700822 // TODO - fix the race conditions and switch back to the immediate turn-off
823 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -0800824 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700825 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
826 // // do not keep Wifi awake when screen is off if Wifi is not associated
827 // mDeviceIdle = true;
828 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400829 } else {
830 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800831 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400832 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835 /* we can return now -- there's nothing to do until we get the idle intent back */
836 return;
837 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800838 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 mDeviceIdle = true;
840 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
841 /*
842 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
843 * AND we are transitioning from a state in which the device was supposed
844 * to stay awake to a state in which it is not supposed to stay awake.
845 * If "stay awake" state is not changing, we do nothing, to avoid resetting
846 * the already-set timer.
847 */
848 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800849 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
851 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
852 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800853 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
855 mPluggedType = pluggedType;
856 return;
857 }
858 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -0700859 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800860 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
861 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
862 boolean isBluetoothPlaying = false;
863 for (BluetoothDevice sink : sinks) {
864 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
865 isBluetoothPlaying = true;
866 }
867 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700868 mWifiStateMachine.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 } else {
871 return;
872 }
873
874 updateWifiState();
875 }
876
877 /**
878 * Determines whether the Wi-Fi chipset should stay awake or be put to
879 * sleep. Looks at the setting for the sleep policy and the current
880 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800881 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 * @see #shouldDeviceStayAwake(int, int)
883 */
884 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
885 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
886 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
887
888 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
889 // Never sleep
890 return true;
891 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
892 (pluggedType != 0)) {
893 // Never sleep while plugged, and we're plugged
894 return true;
895 } else {
896 // Default
897 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
898 }
899 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 /**
902 * Determine whether the bit value corresponding to {@code pluggedType} is set in
903 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
904 * of {@code 0} isn't really a plugged type, but rather an indication that the
905 * device isn't plugged in at all, there is no bit value corresponding to a
906 * {@code pluggedType} value of {@code 0}. That is why we shift by
907 * {@code pluggedType&nbsp;&#8212;&nbsp;1} instead of by {@code pluggedType}.
908 * @param stayAwakeConditions a bit string specifying which "plugged types" should
909 * keep the device (and hence Wi-Fi) awake.
910 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
911 * being made
912 * @return {@code true} if {@code pluggedType} indicates that the device is
913 * supposed to stay awake, {@code false} otherwise.
914 */
915 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
916 return (stayAwakeConditions & pluggedType) != 0;
917 }
918 };
919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 private void updateWifiState() {
921 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700922 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 boolean lockHeld = mLocks.hasLocks();
924 int strongestLockMode;
925 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
926 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
927 if (mDeviceIdle && lockHeld) {
928 strongestLockMode = mLocks.getStrongestLockMode();
929 } else {
930 strongestLockMode = WifiManager.WIFI_MODE_FULL;
931 }
932
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700933 /* Disable tethering when airplane mode is enabled */
934 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700935 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700936 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700937
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700938 if (wifiShouldBeEnabled) {
939 if (wifiShouldBeStarted) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700940 mWifiStateMachine.setWifiEnabled(true);
941 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700942 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700943 mWifiStateMachine.setDriverStart(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700945 mWifiStateMachine.requestCmWakeLock();
946 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700948 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700949 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 }
951 }
952
953 private void registerForBroadcasts() {
954 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
956 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
957 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
958 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -0700959 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 mContext.registerReceiver(mReceiver, intentFilter);
961 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 private boolean isAirplaneSensitive() {
964 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
965 Settings.System.AIRPLANE_MODE_RADIOS);
966 return airplaneModeRadios == null
967 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
968 }
969
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700970 private boolean isAirplaneToggleable() {
971 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
972 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
973 return toggleableRadios != null
974 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
975 }
976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 /**
978 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
979 * currently on.
980 * @return {@code true} if airplane mode is on.
981 */
982 private boolean isAirplaneModeOn() {
983 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
984 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
985 }
986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 @Override
988 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
989 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
990 != PackageManager.PERMISSION_GRANTED) {
991 pw.println("Permission Denial: can't dump WifiService from from pid="
992 + Binder.getCallingPid()
993 + ", uid=" + Binder.getCallingUid());
994 return;
995 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700996 pw.println("Wi-Fi is " + mWifiStateMachine.getWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 pw.println("Stay-awake conditions: " +
998 Settings.System.getInt(mContext.getContentResolver(),
999 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1000 pw.println();
1001
1002 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001003 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 pw.println();
1005 pw.println("Latest scan results:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001006 List<ScanResult> scanResults = mWifiStateMachine.getScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 if (scanResults != null && scanResults.size() != 0) {
1008 pw.println(" BSSID Frequency RSSI Flags SSID");
1009 for (ScanResult r : scanResults) {
1010 pw.printf(" %17s %9d %5d %-16s %s%n",
1011 r.BSSID,
1012 r.frequency,
1013 r.level,
1014 r.capabilities,
1015 r.SSID == null ? "" : r.SSID);
1016 }
1017 }
1018 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001019 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1020 mScanLocksAcquired + " scan");
1021 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1022 mScanLocksReleased + " scan");
1023 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 pw.println("Locks held:");
1025 mLocks.dump(pw);
1026 }
1027
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001028 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001030 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
1032
1033 public void binderDied() {
1034 synchronized (mLocks) {
1035 releaseWifiLockLocked(mBinder);
1036 }
1037 }
1038
1039 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001040 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
1042 }
1043
1044 private class LockList {
1045 private List<WifiLock> mList;
1046
1047 private LockList() {
1048 mList = new ArrayList<WifiLock>();
1049 }
1050
1051 private synchronized boolean hasLocks() {
1052 return !mList.isEmpty();
1053 }
1054
1055 private synchronized int getStrongestLockMode() {
1056 if (mList.isEmpty()) {
1057 return WifiManager.WIFI_MODE_FULL;
1058 }
1059 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001060 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 return WifiManager.WIFI_MODE_FULL;
1062 }
1063 }
1064 return WifiManager.WIFI_MODE_SCAN_ONLY;
1065 }
1066
1067 private void addLock(WifiLock lock) {
1068 if (findLockByBinder(lock.mBinder) < 0) {
1069 mList.add(lock);
1070 }
1071 }
1072
1073 private WifiLock removeLock(IBinder binder) {
1074 int index = findLockByBinder(binder);
1075 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001076 WifiLock ret = mList.remove(index);
1077 ret.unlinkDeathRecipient();
1078 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 } else {
1080 return null;
1081 }
1082 }
1083
1084 private int findLockByBinder(IBinder binder) {
1085 int size = mList.size();
1086 for (int i = size - 1; i >= 0; i--)
1087 if (mList.get(i).mBinder == binder)
1088 return i;
1089 return -1;
1090 }
1091
1092 private void dump(PrintWriter pw) {
1093 for (WifiLock l : mList) {
1094 pw.print(" ");
1095 pw.println(l);
1096 }
1097 }
1098 }
1099
1100 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1101 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1102 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1103 return false;
1104 }
1105 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1106 synchronized (mLocks) {
1107 return acquireWifiLockLocked(wifiLock);
1108 }
1109 }
1110
1111 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001112 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001115
The Android Open Source Project10592532009-03-18 17:39:46 -07001116 int uid = Binder.getCallingUid();
1117 long ident = Binder.clearCallingIdentity();
1118 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001119 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001120 case WifiManager.WIFI_MODE_FULL:
1121 ++mFullLocksAcquired;
1122 mBatteryStats.noteFullWifiLockAcquired(uid);
1123 break;
1124 case WifiManager.WIFI_MODE_SCAN_ONLY:
1125 ++mScanLocksAcquired;
1126 mBatteryStats.noteScanWifiLockAcquired(uid);
1127 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001128 }
1129 } catch (RemoteException e) {
1130 } finally {
1131 Binder.restoreCallingIdentity(ident);
1132 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 updateWifiState();
1135 return true;
1136 }
1137
1138 public boolean releaseWifiLock(IBinder lock) {
1139 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1140 synchronized (mLocks) {
1141 return releaseWifiLockLocked(lock);
1142 }
1143 }
1144
1145 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001146 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001147
The Android Open Source Project10592532009-03-18 17:39:46 -07001148 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001149
Joe Onorato8a9b2202010-02-26 18:56:32 -08001150 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001151
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001152 hadLock = (wifiLock != null);
1153
1154 if (hadLock) {
1155 int uid = Binder.getCallingUid();
1156 long ident = Binder.clearCallingIdentity();
1157 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001158 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001159 case WifiManager.WIFI_MODE_FULL:
1160 ++mFullLocksReleased;
1161 mBatteryStats.noteFullWifiLockReleased(uid);
1162 break;
1163 case WifiManager.WIFI_MODE_SCAN_ONLY:
1164 ++mScanLocksReleased;
1165 mBatteryStats.noteScanWifiLockReleased(uid);
1166 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001167 }
1168 } catch (RemoteException e) {
1169 } finally {
1170 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001171 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001172 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001173 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001175 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001177
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001178 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001179 implements IBinder.DeathRecipient {
1180 String mTag;
1181 int mMode;
1182 IBinder mBinder;
1183
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001184 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001185 super();
1186 mTag = tag;
1187 mMode = mode;
1188 mBinder = binder;
1189 try {
1190 mBinder.linkToDeath(this, 0);
1191 } catch (RemoteException e) {
1192 binderDied();
1193 }
1194 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001195
1196 void unlinkDeathRecipient() {
1197 mBinder.unlinkToDeath(this, 0);
1198 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001199 }
1200
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001201 private class Multicaster extends DeathRecipient {
1202 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001203 super(Binder.getCallingUid(), tag, binder);
1204 }
1205
1206 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001207 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001208 synchronized (mMulticasters) {
1209 int i = mMulticasters.indexOf(this);
1210 if (i != -1) {
1211 removeMulticasterLocked(i, mMode);
1212 }
1213 }
1214 }
1215
1216 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001217 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001218 }
1219
1220 public int getUid() {
1221 return mMode;
1222 }
1223 }
1224
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001225 public void initializeMulticastFiltering() {
1226 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001227
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001228 synchronized (mMulticasters) {
1229 // if anybody had requested filters be off, leave off
1230 if (mMulticasters.size() != 0) {
1231 return;
1232 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001233 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001234 }
1235 }
1236 }
1237
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001238 public void acquireMulticastLock(IBinder binder, String tag) {
1239 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001240
1241 synchronized (mMulticasters) {
1242 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001243 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001244 // Note that we could call stopPacketFiltering only when
1245 // our new size == 1 (first call), but this function won't
1246 // be called often and by making the stopPacket call each
1247 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001248 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001249 }
1250
1251 int uid = Binder.getCallingUid();
1252 Long ident = Binder.clearCallingIdentity();
1253 try {
1254 mBatteryStats.noteWifiMulticastEnabled(uid);
1255 } catch (RemoteException e) {
1256 } finally {
1257 Binder.restoreCallingIdentity(ident);
1258 }
1259 }
1260
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001261 public void releaseMulticastLock() {
1262 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001263
1264 int uid = Binder.getCallingUid();
1265 synchronized (mMulticasters) {
1266 mMulticastDisabled++;
1267 int size = mMulticasters.size();
1268 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001269 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001270 if ((m != null) && (m.getUid() == uid)) {
1271 removeMulticasterLocked(i, uid);
1272 }
1273 }
1274 }
1275 }
1276
1277 private void removeMulticasterLocked(int i, int uid)
1278 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001279 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001280
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001281 if (removed != null) {
1282 removed.unlinkDeathRecipient();
1283 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001284 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001285 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001286 }
1287
1288 Long ident = Binder.clearCallingIdentity();
1289 try {
1290 mBatteryStats.noteWifiMulticastDisabled(uid);
1291 } catch (RemoteException e) {
1292 } finally {
1293 Binder.restoreCallingIdentity(ident);
1294 }
1295 }
1296
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001297 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001298 enforceAccessPermission();
1299
1300 synchronized (mMulticasters) {
1301 return (mMulticasters.size() > 0);
1302 }
1303 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001304
1305 private void checkAndSetNotification() {
1306 // If we shouldn't place a notification on available networks, then
1307 // don't bother doing any of the following
1308 if (!mNotificationEnabled) return;
1309
1310 State state = mNetworkInfo.getState();
1311 if ((state == NetworkInfo.State.DISCONNECTED)
1312 || (state == NetworkInfo.State.UNKNOWN)) {
1313 // Look for an open network
1314 List<ScanResult> scanResults = mWifiStateMachine.getScanResultsList();
1315 if (scanResults != null) {
1316 int numOpenNetworks = 0;
1317 for (int i = scanResults.size() - 1; i >= 0; i--) {
1318 ScanResult scanResult = scanResults.get(i);
1319
1320 if (TextUtils.isEmpty(scanResult.capabilities)) {
1321 numOpenNetworks++;
1322 }
1323 }
1324
1325 if (numOpenNetworks > 0) {
1326 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1327 /*
1328 * We've scanned continuously at least
1329 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1330 * probably does not have a remembered network in range,
1331 * since otherwise supplicant would have tried to
1332 * associate and thus resetting this counter.
1333 */
1334 setNotificationVisible(true, numOpenNetworks, false, 0);
1335 }
1336 return;
1337 }
1338 }
1339 }
1340
1341 // No open networks in range, remove the notification
1342 setNotificationVisible(false, 0, false, 0);
1343 }
1344
1345 /**
1346 * Clears variables related to tracking whether a notification has been
1347 * shown recently and clears the current notification.
1348 */
1349 private void resetNotification() {
1350 mNotificationRepeatTime = 0;
1351 mNumScansSinceNetworkStateChange = 0;
1352 setNotificationVisible(false, 0, false, 0);
1353 }
1354
1355 /**
1356 * Display or don't display a notification that there are open Wi-Fi networks.
1357 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1358 * @param numNetworks the number networks seen
1359 * @param force {@code true} to force notification to be shown/not-shown,
1360 * even if it is already shown/not-shown.
1361 * @param delay time in milliseconds after which the notification should be made
1362 * visible or invisible.
1363 */
1364 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1365 int delay) {
1366
1367 // Since we use auto cancel on the notification, when the
1368 // mNetworksAvailableNotificationShown is true, the notification may
1369 // have actually been canceled. However, when it is false we know
1370 // for sure that it is not being shown (it will not be shown any other
1371 // place than here)
1372
1373 // If it should be hidden and it is already hidden, then noop
1374 if (!visible && !mNotificationShown && !force) {
1375 return;
1376 }
1377
1378 NotificationManager notificationManager = (NotificationManager) mContext
1379 .getSystemService(Context.NOTIFICATION_SERVICE);
1380
1381 Message message;
1382 if (visible) {
1383
1384 // Not enough time has passed to show the notification again
1385 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1386 return;
1387 }
1388
1389 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001390 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001391 mNotification = new Notification();
1392 mNotification.when = 0;
1393 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1394 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1395 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1396 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1397 }
1398
1399 CharSequence title = mContext.getResources().getQuantityText(
1400 com.android.internal.R.plurals.wifi_available, numNetworks);
1401 CharSequence details = mContext.getResources().getQuantityText(
1402 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1403 mNotification.tickerText = title;
1404 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1405
1406 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1407
1408 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001409 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001410 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001411 }
1412
Irfan Sheriff0d255342010-07-28 09:35:20 -07001413 mNotificationShown = visible;
1414 }
1415
1416 private class NotificationEnabledSettingObserver extends ContentObserver {
1417
1418 public NotificationEnabledSettingObserver(Handler handler) {
1419 super(handler);
1420 }
1421
1422 public void register() {
1423 ContentResolver cr = mContext.getContentResolver();
1424 cr.registerContentObserver(Settings.Secure.getUriFor(
1425 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1426 mNotificationEnabled = getValue();
1427 }
1428
1429 @Override
1430 public void onChange(boolean selfChange) {
1431 super.onChange(selfChange);
1432
1433 mNotificationEnabled = getValue();
1434 resetNotification();
1435 }
1436
1437 private boolean getValue() {
1438 return Settings.Secure.getInt(mContext.getContentResolver(),
1439 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1440 }
1441 }
1442
1443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444}