blob: 98794c923f7ccd2575483c51b36d2ff504f5540a [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
Irfan Sheriff330b1872012-09-16 12:27:57 -070019import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.app.AlarmManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070021import android.app.Notification;
22import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.app.PendingIntent;
Adam Powelld56b4d12012-09-30 18:27:31 -070024import android.app.TaskStackBuilder;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070025import android.bluetooth.BluetoothAdapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.BroadcastReceiver;
27import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070032import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.net.wifi.IWifiManager;
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -080034import android.net.wifi.ScanResult;
35import android.net.wifi.SupplicantState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.wifi.WifiInfo;
37import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070038import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.net.wifi.WifiConfiguration;
Isaac Levy654f5092011-07-13 17:41:45 -070040import android.net.wifi.WifiWatchdogStateMachine;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080041import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff651cdfc2011-09-07 00:31:20 -070042import android.net.wifi.WpsInfo;
Irfan Sheriffe4c56c92011-01-12 16:33:58 -080043import android.net.wifi.WpsResult;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080044import android.net.ConnectivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070046import android.net.NetworkInfo;
47import android.net.NetworkInfo.State;
Irfan Sheriff227bec42011-02-15 19:30:27 -080048import android.net.NetworkInfo.DetailedState;
49import android.net.TrafficStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070051import android.os.Handler;
Irfan Sheriff227bec42011-02-15 19:30:27 -080052import android.os.Messenger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.HandlerThread;
54import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080055import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070056import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070058import android.os.ServiceManager;
Irfan Sheriff227bec42011-02-15 19:30:27 -080059import android.os.SystemProperties;
Irfan Sheriff330b1872012-09-16 12:27:57 -070060import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070061import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070063import android.text.TextUtils;
Nick Pelly6ccaa542012-06-15 15:22:47 -070064import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080065import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
67import java.util.ArrayList;
Irfan Sheriff8cef0672011-12-13 17:03:59 -080068import java.util.HashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080070import java.util.Set;
Irfan Sheriff658772f2011-03-08 14:52:31 -080071import java.util.concurrent.atomic.AtomicInteger;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070072import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.io.FileDescriptor;
74import java.io.PrintWriter;
75
The Android Open Source Project10592532009-03-18 17:39:46 -070076import com.android.internal.app.IBatteryStats;
Irfan Sheriff616f3172011-09-11 19:59:01 -070077import com.android.internal.telephony.TelephonyIntents;
Wink Saville4b7ba092010-10-20 15:37:41 -070078import com.android.internal.util.AsyncChannel;
The Android Open Source Project10592532009-03-18 17:39:46 -070079import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080080import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082/**
83 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070084 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 *
86 * @hide
87 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070088//TODO: Clean up multiple locks and implement WifiService
89// as a SM to track soft AP/client/adhoc bring up based
90// on device idle state, airplane mode and boot.
91
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092public class WifiService extends IWifiManager.Stub {
93 private static final String TAG = "WifiService";
Dianne Hackborn5fd21692011-06-07 14:09:47 -070094 private static final boolean DBG = false;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070095
Irfan Sheriff0d255342010-07-28 09:35:20 -070096 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
98 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
100 private AlarmManager mAlarmManager;
101 private PendingIntent mIdleIntent;
102 private static final int IDLE_REQUEST = 0;
103 private boolean mScreenOff;
104 private boolean mDeviceIdle;
Irfan Sheriff616f3172011-09-11 19:59:01 -0700105 private boolean mEmergencyCallbackMode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 private int mPluggedType;
107
108 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700109 // some wifi lock statistics
Irfan Sheriff5876a422010-08-12 20:26:23 -0700110 private int mFullHighPerfLocksAcquired;
111 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700112 private int mFullLocksAcquired;
113 private int mFullLocksReleased;
114 private int mScanLocksAcquired;
115 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700116
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700117 private final List<Multicaster> mMulticasters =
118 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700119 private int mMulticastEnabled;
120 private int mMulticastDisabled;
121
The Android Open Source Project10592532009-03-18 17:39:46 -0700122 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800123
Irfan Sheriff227bec42011-02-15 19:30:27 -0800124 private boolean mEnableTrafficStatsPoll = false;
125 private int mTrafficStatsPollToken = 0;
126 private long mTxPkts;
127 private long mRxPkts;
128 /* Tracks last reported data activity */
129 private int mDataActivity;
130 private String mInterfaceName;
131
132 /**
133 * Interval in milliseconds between polling for traffic
134 * statistics
135 */
136 private static final int POLL_TRAFFIC_STATS_INTERVAL_MSECS = 1000;
137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 /**
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700139 * See {@link Settings.Global#WIFI_IDLE_MS}. This is the default value if a
140 * Settings.Global value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 * the approximate point at which the battery drain caused by Wi-Fi
142 * being enabled but not active exceeds the battery drain caused by
143 * re-establishing a connection to the mobile data network.
144 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700145 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 private static final String ACTION_DEVICE_IDLE =
148 "com.android.server.WifiManager.action.DEVICE_IDLE";
149
Irfan Sheriff658772f2011-03-08 14:52:31 -0800150 private static final int WIFI_DISABLED = 0;
151 private static final int WIFI_ENABLED = 1;
152 /* Wifi enabled while in airplane mode */
153 private static final int WIFI_ENABLED_AIRPLANE_OVERRIDE = 2;
Irfan Sheriff31b92e22011-10-03 12:13:20 -0700154 /* Wifi disabled due to airplane mode on */
155 private static final int WIFI_DISABLED_AIRPLANE_ON = 3;
Irfan Sheriff658772f2011-03-08 14:52:31 -0800156
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800157 /* Persisted state that tracks the wifi & airplane interaction from settings */
158 private AtomicInteger mPersistWifiState = new AtomicInteger(WIFI_DISABLED);
159 /* Tracks current airplane mode state */
Irfan Sheriff658772f2011-03-08 14:52:31 -0800160 private AtomicBoolean mAirplaneModeOn = new AtomicBoolean(false);
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800161 /* Tracks whether wifi is enabled from WifiStateMachine's perspective */
162 private boolean mWifiEnabled;
Irfan Sheriff658772f2011-03-08 14:52:31 -0800163
Nick Pelly6ccaa542012-06-15 15:22:47 -0700164 /* The work source (UID) that triggered the current WIFI scan, synchronized
165 * on this */
166 private WorkSource mScanWorkSource;
167
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700168 private boolean mIsReceiverRegistered = false;
169
Irfan Sheriff0d255342010-07-28 09:35:20 -0700170
171 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
172
173 // Variables relating to the 'available networks' notification
174 /**
175 * The icon to show in the 'available networks' notification. This will also
176 * be the ID of the Notification given to the NotificationManager.
177 */
178 private static final int ICON_NETWORKS_AVAILABLE =
179 com.android.internal.R.drawable.stat_notify_wifi_in_range;
180 /**
181 * When a notification is shown, we wait this amount before possibly showing it again.
182 */
183 private final long NOTIFICATION_REPEAT_DELAY_MS;
184 /**
185 * Whether the user has set the setting to show the 'available networks' notification.
186 */
187 private boolean mNotificationEnabled;
188 /**
189 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
190 */
191 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
192 /**
193 * The {@link System#currentTimeMillis()} must be at least this value for us
194 * to show the notification again.
195 */
196 private long mNotificationRepeatTime;
197 /**
198 * The Notification object given to the NotificationManager.
199 */
200 private Notification mNotification;
201 /**
202 * Whether the notification is being shown, as set by us. That is, if the
203 * user cancels the notification, we will not receive the callback so this
204 * will still be true. We only guarantee if this is false, then the
205 * notification is not showing.
206 */
207 private boolean mNotificationShown;
208 /**
209 * The number of continuous scans that must occur before consider the
210 * supplicant in a scanning state. This allows supplicant to associate with
211 * remembered networks that are in the scan results.
212 */
213 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
214 /**
215 * The number of scans since the last network state change. When this
216 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
217 * supplicant to actually be scanning. When the network state changes to
218 * something other than scanning, we reset this to 0.
219 */
220 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700221
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700222 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700223 * Asynchronous channel to WifiStateMachine
224 */
Irfan Sheriff227bec42011-02-15 19:30:27 -0800225 private AsyncChannel mWifiStateMachineChannel;
Wink Saville4b7ba092010-10-20 15:37:41 -0700226
227 /**
Irfan Sheriff227bec42011-02-15 19:30:27 -0800228 * Clients receiving asynchronous messages
Wink Saville4b7ba092010-10-20 15:37:41 -0700229 */
Irfan Sheriff227bec42011-02-15 19:30:27 -0800230 private List<AsyncChannel> mClients = new ArrayList<AsyncChannel>();
Wink Saville4b7ba092010-10-20 15:37:41 -0700231
Irfan Sheriff227bec42011-02-15 19:30:27 -0800232 /**
233 * Handles client connections
234 */
235 private class AsyncServiceHandler extends Handler {
236
237 AsyncServiceHandler(android.os.Looper looper) {
Wink Saville4b7ba092010-10-20 15:37:41 -0700238 super(looper);
Wink Saville4b7ba092010-10-20 15:37:41 -0700239 }
240
241 @Override
242 public void handleMessage(Message msg) {
243 switch (msg.what) {
244 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
245 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
Irfan Sheriff6bfc8882012-08-29 15:35:57 -0700246 if (DBG) Slog.d(TAG, "New client listening to asynchronous messages");
Irfan Sheriff227bec42011-02-15 19:30:27 -0800247 mClients.add((AsyncChannel) msg.obj);
Wink Saville4b7ba092010-10-20 15:37:41 -0700248 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800249 Slog.e(TAG, "Client connection failure, error=" + msg.arg1);
250 }
251 break;
252 }
Irfan Sheriffc23971b2011-03-04 17:06:31 -0800253 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
254 if (msg.arg1 == AsyncChannel.STATUS_SEND_UNSUCCESSFUL) {
Irfan Sheriff6bfc8882012-08-29 15:35:57 -0700255 if (DBG) Slog.d(TAG, "Send failed, client connection lost");
Irfan Sheriffc23971b2011-03-04 17:06:31 -0800256 } else {
Irfan Sheriff6bfc8882012-08-29 15:35:57 -0700257 if (DBG) Slog.d(TAG, "Client connection lost with reason: " + msg.arg1);
Irfan Sheriffc23971b2011-03-04 17:06:31 -0800258 }
259 mClients.remove((AsyncChannel) msg.obj);
260 break;
261 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800262 case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: {
263 AsyncChannel ac = new AsyncChannel();
264 ac.connect(mContext, this, msg.replyTo);
265 break;
266 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800267 case WifiManager.ENABLE_TRAFFIC_STATS_POLL: {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800268 mEnableTrafficStatsPoll = (msg.arg1 == 1);
269 mTrafficStatsPollToken++;
270 if (mEnableTrafficStatsPoll) {
271 notifyOnDataActivity();
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800272 sendMessageDelayed(Message.obtain(this, WifiManager.TRAFFIC_STATS_POLL,
Irfan Sheriff227bec42011-02-15 19:30:27 -0800273 mTrafficStatsPollToken, 0), POLL_TRAFFIC_STATS_INTERVAL_MSECS);
274 }
275 break;
276 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800277 case WifiManager.TRAFFIC_STATS_POLL: {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800278 if (msg.arg1 == mTrafficStatsPollToken) {
279 notifyOnDataActivity();
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800280 sendMessageDelayed(Message.obtain(this, WifiManager.TRAFFIC_STATS_POLL,
Irfan Sheriff227bec42011-02-15 19:30:27 -0800281 mTrafficStatsPollToken, 0), POLL_TRAFFIC_STATS_INTERVAL_MSECS);
Wink Saville4b7ba092010-10-20 15:37:41 -0700282 }
283 break;
284 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800285 case WifiManager.CONNECT_NETWORK: {
286 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800287 break;
288 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800289 case WifiManager.SAVE_NETWORK: {
290 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800291 break;
292 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800293 case WifiManager.FORGET_NETWORK: {
294 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800295 break;
296 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800297 case WifiManager.START_WPS: {
298 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800299 break;
300 }
Irfan Sheriff86a5f5b2012-02-28 17:03:56 -0800301 case WifiManager.CANCEL_WPS: {
302 mWifiStateMachine.sendMessage(Message.obtain(msg));
303 break;
304 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800305 case WifiManager.DISABLE_NETWORK: {
306 mWifiStateMachine.sendMessage(Message.obtain(msg));
Isaac Levy8dc6a1b2011-07-27 08:00:03 -0700307 break;
308 }
Yuhao Zhengf6307822012-08-14 14:21:25 -0700309 case WifiManager.RSSI_PKTCNT_FETCH: {
310 mWifiStateMachine.sendMessage(Message.obtain(msg));
311 break;
312 }
Wink Saville4b7ba092010-10-20 15:37:41 -0700313 default: {
314 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
315 break;
316 }
317 }
318 }
319 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800320 private AsyncServiceHandler mAsyncServiceHandler;
321
322 /**
323 * Handles interaction with WifiStateMachine
324 */
325 private class WifiStateMachineHandler extends Handler {
326 private AsyncChannel mWsmChannel;
327
328 WifiStateMachineHandler(android.os.Looper looper) {
329 super(looper);
330 mWsmChannel = new AsyncChannel();
331 mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
332 }
333
334 @Override
335 public void handleMessage(Message msg) {
336 switch (msg.what) {
337 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
338 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
339 mWifiStateMachineChannel = mWsmChannel;
340 } else {
341 Slog.e(TAG, "WifiStateMachine connection failure, error=" + msg.arg1);
342 mWifiStateMachineChannel = null;
343 }
344 break;
345 }
Irfan Sheriff6da83d52011-06-06 12:54:06 -0700346 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
347 Slog.e(TAG, "WifiStateMachine channel lost, msg.arg1 =" + msg.arg1);
348 mWifiStateMachineChannel = null;
349 //Re-establish connection to state machine
350 mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
351 break;
352 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800353 default: {
354 Slog.d(TAG, "WifiStateMachineHandler.handleMessage ignoring msg=" + msg);
355 break;
356 }
357 }
358 }
359 }
360 WifiStateMachineHandler mWifiStateMachineHandler;
Wink Saville4b7ba092010-10-20 15:37:41 -0700361
362 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700363 * Temporary for computing UIDS that are responsible for starting WIFI.
364 * Protected by mWifiStateTracker lock.
365 */
366 private final WorkSource mTmpWorkSource = new WorkSource();
Isaac Levy654f5092011-07-13 17:41:45 -0700367 private WifiWatchdogStateMachine mWifiWatchdogStateMachine;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700368
369 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 mContext = context;
Irfan Sheriff227bec42011-02-15 19:30:27 -0800371
372 mInterfaceName = SystemProperties.get("wifi.interface", "wlan0");
373
374 mWifiStateMachine = new WifiStateMachine(mContext, mInterfaceName);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700375 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700376 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
379 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
380 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 mContext.registerReceiver(
383 new BroadcastReceiver() {
384 @Override
385 public void onReceive(Context context, Intent intent) {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800386 mAirplaneModeOn.set(isAirplaneModeOn());
Irfan Sheriff42d73bb2012-05-17 14:14:44 -0700387 handleAirplaneModeToggled(mAirplaneModeOn.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 updateWifiState();
389 }
390 },
391 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
392
Irfan Sheriff0d255342010-07-28 09:35:20 -0700393 IntentFilter filter = new IntentFilter();
394 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
395 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
396 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
397
398 mContext.registerReceiver(
399 new BroadcastReceiver() {
400 @Override
401 public void onReceive(Context context, Intent intent) {
402 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800403 int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
404 WifiManager.WIFI_STATE_DISABLED);
405
406 mWifiEnabled = (wifiState == WifiManager.WIFI_STATE_ENABLED);
407
408 // reset & clear notification on any wifi state change
Irfan Sheriff0d255342010-07-28 09:35:20 -0700409 resetNotification();
410 } else if (intent.getAction().equals(
411 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
412 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
413 WifiManager.EXTRA_NETWORK_INFO);
414 // reset & clear notification on a network connect & disconnect
415 switch(mNetworkInfo.getDetailedState()) {
416 case CONNECTED:
417 case DISCONNECTED:
Irfan Sheriffda6da092012-08-16 12:49:23 -0700418 case CAPTIVE_PORTAL_CHECK:
Irfan Sheriff227bec42011-02-15 19:30:27 -0800419 evaluateTrafficStatsPolling();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700420 resetNotification();
421 break;
422 }
423 } else if (intent.getAction().equals(
424 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
Nick Pelly6ccaa542012-06-15 15:22:47 -0700425 noteScanEnd();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700426 checkAndSetNotification();
427 }
428 }
429 }, filter);
430
Irfan Sheriff227bec42011-02-15 19:30:27 -0800431 HandlerThread wifiThread = new HandlerThread("WifiService");
432 wifiThread.start();
433 mAsyncServiceHandler = new AsyncServiceHandler(wifiThread.getLooper());
434 mWifiStateMachineHandler = new WifiStateMachineHandler(wifiThread.getLooper());
435
Irfan Sheriff0d255342010-07-28 09:35:20 -0700436 // Setting is in seconds
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700437 NOTIFICATION_REPEAT_DELAY_MS = Settings.Global.getInt(context.getContentResolver(),
438 Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700439 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
440 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800441 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800442
Nick Pelly6ccaa542012-06-15 15:22:47 -0700443 /** Tell battery stats about a new WIFI scan */
444 private void noteScanStart() {
445 WorkSource scanWorkSource = null;
446 synchronized (WifiService.this) {
447 if (mScanWorkSource != null) {
448 // Scan already in progress, don't add this one to battery stats
449 return;
450 }
451 scanWorkSource = new WorkSource(Binder.getCallingUid());
452 mScanWorkSource = scanWorkSource;
453 }
454
455 long id = Binder.clearCallingIdentity();
456 try {
457 mBatteryStats.noteWifiScanStartedFromSource(scanWorkSource);
458 } catch (RemoteException e) {
459 Log.w(TAG, e);
460 } finally {
461 Binder.restoreCallingIdentity(id);
462 }
463 }
464
465 /** Tell battery stats that the current WIFI scan has completed */
466 private void noteScanEnd() {
467 WorkSource scanWorkSource = null;
468 synchronized (WifiService.this) {
469 scanWorkSource = mScanWorkSource;
470 mScanWorkSource = null;
471 }
472 if (scanWorkSource != null) {
473 try {
474 mBatteryStats.noteWifiScanStoppedFromSource(scanWorkSource);
475 } catch (RemoteException e) {
476 Log.w(TAG, e);
477 }
478 }
479 }
480
Irfan Sheriff7b009782010-03-11 16:37:45 -0800481 /**
482 * Check if Wi-Fi needs to be enabled and start
483 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700484 *
485 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800486 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700487 public void checkAndStartWifi() {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800488 mAirplaneModeOn.set(isAirplaneModeOn());
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800489 mPersistWifiState.set(getPersistedWifiState());
Irfan Sheriff658772f2011-03-08 14:52:31 -0800490 /* Start if Wi-Fi should be enabled or the saved state indicates Wi-Fi was on */
491 boolean wifiEnabled = shouldWifiBeEnabled() || testAndClearWifiSavedState();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800492 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
493 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sherifff03d6202012-05-17 12:33:46 -0700494
495 // If we are already disabled (could be due to airplane mode), avoid changing persist
496 // state here
497 if (wifiEnabled) setWifiEnabled(wifiEnabled);
Isaac Levybc7dfb52011-06-06 15:34:01 -0700498
Isaac Levy654f5092011-07-13 17:41:45 -0700499 mWifiWatchdogStateMachine = WifiWatchdogStateMachine.
500 makeWifiWatchdogStateMachine(mContext);
501
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800502 }
503
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700504 private boolean testAndClearWifiSavedState() {
505 final ContentResolver cr = mContext.getContentResolver();
506 int wifiSavedState = 0;
507 try {
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700508 wifiSavedState = Settings.Global.getInt(cr, Settings.Global.WIFI_SAVED_STATE);
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700509 if(wifiSavedState == 1)
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700510 Settings.Global.putInt(cr, Settings.Global.WIFI_SAVED_STATE, 0);
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700511 } catch (Settings.SettingNotFoundException e) {
512 ;
513 }
514 return (wifiSavedState == 1);
515 }
516
Irfan Sheriff658772f2011-03-08 14:52:31 -0800517 private int getPersistedWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 final ContentResolver cr = mContext.getContentResolver();
519 try {
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700520 return Settings.Global.getInt(cr, Settings.Global.WIFI_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 } catch (Settings.SettingNotFoundException e) {
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700522 Settings.Global.putInt(cr, Settings.Global.WIFI_ON, WIFI_DISABLED);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800523 return WIFI_DISABLED;
524 }
525 }
526
527 private boolean shouldWifiBeEnabled() {
528 if (mAirplaneModeOn.get()) {
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800529 return mPersistWifiState.get() == WIFI_ENABLED_AIRPLANE_OVERRIDE;
Irfan Sheriff658772f2011-03-08 14:52:31 -0800530 } else {
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800531 return mPersistWifiState.get() != WIFI_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 }
533 }
534
Irfan Sheriff42d73bb2012-05-17 14:14:44 -0700535 private void handleWifiToggled(boolean wifiEnabled) {
536 boolean airplaneEnabled = mAirplaneModeOn.get() && isAirplaneToggleable();
537 if (wifiEnabled) {
538 if (airplaneEnabled) {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700539 persistWifiState(WIFI_ENABLED_AIRPLANE_OVERRIDE);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800540 } else {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700541 persistWifiState(WIFI_ENABLED);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800542 }
543 } else {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700544 // When wifi state is disabled, we do not care
545 // if airplane mode is on or not. The scenario of
546 // wifi being disabled due to airplane mode being turned on
547 // is handled handleAirplaneModeToggled()
548 persistWifiState(WIFI_DISABLED);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 }
551
Irfan Sheriff42d73bb2012-05-17 14:14:44 -0700552 private void handleAirplaneModeToggled(boolean airplaneEnabled) {
553 if (airplaneEnabled) {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700554 // Wifi disabled due to airplane on
555 if (mWifiEnabled) {
556 persistWifiState(WIFI_DISABLED_AIRPLANE_ON);
557 }
558 } else {
559 /* On airplane mode disable, restore wifi state if necessary */
560 if (testAndClearWifiSavedState() ||
561 mPersistWifiState.get() == WIFI_ENABLED_AIRPLANE_OVERRIDE) {
562 persistWifiState(WIFI_ENABLED);
563 }
564 }
565 }
566
567 private void persistWifiState(int state) {
568 final ContentResolver cr = mContext.getContentResolver();
569 mPersistWifiState.set(state);
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700570 Settings.Global.putInt(cr, Settings.Global.WIFI_ON, state);
Irfan Sherifff03d6202012-05-17 12:33:46 -0700571 }
Irfan Sheriff658772f2011-03-08 14:52:31 -0800572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 /**
574 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700575 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 */
577 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700578 enforceAccessPermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800579 if (mWifiStateMachineChannel != null) {
580 return mWifiStateMachine.syncPingSupplicant(mWifiStateMachineChannel);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700581 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800582 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700583 return false;
584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 }
586
587 /**
588 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700590 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700592 mWifiStateMachine.startScan(forceActive);
Nick Pelly6ccaa542012-06-15 15:22:47 -0700593 noteScanStart();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 }
595
596 private void enforceAccessPermission() {
597 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
598 "WifiService");
599 }
600
601 private void enforceChangePermission() {
602 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
603 "WifiService");
604
605 }
606
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700607 private void enforceMulticastChangePermission() {
608 mContext.enforceCallingOrSelfPermission(
609 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
610 "WifiService");
611 }
612
Irfan Sheriffda6da092012-08-16 12:49:23 -0700613 private void enforceConnectivityInternalPermission() {
614 mContext.enforceCallingOrSelfPermission(
615 android.Manifest.permission.CONNECTIVITY_INTERNAL,
616 "ConnectivityService");
617 }
618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700620 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
621 * @param enable {@code true} to enable, {@code false} to disable.
622 * @return {@code true} if the enable/disable operation was
623 * started or is already in the queue.
624 */
625 public synchronized boolean setWifiEnabled(boolean enable) {
626 enforceChangePermission();
Irfan Sheriffbd21b782012-05-16 13:13:54 -0700627 Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid()
628 + ", uid=" + Binder.getCallingUid());
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700629 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700630 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700631 }
632
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700633 if (enable) {
634 reportStartWorkSource();
635 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700636 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700637
638 /*
639 * Caller might not have WRITE_SECURE_SETTINGS,
640 * only CHANGE_WIFI_STATE is enforced
641 */
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800642
Irfan Sherifff03d6202012-05-17 12:33:46 -0700643 long ident = Binder.clearCallingIdentity();
Irfan Sheriff3d33a632012-09-16 17:59:13 -0700644 try {
645 handleWifiToggled(enable);
646 } finally {
647 Binder.restoreCallingIdentity(ident);
648 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700649
650 if (enable) {
651 if (!mIsReceiverRegistered) {
652 registerForBroadcasts();
653 mIsReceiverRegistered = true;
654 }
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800655 } else if (mIsReceiverRegistered) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700656 mContext.unregisterReceiver(mReceiver);
657 mIsReceiverRegistered = false;
658 }
659
660 return true;
661 }
662
663 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 * see {@link WifiManager#getWifiState()}
665 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
666 * {@link WifiManager#WIFI_STATE_DISABLING},
667 * {@link WifiManager#WIFI_STATE_ENABLED},
668 * {@link WifiManager#WIFI_STATE_ENABLING},
669 * {@link WifiManager#WIFI_STATE_UNKNOWN}
670 */
671 public int getWifiEnabledState() {
672 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700673 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 }
675
676 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700677 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800678 * @param wifiConfig SSID, security and channel details as
679 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700680 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800681 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700682 public void setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800683 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700684 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800685 }
686
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700687 /**
688 * see {@link WifiManager#getWifiApState()}
689 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
690 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
691 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
692 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
693 * {@link WifiManager#WIFI_AP_STATE_FAILED}
694 */
695 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700696 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700697 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700698 }
699
700 /**
701 * see {@link WifiManager#getWifiApConfiguration()}
702 * @return soft access point configuration
703 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700704 public WifiConfiguration getWifiApConfiguration() {
705 enforceAccessPermission();
Irfan Sheriff9575a1b2011-11-07 10:34:54 -0800706 return mWifiStateMachine.syncGetWifiApConfiguration();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800707 }
708
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700709 /**
710 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
711 * @param wifiConfig WifiConfiguration details for soft access point
712 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700713 public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700714 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800715 if (wifiConfig == null)
716 return;
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700717 mWifiStateMachine.setWifiApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800718 }
719
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800720 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700721 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800722 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700723 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700724 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700725 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800726 }
727
728 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700729 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800730 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700731 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700732 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700733 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800734 }
735
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700736 /**
737 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700738 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700739 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700740 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700741 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800742 }
743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 /**
745 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
746 * @return the list of configured networks
747 */
748 public List<WifiConfiguration> getConfiguredNetworks() {
749 enforceAccessPermission();
Irfan Sheriffe744cff2011-12-11 09:17:50 -0800750 if (mWifiStateMachineChannel != null) {
751 return mWifiStateMachine.syncGetConfiguredNetworks(mWifiStateMachineChannel);
752 } else {
753 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
754 return null;
755 }
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800756 }
757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 /**
759 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
760 * @return the supplicant-assigned identifier for the new or updated
761 * network if the operation succeeds, or {@code -1} if it fails
762 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800763 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800765 if (mWifiStateMachineChannel != null) {
766 return mWifiStateMachine.syncAddOrUpdateNetwork(mWifiStateMachineChannel, config);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700767 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800768 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700769 return -1;
770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 }
772
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700773 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
775 * @param netId the integer that identifies the network configuration
776 * to the supplicant
777 * @return {@code true} if the operation succeeded
778 */
779 public boolean removeNetwork(int netId) {
780 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800781 if (mWifiStateMachineChannel != null) {
782 return mWifiStateMachine.syncRemoveNetwork(mWifiStateMachineChannel, netId);
Wink Saville4b7ba092010-10-20 15:37:41 -0700783 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800784 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Wink Saville4b7ba092010-10-20 15:37:41 -0700785 return false;
786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 }
788
789 /**
790 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
791 * @param netId the integer that identifies the network configuration
792 * to the supplicant
793 * @param disableOthers if true, disable all other networks.
794 * @return {@code true} if the operation succeeded
795 */
796 public boolean enableNetwork(int netId, boolean disableOthers) {
797 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800798 if (mWifiStateMachineChannel != null) {
799 return mWifiStateMachine.syncEnableNetwork(mWifiStateMachineChannel, netId,
800 disableOthers);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700801 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800802 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700803 return false;
804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 }
806
807 /**
808 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
809 * @param netId the integer that identifies the network configuration
810 * to the supplicant
811 * @return {@code true} if the operation succeeded
812 */
813 public boolean disableNetwork(int netId) {
814 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800815 if (mWifiStateMachineChannel != null) {
816 return mWifiStateMachine.syncDisableNetwork(mWifiStateMachineChannel, netId);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700817 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800818 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700819 return false;
820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 }
822
823 /**
824 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
825 * @return the Wi-Fi information, contained in {@link WifiInfo}.
826 */
827 public WifiInfo getConnectionInfo() {
828 enforceAccessPermission();
829 /*
830 * Make sure we have the latest information, by sending
831 * a status request to the supplicant.
832 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700833 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835
836 /**
837 * Return the results of the most recent access point scan, in the form of
838 * a list of {@link ScanResult} objects.
839 * @return the list of results
840 */
841 public List<ScanResult> getScanResults() {
842 enforceAccessPermission();
Irfan Sheriffdb831da2012-09-16 17:39:26 -0700843 int userId = UserHandle.getCallingUserId();
844 long ident = Binder.clearCallingIdentity();
Irfan Sheriff3d33a632012-09-16 17:59:13 -0700845 try {
846 int currentUser = ActivityManager.getCurrentUser();
847 if (userId != currentUser) {
848 return new ArrayList<ScanResult>();
849 } else {
850 return mWifiStateMachine.syncGetScanResultsList();
851 }
852 } finally {
853 Binder.restoreCallingIdentity(ident);
Irfan Sheriff330b1872012-09-16 12:27:57 -0700854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856
857 /**
858 * Tell the supplicant to persist the current list of configured networks.
859 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700860 *
861 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 */
863 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700864 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800866 if (mWifiStateMachineChannel != null) {
867 return mWifiStateMachine.syncSaveConfig(mWifiStateMachineChannel);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700868 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800869 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700870 return false;
871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 }
873
874 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700875 * Set the country code
876 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700877 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700878 *
879 * The persist behavior exists so that wifi can fall back to the last
880 * persisted country code on a restart, when the locale information is
881 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700883 public void setCountryCode(String countryCode, boolean persist) {
884 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
885 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700887 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 }
889
890 /**
Irfan Sheriff36f74132010-11-04 16:57:37 -0700891 * Set the operational frequency band
892 * @param band One of
893 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
894 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
895 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
896 * @param persist {@code true} if the setting should be remembered.
897 *
898 */
899 public void setFrequencyBand(int band, boolean persist) {
900 enforceChangePermission();
901 if (!isDualBandSupported()) return;
902 Slog.i(TAG, "WifiService trying to set frequency band to " + band +
903 " with persist set to " + persist);
904 mWifiStateMachine.setFrequencyBand(band, persist);
905 }
906
907
908 /**
909 * Get the operational frequency band
910 */
911 public int getFrequencyBand() {
912 enforceAccessPermission();
913 return mWifiStateMachine.getFrequencyBand();
914 }
915
916 public boolean isDualBandSupported() {
917 //TODO: Should move towards adding a driver API that checks at runtime
918 return mContext.getResources().getBoolean(
919 com.android.internal.R.bool.config_wifi_dual_band_support);
920 }
921
922 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 * Return the DHCP-assigned addresses from the last successful DHCP request,
924 * if any.
925 * @return the DHCP information
926 */
927 public DhcpInfo getDhcpInfo() {
928 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700929 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 }
931
Irfan Sheriff0d255342010-07-28 09:35:20 -0700932 /**
933 * see {@link android.net.wifi.WifiManager#startWifi}
934 *
935 */
936 public void startWifi() {
Irfan Sheriffda6da092012-08-16 12:49:23 -0700937 enforceConnectivityInternalPermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700938 /* TODO: may be add permissions for access only to connectivity service
939 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
940 * of WifiLock & device idle status unless wifi enabled status is toggled
941 */
942
Irfan Sheriff4494c902011-12-08 10:47:54 -0800943 mWifiStateMachine.setDriverStart(true, mEmergencyCallbackMode);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700944 mWifiStateMachine.reconnectCommand();
945 }
946
Irfan Sheriffda6da092012-08-16 12:49:23 -0700947 public void captivePortalCheckComplete() {
948 enforceConnectivityInternalPermission();
949 mWifiStateMachine.captivePortalCheckComplete();
950 }
951
Irfan Sheriff0d255342010-07-28 09:35:20 -0700952 /**
953 * see {@link android.net.wifi.WifiManager#stopWifi}
954 *
955 */
956 public void stopWifi() {
Irfan Sheriffda6da092012-08-16 12:49:23 -0700957 enforceConnectivityInternalPermission();
958 /*
Irfan Sheriff0d255342010-07-28 09:35:20 -0700959 * TODO: if a stop is issued, wifi is brought up only by startWifi
960 * unless wifi enabled status is toggled
961 */
Irfan Sheriff4494c902011-12-08 10:47:54 -0800962 mWifiStateMachine.setDriverStart(false, mEmergencyCallbackMode);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700963 }
964
Irfan Sheriff0d255342010-07-28 09:35:20 -0700965 /**
966 * see {@link android.net.wifi.WifiManager#addToBlacklist}
967 *
968 */
969 public void addToBlacklist(String bssid) {
970 enforceChangePermission();
971
972 mWifiStateMachine.addToBlacklist(bssid);
973 }
974
975 /**
976 * see {@link android.net.wifi.WifiManager#clearBlacklist}
977 *
978 */
979 public void clearBlacklist() {
980 enforceChangePermission();
981
982 mWifiStateMachine.clearBlacklist();
983 }
984
Irfan Sheriff227bec42011-02-15 19:30:27 -0800985 /**
986 * Get a reference to handler. This is used by a client to establish
987 * an AsyncChannel communication with WifiService
988 */
Irfan Sheriff07573b32012-01-27 21:00:19 -0800989 public Messenger getWifiServiceMessenger() {
Irfan Sheriff35bbe272012-08-23 16:57:43 -0700990 enforceAccessPermission();
991 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800992 return new Messenger(mAsyncServiceHandler);
993 }
994
Irfan Sheriff07573b32012-01-27 21:00:19 -0800995 /** Get a reference to WifiStateMachine handler for AsyncChannel communication */
996 public Messenger getWifiStateMachineMessenger() {
997 enforceAccessPermission();
998 enforceChangePermission();
999 return mWifiStateMachine.getMessenger();
1000 }
1001
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -08001002 /**
1003 * Get the IP and proxy configuration file
1004 */
1005 public String getConfigFile() {
1006 enforceAccessPermission();
1007 return mWifiStateMachine.getConfigFile();
1008 }
1009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1011 @Override
1012 public void onReceive(Context context, Intent intent) {
1013 String action = intent.getAction();
1014
Doug Zongker43866e02010-01-07 12:09:54 -08001015 long idleMillis =
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001016 Settings.Global.getLong(mContext.getContentResolver(),
1017 Settings.Global.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 int stayAwakeConditions =
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001019 Settings.Global.getInt(mContext.getContentResolver(),
1020 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -04001022 if (DBG) {
1023 Slog.d(TAG, "ACTION_SCREEN_ON");
1024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 mAlarmManager.cancel(mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 mScreenOff = false;
Irfan Sheriff227bec42011-02-15 19:30:27 -08001027 evaluateTrafficStatsPolling();
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001028 setDeviceIdleAndUpdateWifi(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -04001030 if (DBG) {
1031 Slog.d(TAG, "ACTION_SCREEN_OFF");
1032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 mScreenOff = true;
Irfan Sheriff227bec42011-02-15 19:30:27 -08001034 evaluateTrafficStatsPolling();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 /*
1036 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1037 * AND the "stay on while plugged in" setting doesn't match the
1038 * current power conditions (i.e, not plugged in, plugged in to USB,
1039 * or plugged in to AC).
1040 */
1041 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001042 //Delayed shutdown if wifi is connected
1043 if (mNetworkInfo.getDetailedState() == DetailedState.CONNECTED) {
1044 if (DBG) Slog.d(TAG, "setting ACTION_DEVICE_IDLE: " + idleMillis + " ms");
1045 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
1046 + idleMillis, mIdleIntent);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001047 } else {
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001048 setDeviceIdleAndUpdateWifi(true);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001052 setDeviceIdleAndUpdateWifi(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1054 /*
1055 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1056 * AND we are transitioning from a state in which the device was supposed
1057 * to stay awake to a state in which it is not supposed to stay awake.
1058 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1059 * the already-set timer.
1060 */
1061 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -04001062 if (DBG) {
1063 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
1064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1066 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1067 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -04001068 if (DBG) {
1069 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
Irfan Sheriff8cef0672011-12-13 17:03:59 -08001073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 mPluggedType = pluggedType;
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001075 } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
1076 int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
1077 BluetoothAdapter.STATE_DISCONNECTED);
1078 mWifiStateMachine.sendBluetoothAdapterStateChange(state);
Irfan Sheriff616f3172011-09-11 19:59:01 -07001079 } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
1080 mEmergencyCallbackMode = intent.getBooleanExtra("phoneinECMState", false);
1081 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 }
1084
1085 /**
1086 * Determines whether the Wi-Fi chipset should stay awake or be put to
1087 * sleep. Looks at the setting for the sleep policy and the current
1088 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001089 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 * @see #shouldDeviceStayAwake(int, int)
1091 */
1092 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
Irfan Sheriff739f6bc2011-01-28 16:43:12 -08001093 //Never sleep as long as the user has not changed the settings
Brian Muramatsu35d323a2012-09-20 19:52:34 -07001094 int wifiSleepPolicy = Settings.Global.getInt(mContext.getContentResolver(),
1095 Settings.Global.WIFI_SLEEP_POLICY,
1096 Settings.Global.WIFI_SLEEP_POLICY_NEVER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097
Brian Muramatsu35d323a2012-09-20 19:52:34 -07001098 if (wifiSleepPolicy == Settings.Global.WIFI_SLEEP_POLICY_NEVER) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 // Never sleep
1100 return true;
Brian Muramatsu35d323a2012-09-20 19:52:34 -07001101 } else if ((wifiSleepPolicy == Settings.Global.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 (pluggedType != 0)) {
1103 // Never sleep while plugged, and we're plugged
1104 return true;
1105 } else {
1106 // Default
1107 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1108 }
1109 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 /**
1112 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1113 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1114 * of {@code 0} isn't really a plugged type, but rather an indication that the
1115 * device isn't plugged in at all, there is no bit value corresponding to a
1116 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -07001117 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1119 * keep the device (and hence Wi-Fi) awake.
1120 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1121 * being made
1122 * @return {@code true} if {@code pluggedType} indicates that the device is
1123 * supposed to stay awake, {@code false} otherwise.
1124 */
1125 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1126 return (stayAwakeConditions & pluggedType) != 0;
1127 }
1128 };
1129
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001130 private void setDeviceIdleAndUpdateWifi(boolean deviceIdle) {
1131 mDeviceIdle = deviceIdle;
1132 reportStartWorkSource();
1133 updateWifiState();
1134 }
1135
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001136 private synchronized void reportStartWorkSource() {
1137 mTmpWorkSource.clear();
1138 if (mDeviceIdle) {
1139 for (int i=0; i<mLocks.mList.size(); i++) {
1140 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001141 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001142 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001143 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001144 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 private void updateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001148 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
Irfan Sheriff616f3172011-09-11 19:59:01 -07001149 boolean wifiShouldBeStarted;
1150
1151 if (mEmergencyCallbackMode) {
1152 wifiShouldBeStarted = false;
1153 } else {
1154 wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1155 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001156
1157 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001159 }
1160 /* If device is not idle, lockmode cannot be scan only */
1161 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1163 }
1164
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001165 /* Disable tethering when airplane mode is enabled */
Irfan Sheriff658772f2011-03-08 14:52:31 -08001166 if (mAirplaneModeOn.get()) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001167 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001168 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001169
Irfan Sheriff658772f2011-03-08 14:52:31 -08001170 if (shouldWifiBeEnabled()) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001171 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001172 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001173 mWifiStateMachine.setWifiEnabled(true);
1174 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001175 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff4494c902011-12-08 10:47:54 -08001176 mWifiStateMachine.setDriverStart(true, mEmergencyCallbackMode);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001177 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1178 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 } else {
Irfan Sheriff4494c902011-12-08 10:47:54 -08001180 mWifiStateMachine.setDriverStart(false, mEmergencyCallbackMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001182 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001183 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185 }
1186
1187 private void registerForBroadcasts() {
1188 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1190 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1191 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1192 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001193 intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
Irfan Sheriff616f3172011-09-11 19:59:01 -07001194 intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 mContext.registerReceiver(mReceiver, intentFilter);
1196 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 private boolean isAirplaneSensitive() {
Christopher Tatec09cdce2012-09-10 16:50:14 -07001199 String airplaneModeRadios = Settings.Global.getString(mContext.getContentResolver(),
1200 Settings.Global.AIRPLANE_MODE_RADIOS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 return airplaneModeRadios == null
Christopher Tatec09cdce2012-09-10 16:50:14 -07001202 || airplaneModeRadios.contains(Settings.Global.RADIO_WIFI);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 }
1204
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001205 private boolean isAirplaneToggleable() {
Christopher Tatec09cdce2012-09-10 16:50:14 -07001206 String toggleableRadios = Settings.Global.getString(mContext.getContentResolver(),
1207 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001208 return toggleableRadios != null
Christopher Tatec09cdce2012-09-10 16:50:14 -07001209 && toggleableRadios.contains(Settings.Global.RADIO_WIFI);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001210 }
1211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 /**
1213 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1214 * currently on.
1215 * @return {@code true} if airplane mode is on.
1216 */
1217 private boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -07001218 return isAirplaneSensitive() && Settings.Global.getInt(mContext.getContentResolver(),
1219 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
1221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 @Override
1223 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1224 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1225 != PackageManager.PERMISSION_GRANTED) {
1226 pw.println("Permission Denial: can't dump WifiService from from pid="
1227 + Binder.getCallingPid()
1228 + ", uid=" + Binder.getCallingUid());
1229 return;
1230 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001231 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 pw.println("Stay-awake conditions: " +
Christopher Tatec09cdce2012-09-10 16:50:14 -07001233 Settings.Global.getInt(mContext.getContentResolver(),
1234 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 pw.println();
1236
1237 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001238 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 pw.println();
1240 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001241 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 if (scanResults != null && scanResults.size() != 0) {
1243 pw.println(" BSSID Frequency RSSI Flags SSID");
1244 for (ScanResult r : scanResults) {
1245 pw.printf(" %17s %9d %5d %-16s %s%n",
1246 r.BSSID,
1247 r.frequency,
1248 r.level,
1249 r.capabilities,
1250 r.SSID == null ? "" : r.SSID);
1251 }
1252 }
1253 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001254 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001255 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001256 mScanLocksAcquired + " scan");
1257 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001258 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001259 mScanLocksReleased + " scan");
1260 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 pw.println("Locks held:");
1262 mLocks.dump(pw);
Isaac Levybc7dfb52011-06-06 15:34:01 -07001263
1264 pw.println();
Isaac Levy654f5092011-07-13 17:41:45 -07001265 pw.println("WifiWatchdogStateMachine dump");
1266 mWifiWatchdogStateMachine.dump(pw);
Irfan Sheriff60792372012-04-16 16:47:10 -07001267 pw.println("WifiStateMachine dump");
1268 mWifiStateMachine.dump(fd, pw, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 }
1270
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001271 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001272 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1273 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 }
1275
1276 public void binderDied() {
1277 synchronized (mLocks) {
1278 releaseWifiLockLocked(mBinder);
1279 }
1280 }
1281
1282 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001283 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 }
1285 }
1286
1287 private class LockList {
1288 private List<WifiLock> mList;
1289
1290 private LockList() {
1291 mList = new ArrayList<WifiLock>();
1292 }
1293
1294 private synchronized boolean hasLocks() {
1295 return !mList.isEmpty();
1296 }
1297
1298 private synchronized int getStrongestLockMode() {
1299 if (mList.isEmpty()) {
1300 return WifiManager.WIFI_MODE_FULL;
1301 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001302
1303 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1304 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001306
1307 if (mFullLocksAcquired > mFullLocksReleased) {
1308 return WifiManager.WIFI_MODE_FULL;
1309 }
1310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 return WifiManager.WIFI_MODE_SCAN_ONLY;
1312 }
1313
1314 private void addLock(WifiLock lock) {
1315 if (findLockByBinder(lock.mBinder) < 0) {
1316 mList.add(lock);
1317 }
1318 }
1319
1320 private WifiLock removeLock(IBinder binder) {
1321 int index = findLockByBinder(binder);
1322 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001323 WifiLock ret = mList.remove(index);
1324 ret.unlinkDeathRecipient();
1325 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 } else {
1327 return null;
1328 }
1329 }
1330
1331 private int findLockByBinder(IBinder binder) {
1332 int size = mList.size();
1333 for (int i = size - 1; i >= 0; i--)
1334 if (mList.get(i).mBinder == binder)
1335 return i;
1336 return -1;
1337 }
1338
1339 private void dump(PrintWriter pw) {
1340 for (WifiLock l : mList) {
1341 pw.print(" ");
1342 pw.println(l);
1343 }
1344 }
1345 }
1346
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001347 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001348 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001349 return;
1350 }
1351 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1352 pid, uid, null);
1353 }
1354
1355 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001357 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1358 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1359 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1360 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1361 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 return false;
1363 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001364 if (ws != null && ws.size() == 0) {
1365 ws = null;
1366 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001367 if (ws != null) {
1368 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1369 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001370 if (ws == null) {
1371 ws = new WorkSource(Binder.getCallingUid());
1372 }
1373 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 synchronized (mLocks) {
1375 return acquireWifiLockLocked(wifiLock);
1376 }
1377 }
1378
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001379 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1380 switch(wifiLock.mMode) {
1381 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001382 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001383 case WifiManager.WIFI_MODE_SCAN_ONLY:
Nick Pelly6ccaa542012-06-15 15:22:47 -07001384 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001385 break;
1386 }
1387 }
1388
1389 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1390 switch(wifiLock.mMode) {
1391 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001392 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001393 case WifiManager.WIFI_MODE_SCAN_ONLY:
Nick Pelly6ccaa542012-06-15 15:22:47 -07001394 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001395 break;
1396 }
1397 }
1398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001400 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001403
The Android Open Source Project10592532009-03-18 17:39:46 -07001404 long ident = Binder.clearCallingIdentity();
1405 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001406 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001407 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001408 case WifiManager.WIFI_MODE_FULL:
1409 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001410 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001411 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1412 ++mFullHighPerfLocksAcquired;
1413 break;
1414
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001415 case WifiManager.WIFI_MODE_SCAN_ONLY:
1416 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001417 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001418 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001419
1420 // Be aggressive about adding new locks into the accounted state...
1421 // we want to over-report rather than under-report.
1422 reportStartWorkSource();
1423
1424 updateWifiState();
1425 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001426 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001427 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001428 } finally {
1429 Binder.restoreCallingIdentity(ident);
1430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 }
1432
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001433 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1434 int uid = Binder.getCallingUid();
1435 int pid = Binder.getCallingPid();
1436 if (ws != null && ws.size() == 0) {
1437 ws = null;
1438 }
1439 if (ws != null) {
1440 enforceWakeSourcePermission(uid, pid);
1441 }
1442 long ident = Binder.clearCallingIdentity();
1443 try {
1444 synchronized (mLocks) {
1445 int index = mLocks.findLockByBinder(lock);
1446 if (index < 0) {
1447 throw new IllegalArgumentException("Wifi lock not active");
1448 }
1449 WifiLock wl = mLocks.mList.get(index);
1450 noteReleaseWifiLock(wl);
1451 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1452 noteAcquireWifiLock(wl);
1453 }
1454 } catch (RemoteException e) {
1455 } finally {
1456 Binder.restoreCallingIdentity(ident);
1457 }
1458 }
1459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 public boolean releaseWifiLock(IBinder lock) {
1461 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1462 synchronized (mLocks) {
1463 return releaseWifiLockLocked(lock);
1464 }
1465 }
1466
1467 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001468 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001469
The Android Open Source Project10592532009-03-18 17:39:46 -07001470 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001471
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001472 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001473
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001474 hadLock = (wifiLock != null);
1475
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001476 long ident = Binder.clearCallingIdentity();
1477 try {
1478 if (hadLock) {
Wink Savillece0ea1f2b2011-10-13 16:55:20 -07001479 noteReleaseWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001480 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001481 case WifiManager.WIFI_MODE_FULL:
1482 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001483 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001484 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1485 ++mFullHighPerfLocksReleased;
1486 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001487 case WifiManager.WIFI_MODE_SCAN_ONLY:
1488 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001489 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001490 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001491 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001492
1493 // TODO - should this only happen if you hadLock?
1494 updateWifiState();
1495
1496 } catch (RemoteException e) {
1497 } finally {
1498 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001499 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001500
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001501 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001503
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001504 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001505 implements IBinder.DeathRecipient {
1506 String mTag;
1507 int mMode;
1508 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001509 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001510
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001511 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001512 super();
1513 mTag = tag;
1514 mMode = mode;
1515 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001516 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001517 try {
1518 mBinder.linkToDeath(this, 0);
1519 } catch (RemoteException e) {
1520 binderDied();
1521 }
1522 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001523
1524 void unlinkDeathRecipient() {
1525 mBinder.unlinkToDeath(this, 0);
1526 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001527 }
1528
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001529 private class Multicaster extends DeathRecipient {
1530 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001531 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001532 }
1533
1534 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001535 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001536 synchronized (mMulticasters) {
1537 int i = mMulticasters.indexOf(this);
1538 if (i != -1) {
1539 removeMulticasterLocked(i, mMode);
1540 }
1541 }
1542 }
1543
1544 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001545 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001546 }
1547
1548 public int getUid() {
1549 return mMode;
1550 }
1551 }
1552
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001553 public void initializeMulticastFiltering() {
1554 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001555
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001556 synchronized (mMulticasters) {
1557 // if anybody had requested filters be off, leave off
1558 if (mMulticasters.size() != 0) {
1559 return;
1560 } else {
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001561 mWifiStateMachine.startFilteringMulticastV4Packets();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001562 }
1563 }
1564 }
1565
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001566 public void acquireMulticastLock(IBinder binder, String tag) {
1567 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001568
1569 synchronized (mMulticasters) {
1570 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001571 mMulticasters.add(new Multicaster(tag, binder));
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001572 // Note that we could call stopFilteringMulticastV4Packets only when
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001573 // our new size == 1 (first call), but this function won't
1574 // be called often and by making the stopPacket call each
1575 // time we're less fragile and self-healing.
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001576 mWifiStateMachine.stopFilteringMulticastV4Packets();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001577 }
1578
1579 int uid = Binder.getCallingUid();
1580 Long ident = Binder.clearCallingIdentity();
1581 try {
1582 mBatteryStats.noteWifiMulticastEnabled(uid);
1583 } catch (RemoteException e) {
1584 } finally {
1585 Binder.restoreCallingIdentity(ident);
1586 }
1587 }
1588
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001589 public void releaseMulticastLock() {
1590 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001591
1592 int uid = Binder.getCallingUid();
1593 synchronized (mMulticasters) {
1594 mMulticastDisabled++;
1595 int size = mMulticasters.size();
1596 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001597 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001598 if ((m != null) && (m.getUid() == uid)) {
1599 removeMulticasterLocked(i, uid);
1600 }
1601 }
1602 }
1603 }
1604
1605 private void removeMulticasterLocked(int i, int uid)
1606 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001607 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001608
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001609 if (removed != null) {
1610 removed.unlinkDeathRecipient();
1611 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001612 if (mMulticasters.size() == 0) {
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001613 mWifiStateMachine.startFilteringMulticastV4Packets();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001614 }
1615
1616 Long ident = Binder.clearCallingIdentity();
1617 try {
1618 mBatteryStats.noteWifiMulticastDisabled(uid);
1619 } catch (RemoteException e) {
1620 } finally {
1621 Binder.restoreCallingIdentity(ident);
1622 }
1623 }
1624
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001625 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001626 enforceAccessPermission();
1627
1628 synchronized (mMulticasters) {
1629 return (mMulticasters.size() > 0);
1630 }
1631 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001632
Irfan Sheriff227bec42011-02-15 19:30:27 -08001633 /**
1634 * Evaluate if traffic stats polling is needed based on
1635 * connection and screen on status
1636 */
1637 private void evaluateTrafficStatsPolling() {
1638 Message msg;
1639 if (mNetworkInfo.getDetailedState() == DetailedState.CONNECTED && !mScreenOff) {
Irfan Sheriffebe606f2011-02-24 11:39:15 -08001640 msg = Message.obtain(mAsyncServiceHandler,
Irfan Sheriffd3975a92012-02-24 10:54:13 -08001641 WifiManager.ENABLE_TRAFFIC_STATS_POLL, 1, 0);
Irfan Sheriff227bec42011-02-15 19:30:27 -08001642 } else {
Irfan Sheriffebe606f2011-02-24 11:39:15 -08001643 msg = Message.obtain(mAsyncServiceHandler,
Irfan Sheriffd3975a92012-02-24 10:54:13 -08001644 WifiManager.ENABLE_TRAFFIC_STATS_POLL, 0, 0);
Irfan Sheriff227bec42011-02-15 19:30:27 -08001645 }
1646 msg.sendToTarget();
1647 }
1648
1649 private void notifyOnDataActivity() {
1650 long sent, received;
1651 long preTxPkts = mTxPkts, preRxPkts = mRxPkts;
1652 int dataActivity = WifiManager.DATA_ACTIVITY_NONE;
1653
1654 mTxPkts = TrafficStats.getTxPackets(mInterfaceName);
1655 mRxPkts = TrafficStats.getRxPackets(mInterfaceName);
1656
1657 if (preTxPkts > 0 || preRxPkts > 0) {
1658 sent = mTxPkts - preTxPkts;
1659 received = mRxPkts - preRxPkts;
1660 if (sent > 0) {
1661 dataActivity |= WifiManager.DATA_ACTIVITY_OUT;
1662 }
1663 if (received > 0) {
1664 dataActivity |= WifiManager.DATA_ACTIVITY_IN;
1665 }
1666
1667 if (dataActivity != mDataActivity && !mScreenOff) {
1668 mDataActivity = dataActivity;
1669 for (AsyncChannel client : mClients) {
1670 client.sendMessage(WifiManager.DATA_ACTIVITY_NOTIFICATION, mDataActivity);
1671 }
1672 }
1673 }
1674 }
1675
1676
Irfan Sheriff0d255342010-07-28 09:35:20 -07001677 private void checkAndSetNotification() {
1678 // If we shouldn't place a notification on available networks, then
1679 // don't bother doing any of the following
1680 if (!mNotificationEnabled) return;
1681
1682 State state = mNetworkInfo.getState();
1683 if ((state == NetworkInfo.State.DISCONNECTED)
1684 || (state == NetworkInfo.State.UNKNOWN)) {
1685 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001686 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001687 if (scanResults != null) {
1688 int numOpenNetworks = 0;
1689 for (int i = scanResults.size() - 1; i >= 0; i--) {
1690 ScanResult scanResult = scanResults.get(i);
1691
Irfan Sherifffdd5f952011-08-04 16:55:54 -07001692 //A capability of [ESS] represents an open access point
1693 //that is available for an STA to connect
1694 if (scanResult.capabilities != null &&
1695 scanResult.capabilities.equals("[ESS]")) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001696 numOpenNetworks++;
1697 }
1698 }
1699
1700 if (numOpenNetworks > 0) {
1701 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1702 /*
1703 * We've scanned continuously at least
1704 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1705 * probably does not have a remembered network in range,
1706 * since otherwise supplicant would have tried to
1707 * associate and thus resetting this counter.
1708 */
1709 setNotificationVisible(true, numOpenNetworks, false, 0);
1710 }
1711 return;
1712 }
1713 }
1714 }
1715
1716 // No open networks in range, remove the notification
1717 setNotificationVisible(false, 0, false, 0);
1718 }
1719
1720 /**
1721 * Clears variables related to tracking whether a notification has been
1722 * shown recently and clears the current notification.
1723 */
1724 private void resetNotification() {
1725 mNotificationRepeatTime = 0;
1726 mNumScansSinceNetworkStateChange = 0;
1727 setNotificationVisible(false, 0, false, 0);
1728 }
1729
1730 /**
1731 * Display or don't display a notification that there are open Wi-Fi networks.
1732 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1733 * @param numNetworks the number networks seen
1734 * @param force {@code true} to force notification to be shown/not-shown,
1735 * even if it is already shown/not-shown.
1736 * @param delay time in milliseconds after which the notification should be made
1737 * visible or invisible.
1738 */
1739 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1740 int delay) {
1741
1742 // Since we use auto cancel on the notification, when the
1743 // mNetworksAvailableNotificationShown is true, the notification may
1744 // have actually been canceled. However, when it is false we know
1745 // for sure that it is not being shown (it will not be shown any other
1746 // place than here)
1747
1748 // If it should be hidden and it is already hidden, then noop
1749 if (!visible && !mNotificationShown && !force) {
1750 return;
1751 }
1752
1753 NotificationManager notificationManager = (NotificationManager) mContext
1754 .getSystemService(Context.NOTIFICATION_SERVICE);
1755
1756 Message message;
1757 if (visible) {
1758
1759 // Not enough time has passed to show the notification again
1760 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1761 return;
1762 }
1763
1764 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001765 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001766 mNotification = new Notification();
1767 mNotification.when = 0;
1768 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1769 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
Adam Powelld56b4d12012-09-30 18:27:31 -07001770 mNotification.contentIntent = TaskStackBuilder.create(mContext)
1771 .addNextIntentWithParentStack(
1772 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK))
1773 .getPendingIntent(0, 0, null, UserHandle.CURRENT);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001774 }
1775
1776 CharSequence title = mContext.getResources().getQuantityText(
1777 com.android.internal.R.plurals.wifi_available, numNetworks);
1778 CharSequence details = mContext.getResources().getQuantityText(
1779 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1780 mNotification.tickerText = title;
1781 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1782
1783 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1784
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001785 notificationManager.notifyAsUser(null, ICON_NETWORKS_AVAILABLE, mNotification,
1786 UserHandle.ALL);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001787 } else {
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001788 notificationManager.cancelAsUser(null, ICON_NETWORKS_AVAILABLE, UserHandle.ALL);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001789 }
1790
Irfan Sheriff0d255342010-07-28 09:35:20 -07001791 mNotificationShown = visible;
1792 }
1793
1794 private class NotificationEnabledSettingObserver extends ContentObserver {
1795
1796 public NotificationEnabledSettingObserver(Handler handler) {
1797 super(handler);
1798 }
1799
1800 public void register() {
1801 ContentResolver cr = mContext.getContentResolver();
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001802 cr.registerContentObserver(Settings.Global.getUriFor(
1803 Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001804 mNotificationEnabled = getValue();
1805 }
1806
1807 @Override
1808 public void onChange(boolean selfChange) {
1809 super.onChange(selfChange);
1810
1811 mNotificationEnabled = getValue();
1812 resetNotification();
1813 }
1814
1815 private boolean getValue() {
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001816 return Settings.Global.getInt(mContext.getContentResolver(),
1817 Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
Irfan Sheriff0d255342010-07-28 09:35:20 -07001818 }
1819 }
1820
1821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822}