blob: 5bfe6f8bbc2f1627d44b235cce431d85d512b4ed [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;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070023import android.bluetooth.BluetoothAdapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.BroadcastReceiver;
25import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070030import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.net.wifi.IWifiManager;
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -080032import android.net.wifi.ScanResult;
33import android.net.wifi.SupplicantState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.net.wifi.WifiInfo;
35import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070036import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.net.wifi.WifiConfiguration;
Isaac Levy654f5092011-07-13 17:41:45 -070038import android.net.wifi.WifiWatchdogStateMachine;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080039import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff651cdfc2011-09-07 00:31:20 -070040import android.net.wifi.WpsInfo;
Irfan Sheriffe4c56c92011-01-12 16:33:58 -080041import android.net.wifi.WpsResult;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080042import android.net.ConnectivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070044import android.net.NetworkInfo;
45import android.net.NetworkInfo.State;
Irfan Sheriff227bec42011-02-15 19:30:27 -080046import android.net.NetworkInfo.DetailedState;
47import android.net.TrafficStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070049import android.os.Handler;
Irfan Sheriff227bec42011-02-15 19:30:27 -080050import android.os.Messenger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.HandlerThread;
52import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080053import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070054import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070056import android.os.ServiceManager;
Irfan Sheriff227bec42011-02-15 19:30:27 -080057import android.os.SystemProperties;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070058import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070060import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080061import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062
63import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080065import java.util.Set;
Irfan Sheriff658772f2011-03-08 14:52:31 -080066import java.util.concurrent.atomic.AtomicInteger;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070067import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.io.FileDescriptor;
69import java.io.PrintWriter;
70
The Android Open Source Project10592532009-03-18 17:39:46 -070071import com.android.internal.app.IBatteryStats;
Irfan Sheriff616f3172011-09-11 19:59:01 -070072import com.android.internal.telephony.TelephonyIntents;
Wink Saville4b7ba092010-10-20 15:37:41 -070073import com.android.internal.util.AsyncChannel;
The Android Open Source Project10592532009-03-18 17:39:46 -070074import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080075import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077/**
78 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070079 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 *
81 * @hide
82 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070083//TODO: Clean up multiple locks and implement WifiService
84// as a SM to track soft AP/client/adhoc bring up based
85// on device idle state, airplane mode and boot.
86
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087public class WifiService extends IWifiManager.Stub {
88 private static final String TAG = "WifiService";
Dianne Hackborn5fd21692011-06-07 14:09:47 -070089 private static final boolean DBG = false;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070090
Irfan Sheriff0d255342010-07-28 09:35:20 -070091 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092
93 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
95 private AlarmManager mAlarmManager;
96 private PendingIntent mIdleIntent;
97 private static final int IDLE_REQUEST = 0;
98 private boolean mScreenOff;
99 private boolean mDeviceIdle;
Irfan Sheriff616f3172011-09-11 19:59:01 -0700100 private boolean mEmergencyCallbackMode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private int mPluggedType;
102
Irfan Sherifffcc08452011-02-17 16:44:54 -0800103 /* Chipset supports background scan */
104 private final boolean mBackgroundScanSupported;
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700107 // some wifi lock statistics
Irfan Sheriff5876a422010-08-12 20:26:23 -0700108 private int mFullHighPerfLocksAcquired;
109 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700110 private int mFullLocksAcquired;
111 private int mFullLocksReleased;
112 private int mScanLocksAcquired;
113 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700114
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700115 private final List<Multicaster> mMulticasters =
116 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700117 private int mMulticastEnabled;
118 private int mMulticastDisabled;
119
The Android Open Source Project10592532009-03-18 17:39:46 -0700120 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800121
Irfan Sheriff227bec42011-02-15 19:30:27 -0800122 private boolean mEnableTrafficStatsPoll = false;
123 private int mTrafficStatsPollToken = 0;
124 private long mTxPkts;
125 private long mRxPkts;
126 /* Tracks last reported data activity */
127 private int mDataActivity;
128 private String mInterfaceName;
129
130 /**
131 * Interval in milliseconds between polling for traffic
132 * statistics
133 */
134 private static final int POLL_TRAFFIC_STATS_INTERVAL_MSECS = 1000;
135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800137 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
138 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 * the approximate point at which the battery drain caused by Wi-Fi
140 * being enabled but not active exceeds the battery drain caused by
141 * re-establishing a connection to the mobile data network.
142 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700143 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private static final String ACTION_DEVICE_IDLE =
146 "com.android.server.WifiManager.action.DEVICE_IDLE";
147
Irfan Sheriff658772f2011-03-08 14:52:31 -0800148 private static final int WIFI_DISABLED = 0;
149 private static final int WIFI_ENABLED = 1;
150 /* Wifi enabled while in airplane mode */
151 private static final int WIFI_ENABLED_AIRPLANE_OVERRIDE = 2;
Irfan Sheriff31b92e22011-10-03 12:13:20 -0700152 /* Wifi disabled due to airplane mode on */
153 private static final int WIFI_DISABLED_AIRPLANE_ON = 3;
Irfan Sheriff658772f2011-03-08 14:52:31 -0800154
155 private AtomicInteger mWifiState = new AtomicInteger(WIFI_DISABLED);
156 private AtomicBoolean mAirplaneModeOn = new AtomicBoolean(false);
157
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700158 private boolean mIsReceiverRegistered = false;
159
Irfan Sheriff0d255342010-07-28 09:35:20 -0700160
161 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
162
163 // Variables relating to the 'available networks' notification
164 /**
165 * The icon to show in the 'available networks' notification. This will also
166 * be the ID of the Notification given to the NotificationManager.
167 */
168 private static final int ICON_NETWORKS_AVAILABLE =
169 com.android.internal.R.drawable.stat_notify_wifi_in_range;
170 /**
171 * When a notification is shown, we wait this amount before possibly showing it again.
172 */
173 private final long NOTIFICATION_REPEAT_DELAY_MS;
174 /**
175 * Whether the user has set the setting to show the 'available networks' notification.
176 */
177 private boolean mNotificationEnabled;
178 /**
179 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
180 */
181 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
182 /**
183 * The {@link System#currentTimeMillis()} must be at least this value for us
184 * to show the notification again.
185 */
186 private long mNotificationRepeatTime;
187 /**
188 * The Notification object given to the NotificationManager.
189 */
190 private Notification mNotification;
191 /**
192 * Whether the notification is being shown, as set by us. That is, if the
193 * user cancels the notification, we will not receive the callback so this
194 * will still be true. We only guarantee if this is false, then the
195 * notification is not showing.
196 */
197 private boolean mNotificationShown;
198 /**
199 * The number of continuous scans that must occur before consider the
200 * supplicant in a scanning state. This allows supplicant to associate with
201 * remembered networks that are in the scan results.
202 */
203 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
204 /**
205 * The number of scans since the last network state change. When this
206 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
207 * supplicant to actually be scanning. When the network state changes to
208 * something other than scanning, we reset this to 0.
209 */
210 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700211
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700212 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700213 * Asynchronous channel to WifiStateMachine
214 */
Irfan Sheriff227bec42011-02-15 19:30:27 -0800215 private AsyncChannel mWifiStateMachineChannel;
Wink Saville4b7ba092010-10-20 15:37:41 -0700216
217 /**
Irfan Sheriff227bec42011-02-15 19:30:27 -0800218 * Clients receiving asynchronous messages
Wink Saville4b7ba092010-10-20 15:37:41 -0700219 */
Irfan Sheriff227bec42011-02-15 19:30:27 -0800220 private List<AsyncChannel> mClients = new ArrayList<AsyncChannel>();
Wink Saville4b7ba092010-10-20 15:37:41 -0700221
Irfan Sheriff227bec42011-02-15 19:30:27 -0800222 /**
223 * Handles client connections
224 */
225 private class AsyncServiceHandler extends Handler {
226
227 AsyncServiceHandler(android.os.Looper looper) {
Wink Saville4b7ba092010-10-20 15:37:41 -0700228 super(looper);
Wink Saville4b7ba092010-10-20 15:37:41 -0700229 }
230
231 @Override
232 public void handleMessage(Message msg) {
233 switch (msg.what) {
234 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
235 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800236 Slog.d(TAG, "New client listening to asynchronous messages");
237 mClients.add((AsyncChannel) msg.obj);
Wink Saville4b7ba092010-10-20 15:37:41 -0700238 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800239 Slog.e(TAG, "Client connection failure, error=" + msg.arg1);
240 }
241 break;
242 }
Irfan Sheriffc23971b2011-03-04 17:06:31 -0800243 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
244 if (msg.arg1 == AsyncChannel.STATUS_SEND_UNSUCCESSFUL) {
245 Slog.d(TAG, "Send failed, client connection lost");
246 } else {
247 Slog.d(TAG, "Client connection lost with reason: " + msg.arg1);
248 }
249 mClients.remove((AsyncChannel) msg.obj);
250 break;
251 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800252 case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: {
253 AsyncChannel ac = new AsyncChannel();
254 ac.connect(mContext, this, msg.replyTo);
255 break;
256 }
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800257 case WifiManager.CMD_ENABLE_TRAFFIC_STATS_POLL: {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800258 mEnableTrafficStatsPoll = (msg.arg1 == 1);
259 mTrafficStatsPollToken++;
260 if (mEnableTrafficStatsPoll) {
261 notifyOnDataActivity();
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800262 sendMessageDelayed(Message.obtain(this, WifiManager.CMD_TRAFFIC_STATS_POLL,
Irfan Sheriff227bec42011-02-15 19:30:27 -0800263 mTrafficStatsPollToken, 0), POLL_TRAFFIC_STATS_INTERVAL_MSECS);
264 }
265 break;
266 }
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800267 case WifiManager.CMD_TRAFFIC_STATS_POLL: {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800268 if (msg.arg1 == mTrafficStatsPollToken) {
269 notifyOnDataActivity();
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800270 sendMessageDelayed(Message.obtain(this, WifiManager.CMD_TRAFFIC_STATS_POLL,
Irfan Sheriff227bec42011-02-15 19:30:27 -0800271 mTrafficStatsPollToken, 0), POLL_TRAFFIC_STATS_INTERVAL_MSECS);
Wink Saville4b7ba092010-10-20 15:37:41 -0700272 }
273 break;
274 }
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800275 case WifiManager.CMD_CONNECT_NETWORK: {
276 if (msg.obj != null) {
277 mWifiStateMachine.connectNetwork((WifiConfiguration)msg.obj);
278 } else {
279 mWifiStateMachine.connectNetwork(msg.arg1);
280 }
281 break;
282 }
283 case WifiManager.CMD_SAVE_NETWORK: {
284 mWifiStateMachine.saveNetwork((WifiConfiguration)msg.obj);
285 break;
286 }
287 case WifiManager.CMD_FORGET_NETWORK: {
288 mWifiStateMachine.forgetNetwork(msg.arg1);
289 break;
290 }
291 case WifiManager.CMD_START_WPS: {
292 //replyTo has the original source
Irfan Sheriff651cdfc2011-09-07 00:31:20 -0700293 mWifiStateMachine.startWps(msg.replyTo, (WpsInfo)msg.obj);
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800294 break;
295 }
Isaac Levy8dc6a1b2011-07-27 08:00:03 -0700296 case WifiManager.CMD_DISABLE_NETWORK: {
297 mWifiStateMachine.disableNetwork(msg.replyTo, msg.arg1, msg.arg2);
298 break;
299 }
Wink Saville4b7ba092010-10-20 15:37:41 -0700300 default: {
301 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
302 break;
303 }
304 }
305 }
306 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800307 private AsyncServiceHandler mAsyncServiceHandler;
308
309 /**
310 * Handles interaction with WifiStateMachine
311 */
312 private class WifiStateMachineHandler extends Handler {
313 private AsyncChannel mWsmChannel;
314
315 WifiStateMachineHandler(android.os.Looper looper) {
316 super(looper);
317 mWsmChannel = new AsyncChannel();
318 mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
319 }
320
321 @Override
322 public void handleMessage(Message msg) {
323 switch (msg.what) {
324 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
325 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
326 mWifiStateMachineChannel = mWsmChannel;
327 } else {
328 Slog.e(TAG, "WifiStateMachine connection failure, error=" + msg.arg1);
329 mWifiStateMachineChannel = null;
330 }
331 break;
332 }
Irfan Sheriff6da83d52011-06-06 12:54:06 -0700333 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
334 Slog.e(TAG, "WifiStateMachine channel lost, msg.arg1 =" + msg.arg1);
335 mWifiStateMachineChannel = null;
336 //Re-establish connection to state machine
337 mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
338 break;
339 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800340 default: {
341 Slog.d(TAG, "WifiStateMachineHandler.handleMessage ignoring msg=" + msg);
342 break;
343 }
344 }
345 }
346 }
347 WifiStateMachineHandler mWifiStateMachineHandler;
Wink Saville4b7ba092010-10-20 15:37:41 -0700348
349 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700350 * Temporary for computing UIDS that are responsible for starting WIFI.
351 * Protected by mWifiStateTracker lock.
352 */
353 private final WorkSource mTmpWorkSource = new WorkSource();
Isaac Levy654f5092011-07-13 17:41:45 -0700354 private WifiWatchdogStateMachine mWifiWatchdogStateMachine;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700355
356 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 mContext = context;
Irfan Sheriff227bec42011-02-15 19:30:27 -0800358
359 mInterfaceName = SystemProperties.get("wifi.interface", "wlan0");
360
361 mWifiStateMachine = new WifiStateMachine(mContext, mInterfaceName);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700362 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700363 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
366 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
367 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 mContext.registerReceiver(
370 new BroadcastReceiver() {
371 @Override
372 public void onReceive(Context context, Intent intent) {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800373 mAirplaneModeOn.set(isAirplaneModeOn());
374 /* On airplane mode disable, restore wifi state if necessary */
375 if (!mAirplaneModeOn.get() && (testAndClearWifiSavedState() ||
376 mWifiState.get() == WIFI_ENABLED_AIRPLANE_OVERRIDE)) {
377 persistWifiEnabled(true);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 updateWifiState();
380 }
381 },
382 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
383
Irfan Sheriff0d255342010-07-28 09:35:20 -0700384 IntentFilter filter = new IntentFilter();
385 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
386 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
387 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
388
389 mContext.registerReceiver(
390 new BroadcastReceiver() {
391 @Override
392 public void onReceive(Context context, Intent intent) {
393 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
394 // reset & clear notification on any wifi state change
395 resetNotification();
396 } else if (intent.getAction().equals(
397 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
398 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
399 WifiManager.EXTRA_NETWORK_INFO);
400 // reset & clear notification on a network connect & disconnect
401 switch(mNetworkInfo.getDetailedState()) {
402 case CONNECTED:
403 case DISCONNECTED:
Irfan Sheriff227bec42011-02-15 19:30:27 -0800404 evaluateTrafficStatsPolling();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700405 resetNotification();
406 break;
407 }
408 } else if (intent.getAction().equals(
409 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
410 checkAndSetNotification();
411 }
412 }
413 }, filter);
414
Irfan Sheriff227bec42011-02-15 19:30:27 -0800415 HandlerThread wifiThread = new HandlerThread("WifiService");
416 wifiThread.start();
417 mAsyncServiceHandler = new AsyncServiceHandler(wifiThread.getLooper());
418 mWifiStateMachineHandler = new WifiStateMachineHandler(wifiThread.getLooper());
419
Irfan Sheriff0d255342010-07-28 09:35:20 -0700420 // Setting is in seconds
421 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
422 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
423 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
424 mNotificationEnabledSettingObserver.register();
Irfan Sherifffcc08452011-02-17 16:44:54 -0800425
426 mBackgroundScanSupported = mContext.getResources().getBoolean(
427 com.android.internal.R.bool.config_wifi_background_scan_support);
Irfan Sheriff7b009782010-03-11 16:37:45 -0800428 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800429
Irfan Sheriff7b009782010-03-11 16:37:45 -0800430 /**
431 * Check if Wi-Fi needs to be enabled and start
432 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700433 *
434 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800435 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700436 public void checkAndStartWifi() {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800437 mAirplaneModeOn.set(isAirplaneModeOn());
438 mWifiState.set(getPersistedWifiState());
439 /* Start if Wi-Fi should be enabled or the saved state indicates Wi-Fi was on */
440 boolean wifiEnabled = shouldWifiBeEnabled() || testAndClearWifiSavedState();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800441 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
442 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700443 setWifiEnabled(wifiEnabled);
Isaac Levybc7dfb52011-06-06 15:34:01 -0700444
Isaac Levy654f5092011-07-13 17:41:45 -0700445 mWifiWatchdogStateMachine = WifiWatchdogStateMachine.
446 makeWifiWatchdogStateMachine(mContext);
447
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800448 }
449
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700450 private boolean testAndClearWifiSavedState() {
451 final ContentResolver cr = mContext.getContentResolver();
452 int wifiSavedState = 0;
453 try {
454 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
455 if(wifiSavedState == 1)
456 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
457 } catch (Settings.SettingNotFoundException e) {
458 ;
459 }
460 return (wifiSavedState == 1);
461 }
462
Irfan Sheriff658772f2011-03-08 14:52:31 -0800463 private int getPersistedWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 final ContentResolver cr = mContext.getContentResolver();
465 try {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800466 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 } catch (Settings.SettingNotFoundException e) {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800468 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, WIFI_DISABLED);
469 return WIFI_DISABLED;
470 }
471 }
472
473 private boolean shouldWifiBeEnabled() {
474 if (mAirplaneModeOn.get()) {
475 return mWifiState.get() == WIFI_ENABLED_AIRPLANE_OVERRIDE;
476 } else {
477 return mWifiState.get() != WIFI_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 }
479 }
480
481 private void persistWifiEnabled(boolean enabled) {
482 final ContentResolver cr = mContext.getContentResolver();
Irfan Sheriff31b92e22011-10-03 12:13:20 -0700483 boolean airplane = mAirplaneModeOn.get() && isAirplaneToggleable();
Irfan Sheriff658772f2011-03-08 14:52:31 -0800484 if (enabled) {
Irfan Sheriff31b92e22011-10-03 12:13:20 -0700485 if (airplane) {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800486 mWifiState.set(WIFI_ENABLED_AIRPLANE_OVERRIDE);
487 } else {
488 mWifiState.set(WIFI_ENABLED);
489 }
490 } else {
Irfan Sheriff31b92e22011-10-03 12:13:20 -0700491 if (airplane) {
492 mWifiState.set(WIFI_DISABLED_AIRPLANE_ON);
493 } else {
494 mWifiState.set(WIFI_DISABLED);
495 }
Irfan Sheriff658772f2011-03-08 14:52:31 -0800496 }
497 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, mWifiState.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 }
499
Irfan Sheriff658772f2011-03-08 14:52:31 -0800500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 /**
502 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700503 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 */
505 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700506 enforceAccessPermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800507 if (mWifiStateMachineChannel != null) {
508 return mWifiStateMachine.syncPingSupplicant(mWifiStateMachineChannel);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700509 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800510 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700511 return false;
512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
514
515 /**
516 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700518 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700520 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 }
522
523 private void enforceAccessPermission() {
524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
525 "WifiService");
526 }
527
528 private void enforceChangePermission() {
529 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
530 "WifiService");
531
532 }
533
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700534 private void enforceMulticastChangePermission() {
535 mContext.enforceCallingOrSelfPermission(
536 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
537 "WifiService");
538 }
539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700541 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
542 * @param enable {@code true} to enable, {@code false} to disable.
543 * @return {@code true} if the enable/disable operation was
544 * started or is already in the queue.
545 */
546 public synchronized boolean setWifiEnabled(boolean enable) {
547 enforceChangePermission();
548
549 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700550 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700551 }
552
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700553 if (enable) {
554 reportStartWorkSource();
555 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700556 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700557
558 /*
559 * Caller might not have WRITE_SECURE_SETTINGS,
560 * only CHANGE_WIFI_STATE is enforced
561 */
562 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700563 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700564 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700565
566 if (enable) {
567 if (!mIsReceiverRegistered) {
568 registerForBroadcasts();
569 mIsReceiverRegistered = true;
570 }
571 } else if (mIsReceiverRegistered){
572 mContext.unregisterReceiver(mReceiver);
573 mIsReceiverRegistered = false;
574 }
575
576 return true;
577 }
578
579 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 * see {@link WifiManager#getWifiState()}
581 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
582 * {@link WifiManager#WIFI_STATE_DISABLING},
583 * {@link WifiManager#WIFI_STATE_ENABLED},
584 * {@link WifiManager#WIFI_STATE_ENABLING},
585 * {@link WifiManager#WIFI_STATE_UNKNOWN}
586 */
587 public int getWifiEnabledState() {
588 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700589 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 }
591
592 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700593 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800594 * @param wifiConfig SSID, security and channel details as
595 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700596 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800597 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700598 public void setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800599 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700600 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800601 }
602
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700603 /**
604 * see {@link WifiManager#getWifiApState()}
605 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
606 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
607 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
608 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
609 * {@link WifiManager#WIFI_AP_STATE_FAILED}
610 */
611 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700612 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700613 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700614 }
615
616 /**
617 * see {@link WifiManager#getWifiApConfiguration()}
618 * @return soft access point configuration
619 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700620 public WifiConfiguration getWifiApConfiguration() {
621 enforceAccessPermission();
Irfan Sheriff6da83d52011-06-06 12:54:06 -0700622 if (mWifiStateMachineChannel != null) {
623 return mWifiStateMachine.syncGetWifiApConfiguration(mWifiStateMachineChannel);
624 } else {
625 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
626 return null;
627 }
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800628 }
629
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700630 /**
631 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
632 * @param wifiConfig WifiConfiguration details for soft access point
633 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700634 public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700635 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800636 if (wifiConfig == null)
637 return;
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700638 mWifiStateMachine.setWifiApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800639 }
640
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800641 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700642 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800643 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700644 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700645 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700646 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800647 }
648
649 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700650 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800651 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700652 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700653 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700654 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800655 }
656
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700657 /**
658 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700659 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700660 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700661 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700662 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800663 }
664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 /**
666 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
667 * @return the list of configured networks
668 */
669 public List<WifiConfiguration> getConfiguredNetworks() {
670 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700671 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800672 }
673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 /**
675 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
676 * @return the supplicant-assigned identifier for the new or updated
677 * network if the operation succeeds, or {@code -1} if it fails
678 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800679 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800681 if (mWifiStateMachineChannel != null) {
682 return mWifiStateMachine.syncAddOrUpdateNetwork(mWifiStateMachineChannel, config);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700683 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800684 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700685 return -1;
686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 }
688
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700689 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
691 * @param netId the integer that identifies the network configuration
692 * to the supplicant
693 * @return {@code true} if the operation succeeded
694 */
695 public boolean removeNetwork(int netId) {
696 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800697 if (mWifiStateMachineChannel != null) {
698 return mWifiStateMachine.syncRemoveNetwork(mWifiStateMachineChannel, netId);
Wink Saville4b7ba092010-10-20 15:37:41 -0700699 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800700 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Wink Saville4b7ba092010-10-20 15:37:41 -0700701 return false;
702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
704
705 /**
706 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
707 * @param netId the integer that identifies the network configuration
708 * to the supplicant
709 * @param disableOthers if true, disable all other networks.
710 * @return {@code true} if the operation succeeded
711 */
712 public boolean enableNetwork(int netId, boolean disableOthers) {
713 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800714 if (mWifiStateMachineChannel != null) {
715 return mWifiStateMachine.syncEnableNetwork(mWifiStateMachineChannel, netId,
716 disableOthers);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700717 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800718 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700719 return false;
720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 }
722
723 /**
724 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
725 * @param netId the integer that identifies the network configuration
726 * to the supplicant
727 * @return {@code true} if the operation succeeded
728 */
729 public boolean disableNetwork(int netId) {
730 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800731 if (mWifiStateMachineChannel != null) {
732 return mWifiStateMachine.syncDisableNetwork(mWifiStateMachineChannel, netId);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700733 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800734 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700735 return false;
736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 }
738
739 /**
740 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
741 * @return the Wi-Fi information, contained in {@link WifiInfo}.
742 */
743 public WifiInfo getConnectionInfo() {
744 enforceAccessPermission();
745 /*
746 * Make sure we have the latest information, by sending
747 * a status request to the supplicant.
748 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700749 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 }
751
752 /**
753 * Return the results of the most recent access point scan, in the form of
754 * a list of {@link ScanResult} objects.
755 * @return the list of results
756 */
757 public List<ScanResult> getScanResults() {
758 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700759 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 }
761
762 /**
763 * Tell the supplicant to persist the current list of configured networks.
764 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700765 *
766 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 */
768 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700769 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800771 if (mWifiStateMachineChannel != null) {
772 return mWifiStateMachine.syncSaveConfig(mWifiStateMachineChannel);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700773 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800774 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700775 return false;
776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
778
779 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700780 * Set the country code
781 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700782 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700783 *
784 * The persist behavior exists so that wifi can fall back to the last
785 * persisted country code on a restart, when the locale information is
786 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700788 public void setCountryCode(String countryCode, boolean persist) {
789 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
790 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700792 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 }
794
795 /**
Irfan Sheriff36f74132010-11-04 16:57:37 -0700796 * Set the operational frequency band
797 * @param band One of
798 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
799 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
800 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
801 * @param persist {@code true} if the setting should be remembered.
802 *
803 */
804 public void setFrequencyBand(int band, boolean persist) {
805 enforceChangePermission();
806 if (!isDualBandSupported()) return;
807 Slog.i(TAG, "WifiService trying to set frequency band to " + band +
808 " with persist set to " + persist);
809 mWifiStateMachine.setFrequencyBand(band, persist);
810 }
811
812
813 /**
814 * Get the operational frequency band
815 */
816 public int getFrequencyBand() {
817 enforceAccessPermission();
818 return mWifiStateMachine.getFrequencyBand();
819 }
820
821 public boolean isDualBandSupported() {
822 //TODO: Should move towards adding a driver API that checks at runtime
823 return mContext.getResources().getBoolean(
824 com.android.internal.R.bool.config_wifi_dual_band_support);
825 }
826
827 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 * Return the DHCP-assigned addresses from the last successful DHCP request,
829 * if any.
830 * @return the DHCP information
831 */
832 public DhcpInfo getDhcpInfo() {
833 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700834 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 }
836
Irfan Sheriff0d255342010-07-28 09:35:20 -0700837 /**
838 * see {@link android.net.wifi.WifiManager#startWifi}
839 *
840 */
841 public void startWifi() {
842 enforceChangePermission();
843 /* TODO: may be add permissions for access only to connectivity service
844 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
845 * of WifiLock & device idle status unless wifi enabled status is toggled
846 */
847
848 mWifiStateMachine.setDriverStart(true);
849 mWifiStateMachine.reconnectCommand();
850 }
851
852 /**
853 * see {@link android.net.wifi.WifiManager#stopWifi}
854 *
855 */
856 public void stopWifi() {
857 enforceChangePermission();
858 /* TODO: may be add permissions for access only to connectivity service
859 * TODO: if a stop is issued, wifi is brought up only by startWifi
860 * unless wifi enabled status is toggled
861 */
862 mWifiStateMachine.setDriverStart(false);
863 }
864
865
866 /**
867 * see {@link android.net.wifi.WifiManager#addToBlacklist}
868 *
869 */
870 public void addToBlacklist(String bssid) {
871 enforceChangePermission();
872
873 mWifiStateMachine.addToBlacklist(bssid);
874 }
875
876 /**
877 * see {@link android.net.wifi.WifiManager#clearBlacklist}
878 *
879 */
880 public void clearBlacklist() {
881 enforceChangePermission();
882
883 mWifiStateMachine.clearBlacklist();
884 }
885
Irfan Sheriff227bec42011-02-15 19:30:27 -0800886 /**
887 * Get a reference to handler. This is used by a client to establish
888 * an AsyncChannel communication with WifiService
889 */
890 public Messenger getMessenger() {
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800891 /* Enforce the highest permissions
892 TODO: when we consider exposing the asynchronous API, think about
893 how to provide both access and change permissions seperately
894 */
Irfan Sheriff227bec42011-02-15 19:30:27 -0800895 enforceAccessPermission();
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800896 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800897 return new Messenger(mAsyncServiceHandler);
898 }
899
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800900 /**
901 * Get the IP and proxy configuration file
902 */
903 public String getConfigFile() {
904 enforceAccessPermission();
905 return mWifiStateMachine.getConfigFile();
906 }
907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
909 @Override
910 public void onReceive(Context context, Intent intent) {
911 String action = intent.getAction();
912
Doug Zongker43866e02010-01-07 12:09:54 -0800913 long idleMillis =
914 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700915 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800917 Settings.System.getInt(mContext.getContentResolver(),
918 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400920 if (DBG) {
921 Slog.d(TAG, "ACTION_SCREEN_ON");
922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 mAlarmManager.cancel(mIdleIntent);
924 mDeviceIdle = false;
925 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700926 // Once the screen is on, we are not keeping WIFI running
927 // because of any locks so clear that tracking immediately.
928 reportStartWorkSource();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800929 evaluateTrafficStatsPolling();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700930 mWifiStateMachine.enableRssiPolling(true);
Irfan Sherifffcc08452011-02-17 16:44:54 -0800931 if (mBackgroundScanSupported) {
Irfan Sheriff2b7f6382011-03-25 14:29:19 -0700932 mWifiStateMachine.enableBackgroundScanCommand(false);
Irfan Sherifffcc08452011-02-17 16:44:54 -0800933 }
Irfan Sheriff8e86b892010-12-22 11:02:20 -0800934 mWifiStateMachine.enableAllNetworks();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700935 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400937 if (DBG) {
938 Slog.d(TAG, "ACTION_SCREEN_OFF");
939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 mScreenOff = true;
Irfan Sheriff227bec42011-02-15 19:30:27 -0800941 evaluateTrafficStatsPolling();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700942 mWifiStateMachine.enableRssiPolling(false);
Irfan Sherifffcc08452011-02-17 16:44:54 -0800943 if (mBackgroundScanSupported) {
Irfan Sheriff2b7f6382011-03-25 14:29:19 -0700944 mWifiStateMachine.enableBackgroundScanCommand(true);
Irfan Sherifffcc08452011-02-17 16:44:54 -0800945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 /*
947 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
948 * AND the "stay on while plugged in" setting doesn't match the
949 * current power conditions (i.e, not plugged in, plugged in to USB,
950 * or plugged in to AC).
951 */
952 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700953 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700954 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700955 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700956 // we don't have time to track down for this release. Delay instead,
957 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700958 // TODO - fix the race conditions and switch back to the immediate turn-off
959 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400960 if (DBG) {
961 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
962 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700963 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
964 // // do not keep Wifi awake when screen is off if Wifi is not associated
965 // mDeviceIdle = true;
966 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400967 } else {
968 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400969 if (DBG) {
970 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
971 + "ms");
972 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400973 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400977 if (DBG) {
978 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700981 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700982 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
984 /*
985 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
986 * AND we are transitioning from a state in which the device was supposed
987 * to stay awake to a state in which it is not supposed to stay awake.
988 * If "stay awake" state is not changing, we do nothing, to avoid resetting
989 * the already-set timer.
990 */
991 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400992 if (DBG) {
993 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
996 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
997 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400998 if (DBG) {
999 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 }
1003 mPluggedType = pluggedType;
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001004 } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
1005 int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
1006 BluetoothAdapter.STATE_DISCONNECTED);
1007 mWifiStateMachine.sendBluetoothAdapterStateChange(state);
Irfan Sheriff616f3172011-09-11 19:59:01 -07001008 } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
1009 mEmergencyCallbackMode = intent.getBooleanExtra("phoneinECMState", false);
1010 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
1013
1014 /**
1015 * Determines whether the Wi-Fi chipset should stay awake or be put to
1016 * sleep. Looks at the setting for the sleep policy and the current
1017 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001018 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 * @see #shouldDeviceStayAwake(int, int)
1020 */
1021 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
Irfan Sheriff739f6bc2011-01-28 16:43:12 -08001022 //Never sleep as long as the user has not changed the settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
Irfan Sheriff96b10d62011-01-11 15:40:35 -08001024 Settings.System.WIFI_SLEEP_POLICY,
Irfan Sheriff739f6bc2011-01-28 16:43:12 -08001025 Settings.System.WIFI_SLEEP_POLICY_NEVER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026
1027 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
1028 // Never sleep
1029 return true;
1030 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
1031 (pluggedType != 0)) {
1032 // Never sleep while plugged, and we're plugged
1033 return true;
1034 } else {
1035 // Default
1036 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1037 }
1038 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 /**
1041 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1042 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1043 * of {@code 0} isn't really a plugged type, but rather an indication that the
1044 * device isn't plugged in at all, there is no bit value corresponding to a
1045 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -07001046 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1048 * keep the device (and hence Wi-Fi) awake.
1049 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1050 * being made
1051 * @return {@code true} if {@code pluggedType} indicates that the device is
1052 * supposed to stay awake, {@code false} otherwise.
1053 */
1054 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1055 return (stayAwakeConditions & pluggedType) != 0;
1056 }
1057 };
1058
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001059 private synchronized void reportStartWorkSource() {
1060 mTmpWorkSource.clear();
1061 if (mDeviceIdle) {
1062 for (int i=0; i<mLocks.mList.size(); i++) {
1063 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001064 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001065 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001066 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001067 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 private void updateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001071 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
Irfan Sheriff616f3172011-09-11 19:59:01 -07001072 boolean wifiShouldBeStarted;
1073
1074 if (mEmergencyCallbackMode) {
1075 wifiShouldBeStarted = false;
1076 } else {
1077 wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1078 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001079
1080 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001082 }
1083 /* If device is not idle, lockmode cannot be scan only */
1084 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1086 }
1087
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001088 /* Disable tethering when airplane mode is enabled */
Irfan Sheriff658772f2011-03-08 14:52:31 -08001089 if (mAirplaneModeOn.get()) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001090 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001091 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001092
Irfan Sheriff658772f2011-03-08 14:52:31 -08001093 if (shouldWifiBeEnabled()) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001094 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001095 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001096 mWifiStateMachine.setWifiEnabled(true);
1097 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001098 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001099 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001100 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1101 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001103 mWifiStateMachine.requestCmWakeLock();
1104 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001106 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001107 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
1109 }
1110
1111 private void registerForBroadcasts() {
1112 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1114 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1115 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1116 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001117 intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
Irfan Sheriff616f3172011-09-11 19:59:01 -07001118 intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 mContext.registerReceiver(mReceiver, intentFilter);
1120 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 private boolean isAirplaneSensitive() {
1123 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1124 Settings.System.AIRPLANE_MODE_RADIOS);
1125 return airplaneModeRadios == null
1126 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1127 }
1128
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001129 private boolean isAirplaneToggleable() {
1130 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1131 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1132 return toggleableRadios != null
1133 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1134 }
1135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 /**
1137 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1138 * currently on.
1139 * @return {@code true} if airplane mode is on.
1140 */
1141 private boolean isAirplaneModeOn() {
1142 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1143 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1144 }
1145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 @Override
1147 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1148 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1149 != PackageManager.PERMISSION_GRANTED) {
1150 pw.println("Permission Denial: can't dump WifiService from from pid="
1151 + Binder.getCallingPid()
1152 + ", uid=" + Binder.getCallingUid());
1153 return;
1154 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001155 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 pw.println("Stay-awake conditions: " +
1157 Settings.System.getInt(mContext.getContentResolver(),
1158 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1159 pw.println();
1160
1161 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001162 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 pw.println();
1164 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001165 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 if (scanResults != null && scanResults.size() != 0) {
1167 pw.println(" BSSID Frequency RSSI Flags SSID");
1168 for (ScanResult r : scanResults) {
1169 pw.printf(" %17s %9d %5d %-16s %s%n",
1170 r.BSSID,
1171 r.frequency,
1172 r.level,
1173 r.capabilities,
1174 r.SSID == null ? "" : r.SSID);
1175 }
1176 }
1177 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001178 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001179 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001180 mScanLocksAcquired + " scan");
1181 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001182 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001183 mScanLocksReleased + " scan");
1184 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 pw.println("Locks held:");
1186 mLocks.dump(pw);
Isaac Levybc7dfb52011-06-06 15:34:01 -07001187
1188 pw.println();
Isaac Levy654f5092011-07-13 17:41:45 -07001189 pw.println("WifiWatchdogStateMachine dump");
1190 mWifiWatchdogStateMachine.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
1192
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001193 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001194 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1195 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 }
1197
1198 public void binderDied() {
1199 synchronized (mLocks) {
1200 releaseWifiLockLocked(mBinder);
1201 }
1202 }
1203
1204 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001205 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
1207 }
1208
1209 private class LockList {
1210 private List<WifiLock> mList;
1211
1212 private LockList() {
1213 mList = new ArrayList<WifiLock>();
1214 }
1215
1216 private synchronized boolean hasLocks() {
1217 return !mList.isEmpty();
1218 }
1219
1220 private synchronized int getStrongestLockMode() {
1221 if (mList.isEmpty()) {
1222 return WifiManager.WIFI_MODE_FULL;
1223 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001224
1225 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1226 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001228
1229 if (mFullLocksAcquired > mFullLocksReleased) {
1230 return WifiManager.WIFI_MODE_FULL;
1231 }
1232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 return WifiManager.WIFI_MODE_SCAN_ONLY;
1234 }
1235
1236 private void addLock(WifiLock lock) {
1237 if (findLockByBinder(lock.mBinder) < 0) {
1238 mList.add(lock);
1239 }
1240 }
1241
1242 private WifiLock removeLock(IBinder binder) {
1243 int index = findLockByBinder(binder);
1244 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001245 WifiLock ret = mList.remove(index);
1246 ret.unlinkDeathRecipient();
1247 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 } else {
1249 return null;
1250 }
1251 }
1252
1253 private int findLockByBinder(IBinder binder) {
1254 int size = mList.size();
1255 for (int i = size - 1; i >= 0; i--)
1256 if (mList.get(i).mBinder == binder)
1257 return i;
1258 return -1;
1259 }
1260
1261 private void dump(PrintWriter pw) {
1262 for (WifiLock l : mList) {
1263 pw.print(" ");
1264 pw.println(l);
1265 }
1266 }
1267 }
1268
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001269 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001270 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001271 return;
1272 }
1273 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1274 pid, uid, null);
1275 }
1276
1277 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001279 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1280 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1281 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1282 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1283 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 return false;
1285 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001286 if (ws != null && ws.size() == 0) {
1287 ws = null;
1288 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001289 if (ws != null) {
1290 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1291 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001292 if (ws == null) {
1293 ws = new WorkSource(Binder.getCallingUid());
1294 }
1295 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 synchronized (mLocks) {
1297 return acquireWifiLockLocked(wifiLock);
1298 }
1299 }
1300
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001301 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1302 switch(wifiLock.mMode) {
1303 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001304 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001305 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1306 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001307 case WifiManager.WIFI_MODE_SCAN_ONLY:
1308 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1309 break;
1310 }
1311 }
1312
1313 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1314 switch(wifiLock.mMode) {
1315 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001316 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001317 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1318 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001319 case WifiManager.WIFI_MODE_SCAN_ONLY:
1320 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1321 break;
1322 }
1323 }
1324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001326 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001329
The Android Open Source Project10592532009-03-18 17:39:46 -07001330 long ident = Binder.clearCallingIdentity();
1331 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001332 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001333 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001334 case WifiManager.WIFI_MODE_FULL:
1335 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001336 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001337 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1338 ++mFullHighPerfLocksAcquired;
1339 break;
1340
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001341 case WifiManager.WIFI_MODE_SCAN_ONLY:
1342 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001343 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001344 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001345
1346 // Be aggressive about adding new locks into the accounted state...
1347 // we want to over-report rather than under-report.
1348 reportStartWorkSource();
1349
1350 updateWifiState();
1351 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001352 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001353 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001354 } finally {
1355 Binder.restoreCallingIdentity(ident);
1356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
1358
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001359 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1360 int uid = Binder.getCallingUid();
1361 int pid = Binder.getCallingPid();
1362 if (ws != null && ws.size() == 0) {
1363 ws = null;
1364 }
1365 if (ws != null) {
1366 enforceWakeSourcePermission(uid, pid);
1367 }
1368 long ident = Binder.clearCallingIdentity();
1369 try {
1370 synchronized (mLocks) {
1371 int index = mLocks.findLockByBinder(lock);
1372 if (index < 0) {
1373 throw new IllegalArgumentException("Wifi lock not active");
1374 }
1375 WifiLock wl = mLocks.mList.get(index);
1376 noteReleaseWifiLock(wl);
1377 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1378 noteAcquireWifiLock(wl);
1379 }
1380 } catch (RemoteException e) {
1381 } finally {
1382 Binder.restoreCallingIdentity(ident);
1383 }
1384 }
1385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 public boolean releaseWifiLock(IBinder lock) {
1387 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1388 synchronized (mLocks) {
1389 return releaseWifiLockLocked(lock);
1390 }
1391 }
1392
1393 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001394 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001395
The Android Open Source Project10592532009-03-18 17:39:46 -07001396 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001397
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001398 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001399
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001400 hadLock = (wifiLock != null);
1401
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001402 long ident = Binder.clearCallingIdentity();
1403 try {
1404 if (hadLock) {
Wink Savillece0ea1f2b2011-10-13 16:55:20 -07001405 noteReleaseWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001406 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001407 case WifiManager.WIFI_MODE_FULL:
1408 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001409 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001410 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1411 ++mFullHighPerfLocksReleased;
1412 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001413 case WifiManager.WIFI_MODE_SCAN_ONLY:
1414 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001415 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001416 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001417 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001418
1419 // TODO - should this only happen if you hadLock?
1420 updateWifiState();
1421
1422 } catch (RemoteException e) {
1423 } finally {
1424 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001425 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001426
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001427 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001429
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001430 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001431 implements IBinder.DeathRecipient {
1432 String mTag;
1433 int mMode;
1434 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001435 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001436
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001437 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001438 super();
1439 mTag = tag;
1440 mMode = mode;
1441 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001442 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001443 try {
1444 mBinder.linkToDeath(this, 0);
1445 } catch (RemoteException e) {
1446 binderDied();
1447 }
1448 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001449
1450 void unlinkDeathRecipient() {
1451 mBinder.unlinkToDeath(this, 0);
1452 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001453 }
1454
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001455 private class Multicaster extends DeathRecipient {
1456 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001457 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001458 }
1459
1460 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001461 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001462 synchronized (mMulticasters) {
1463 int i = mMulticasters.indexOf(this);
1464 if (i != -1) {
1465 removeMulticasterLocked(i, mMode);
1466 }
1467 }
1468 }
1469
1470 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001471 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001472 }
1473
1474 public int getUid() {
1475 return mMode;
1476 }
1477 }
1478
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001479 public void initializeMulticastFiltering() {
1480 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001481
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001482 synchronized (mMulticasters) {
1483 // if anybody had requested filters be off, leave off
1484 if (mMulticasters.size() != 0) {
1485 return;
1486 } else {
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001487 mWifiStateMachine.startFilteringMulticastV4Packets();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001488 }
1489 }
1490 }
1491
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001492 public void acquireMulticastLock(IBinder binder, String tag) {
1493 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001494
1495 synchronized (mMulticasters) {
1496 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001497 mMulticasters.add(new Multicaster(tag, binder));
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001498 // Note that we could call stopFilteringMulticastV4Packets only when
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001499 // our new size == 1 (first call), but this function won't
1500 // be called often and by making the stopPacket call each
1501 // time we're less fragile and self-healing.
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001502 mWifiStateMachine.stopFilteringMulticastV4Packets();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001503 }
1504
1505 int uid = Binder.getCallingUid();
1506 Long ident = Binder.clearCallingIdentity();
1507 try {
1508 mBatteryStats.noteWifiMulticastEnabled(uid);
1509 } catch (RemoteException e) {
1510 } finally {
1511 Binder.restoreCallingIdentity(ident);
1512 }
1513 }
1514
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001515 public void releaseMulticastLock() {
1516 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001517
1518 int uid = Binder.getCallingUid();
1519 synchronized (mMulticasters) {
1520 mMulticastDisabled++;
1521 int size = mMulticasters.size();
1522 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001523 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001524 if ((m != null) && (m.getUid() == uid)) {
1525 removeMulticasterLocked(i, uid);
1526 }
1527 }
1528 }
1529 }
1530
1531 private void removeMulticasterLocked(int i, int uid)
1532 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001533 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001534
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001535 if (removed != null) {
1536 removed.unlinkDeathRecipient();
1537 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001538 if (mMulticasters.size() == 0) {
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001539 mWifiStateMachine.startFilteringMulticastV4Packets();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001540 }
1541
1542 Long ident = Binder.clearCallingIdentity();
1543 try {
1544 mBatteryStats.noteWifiMulticastDisabled(uid);
1545 } catch (RemoteException e) {
1546 } finally {
1547 Binder.restoreCallingIdentity(ident);
1548 }
1549 }
1550
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001551 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001552 enforceAccessPermission();
1553
1554 synchronized (mMulticasters) {
1555 return (mMulticasters.size() > 0);
1556 }
1557 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001558
Irfan Sheriff227bec42011-02-15 19:30:27 -08001559 /**
1560 * Evaluate if traffic stats polling is needed based on
1561 * connection and screen on status
1562 */
1563 private void evaluateTrafficStatsPolling() {
1564 Message msg;
1565 if (mNetworkInfo.getDetailedState() == DetailedState.CONNECTED && !mScreenOff) {
Irfan Sheriffebe606f2011-02-24 11:39:15 -08001566 msg = Message.obtain(mAsyncServiceHandler,
1567 WifiManager.CMD_ENABLE_TRAFFIC_STATS_POLL, 1, 0);
Irfan Sheriff227bec42011-02-15 19:30:27 -08001568 } else {
Irfan Sheriffebe606f2011-02-24 11:39:15 -08001569 msg = Message.obtain(mAsyncServiceHandler,
1570 WifiManager.CMD_ENABLE_TRAFFIC_STATS_POLL, 0, 0);
Irfan Sheriff227bec42011-02-15 19:30:27 -08001571 }
1572 msg.sendToTarget();
1573 }
1574
1575 private void notifyOnDataActivity() {
1576 long sent, received;
1577 long preTxPkts = mTxPkts, preRxPkts = mRxPkts;
1578 int dataActivity = WifiManager.DATA_ACTIVITY_NONE;
1579
1580 mTxPkts = TrafficStats.getTxPackets(mInterfaceName);
1581 mRxPkts = TrafficStats.getRxPackets(mInterfaceName);
1582
1583 if (preTxPkts > 0 || preRxPkts > 0) {
1584 sent = mTxPkts - preTxPkts;
1585 received = mRxPkts - preRxPkts;
1586 if (sent > 0) {
1587 dataActivity |= WifiManager.DATA_ACTIVITY_OUT;
1588 }
1589 if (received > 0) {
1590 dataActivity |= WifiManager.DATA_ACTIVITY_IN;
1591 }
1592
1593 if (dataActivity != mDataActivity && !mScreenOff) {
1594 mDataActivity = dataActivity;
1595 for (AsyncChannel client : mClients) {
1596 client.sendMessage(WifiManager.DATA_ACTIVITY_NOTIFICATION, mDataActivity);
1597 }
1598 }
1599 }
1600 }
1601
1602
Irfan Sheriff0d255342010-07-28 09:35:20 -07001603 private void checkAndSetNotification() {
1604 // If we shouldn't place a notification on available networks, then
1605 // don't bother doing any of the following
1606 if (!mNotificationEnabled) return;
1607
1608 State state = mNetworkInfo.getState();
1609 if ((state == NetworkInfo.State.DISCONNECTED)
1610 || (state == NetworkInfo.State.UNKNOWN)) {
1611 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001612 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001613 if (scanResults != null) {
1614 int numOpenNetworks = 0;
1615 for (int i = scanResults.size() - 1; i >= 0; i--) {
1616 ScanResult scanResult = scanResults.get(i);
1617
Irfan Sherifffdd5f952011-08-04 16:55:54 -07001618 //A capability of [ESS] represents an open access point
1619 //that is available for an STA to connect
1620 if (scanResult.capabilities != null &&
1621 scanResult.capabilities.equals("[ESS]")) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001622 numOpenNetworks++;
1623 }
1624 }
1625
1626 if (numOpenNetworks > 0) {
1627 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1628 /*
1629 * We've scanned continuously at least
1630 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1631 * probably does not have a remembered network in range,
1632 * since otherwise supplicant would have tried to
1633 * associate and thus resetting this counter.
1634 */
1635 setNotificationVisible(true, numOpenNetworks, false, 0);
1636 }
1637 return;
1638 }
1639 }
1640 }
1641
1642 // No open networks in range, remove the notification
1643 setNotificationVisible(false, 0, false, 0);
1644 }
1645
1646 /**
1647 * Clears variables related to tracking whether a notification has been
1648 * shown recently and clears the current notification.
1649 */
1650 private void resetNotification() {
1651 mNotificationRepeatTime = 0;
1652 mNumScansSinceNetworkStateChange = 0;
1653 setNotificationVisible(false, 0, false, 0);
1654 }
1655
1656 /**
1657 * Display or don't display a notification that there are open Wi-Fi networks.
1658 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1659 * @param numNetworks the number networks seen
1660 * @param force {@code true} to force notification to be shown/not-shown,
1661 * even if it is already shown/not-shown.
1662 * @param delay time in milliseconds after which the notification should be made
1663 * visible or invisible.
1664 */
1665 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1666 int delay) {
1667
1668 // Since we use auto cancel on the notification, when the
1669 // mNetworksAvailableNotificationShown is true, the notification may
1670 // have actually been canceled. However, when it is false we know
1671 // for sure that it is not being shown (it will not be shown any other
1672 // place than here)
1673
1674 // If it should be hidden and it is already hidden, then noop
1675 if (!visible && !mNotificationShown && !force) {
1676 return;
1677 }
1678
1679 NotificationManager notificationManager = (NotificationManager) mContext
1680 .getSystemService(Context.NOTIFICATION_SERVICE);
1681
1682 Message message;
1683 if (visible) {
1684
1685 // Not enough time has passed to show the notification again
1686 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1687 return;
1688 }
1689
1690 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001691 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001692 mNotification = new Notification();
1693 mNotification.when = 0;
1694 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1695 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1696 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1697 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1698 }
1699
1700 CharSequence title = mContext.getResources().getQuantityText(
1701 com.android.internal.R.plurals.wifi_available, numNetworks);
1702 CharSequence details = mContext.getResources().getQuantityText(
1703 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1704 mNotification.tickerText = title;
1705 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1706
1707 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1708
1709 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001710 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001711 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001712 }
1713
Irfan Sheriff0d255342010-07-28 09:35:20 -07001714 mNotificationShown = visible;
1715 }
1716
1717 private class NotificationEnabledSettingObserver extends ContentObserver {
1718
1719 public NotificationEnabledSettingObserver(Handler handler) {
1720 super(handler);
1721 }
1722
1723 public void register() {
1724 ContentResolver cr = mContext.getContentResolver();
1725 cr.registerContentObserver(Settings.Secure.getUriFor(
1726 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1727 mNotificationEnabled = getValue();
1728 }
1729
1730 @Override
1731 public void onChange(boolean selfChange) {
1732 super.onChange(selfChange);
1733
1734 mNotificationEnabled = getValue();
1735 resetNotification();
1736 }
1737
1738 private boolean getValue() {
1739 return Settings.Secure.getInt(mContext.getContentResolver(),
1740 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1741 }
1742 }
1743
1744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745}