blob: ad6eb4dbe2fdc87e1458c51d74009ec8696d31a6 [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;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -080021import android.app.AppOpsManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070022import android.app.Notification;
23import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.app.PendingIntent;
Adam Powelld56b4d12012-09-30 18:27:31 -070025import android.app.TaskStackBuilder;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070026import android.bluetooth.BluetoothAdapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.BroadcastReceiver;
28import android.content.ContentResolver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.net.wifi.IWifiManager;
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -080035import android.net.wifi.ScanResult;
36import android.net.wifi.SupplicantState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.net.wifi.WifiInfo;
38import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070039import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.net.wifi.WifiConfiguration;
Isaac Levy654f5092011-07-13 17:41:45 -070041import android.net.wifi.WifiWatchdogStateMachine;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080042import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff651cdfc2011-09-07 00:31:20 -070043import android.net.wifi.WpsInfo;
Irfan Sheriffe4c56c92011-01-12 16:33:58 -080044import android.net.wifi.WpsResult;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080045import android.net.ConnectivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.net.DhcpInfo;
Robert Greenwalt4717c262012-10-31 14:32:53 -070047import android.net.DhcpResults;
48import android.net.LinkAddress;
49import android.net.LinkProperties;
Irfan Sheriff0d255342010-07-28 09:35:20 -070050import android.net.NetworkInfo;
51import android.net.NetworkInfo.State;
Irfan Sheriff227bec42011-02-15 19:30:27 -080052import android.net.NetworkInfo.DetailedState;
Robert Greenwalt4717c262012-10-31 14:32:53 -070053import android.net.NetworkUtils;
54import android.net.RouteInfo;
Irfan Sheriff227bec42011-02-15 19:30:27 -080055import android.net.TrafficStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070057import android.os.Handler;
Irfan Sheriff227bec42011-02-15 19:30:27 -080058import android.os.Messenger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.HandlerThread;
60import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080061import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070062import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070064import android.os.ServiceManager;
Irfan Sheriff227bec42011-02-15 19:30:27 -080065import android.os.SystemProperties;
Irfan Sheriff330b1872012-09-16 12:27:57 -070066import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070067import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070069import android.text.TextUtils;
Nick Pelly6ccaa542012-06-15 15:22:47 -070070import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080071import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
Irfan Sherifff0afe412012-11-30 14:07:44 -080073import java.io.FileDescriptor;
74import java.io.PrintWriter;
Robert Greenwalt4717c262012-10-31 14:32:53 -070075import java.net.InetAddress;
76import java.net.Inet4Address;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import java.util.ArrayList;
Irfan Sheriff8cef0672011-12-13 17:03:59 -080078import java.util.HashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080080import java.util.Set;
Irfan Sheriff658772f2011-03-08 14:52:31 -080081import java.util.concurrent.atomic.AtomicInteger;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070082import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
The Android Open Source Project10592532009-03-18 17:39:46 -070084import com.android.internal.app.IBatteryStats;
Irfan Sheriff616f3172011-09-11 19:59:01 -070085import com.android.internal.telephony.TelephonyIntents;
Wink Saville4b7ba092010-10-20 15:37:41 -070086import com.android.internal.util.AsyncChannel;
The Android Open Source Project10592532009-03-18 17:39:46 -070087import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080088import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090/**
91 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070092 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 *
94 * @hide
95 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070096//TODO: Clean up multiple locks and implement WifiService
97// as a SM to track soft AP/client/adhoc bring up based
98// on device idle state, airplane mode and boot.
99
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100public class WifiService extends IWifiManager.Stub {
101 private static final String TAG = "WifiService";
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700102 private static final boolean DBG = false;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700103
Irfan Sheriff0d255342010-07-28 09:35:20 -0700104 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
106 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
108 private AlarmManager mAlarmManager;
109 private PendingIntent mIdleIntent;
110 private static final int IDLE_REQUEST = 0;
111 private boolean mScreenOff;
112 private boolean mDeviceIdle;
Irfan Sheriff616f3172011-09-11 19:59:01 -0700113 private boolean mEmergencyCallbackMode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 private int mPluggedType;
115
116 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700117 // some wifi lock statistics
Irfan Sheriff5876a422010-08-12 20:26:23 -0700118 private int mFullHighPerfLocksAcquired;
119 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700120 private int mFullLocksAcquired;
121 private int mFullLocksReleased;
122 private int mScanLocksAcquired;
123 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700124
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700125 private final List<Multicaster> mMulticasters =
126 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700127 private int mMulticastEnabled;
128 private int mMulticastDisabled;
129
The Android Open Source Project10592532009-03-18 17:39:46 -0700130 private final IBatteryStats mBatteryStats;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800131 private final AppOpsManager mAppOps;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800132
Irfan Sheriff227bec42011-02-15 19:30:27 -0800133 private boolean mEnableTrafficStatsPoll = false;
134 private int mTrafficStatsPollToken = 0;
135 private long mTxPkts;
136 private long mRxPkts;
137 /* Tracks last reported data activity */
138 private int mDataActivity;
139 private String mInterfaceName;
140
141 /**
142 * Interval in milliseconds between polling for traffic
143 * statistics
144 */
145 private static final int POLL_TRAFFIC_STATS_INTERVAL_MSECS = 1000;
146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 /**
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700148 * See {@link Settings.Global#WIFI_IDLE_MS}. This is the default value if a
149 * Settings.Global value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 * the approximate point at which the battery drain caused by Wi-Fi
151 * being enabled but not active exceeds the battery drain caused by
152 * re-establishing a connection to the mobile data network.
153 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700154 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 private static final String ACTION_DEVICE_IDLE =
157 "com.android.server.WifiManager.action.DEVICE_IDLE";
158
Irfan Sheriff658772f2011-03-08 14:52:31 -0800159 private static final int WIFI_DISABLED = 0;
160 private static final int WIFI_ENABLED = 1;
161 /* Wifi enabled while in airplane mode */
162 private static final int WIFI_ENABLED_AIRPLANE_OVERRIDE = 2;
Irfan Sheriff31b92e22011-10-03 12:13:20 -0700163 /* Wifi disabled due to airplane mode on */
164 private static final int WIFI_DISABLED_AIRPLANE_ON = 3;
Irfan Sheriff658772f2011-03-08 14:52:31 -0800165
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800166 /* Persisted state that tracks the wifi & airplane interaction from settings */
167 private AtomicInteger mPersistWifiState = new AtomicInteger(WIFI_DISABLED);
168 /* Tracks current airplane mode state */
Irfan Sheriff658772f2011-03-08 14:52:31 -0800169 private AtomicBoolean mAirplaneModeOn = new AtomicBoolean(false);
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800170 /* Tracks whether wifi is enabled from WifiStateMachine's perspective */
171 private boolean mWifiEnabled;
Irfan Sheriff658772f2011-03-08 14:52:31 -0800172
Nick Pelly6ccaa542012-06-15 15:22:47 -0700173 /* The work source (UID) that triggered the current WIFI scan, synchronized
174 * on this */
175 private WorkSource mScanWorkSource;
176
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700177 private boolean mIsReceiverRegistered = false;
178
Irfan Sheriff0d255342010-07-28 09:35:20 -0700179
180 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
181
182 // Variables relating to the 'available networks' notification
183 /**
184 * The icon to show in the 'available networks' notification. This will also
185 * be the ID of the Notification given to the NotificationManager.
186 */
187 private static final int ICON_NETWORKS_AVAILABLE =
188 com.android.internal.R.drawable.stat_notify_wifi_in_range;
189 /**
190 * When a notification is shown, we wait this amount before possibly showing it again.
191 */
192 private final long NOTIFICATION_REPEAT_DELAY_MS;
193 /**
194 * Whether the user has set the setting to show the 'available networks' notification.
195 */
196 private boolean mNotificationEnabled;
197 /**
198 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
199 */
200 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
201 /**
202 * The {@link System#currentTimeMillis()} must be at least this value for us
203 * to show the notification again.
204 */
205 private long mNotificationRepeatTime;
206 /**
207 * The Notification object given to the NotificationManager.
208 */
209 private Notification mNotification;
210 /**
211 * Whether the notification is being shown, as set by us. That is, if the
212 * user cancels the notification, we will not receive the callback so this
213 * will still be true. We only guarantee if this is false, then the
214 * notification is not showing.
215 */
216 private boolean mNotificationShown;
217 /**
218 * The number of continuous scans that must occur before consider the
219 * supplicant in a scanning state. This allows supplicant to associate with
220 * remembered networks that are in the scan results.
221 */
222 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
223 /**
224 * The number of scans since the last network state change. When this
225 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
226 * supplicant to actually be scanning. When the network state changes to
227 * something other than scanning, we reset this to 0.
228 */
229 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700230
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700231 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700232 * Asynchronous channel to WifiStateMachine
233 */
Irfan Sheriff227bec42011-02-15 19:30:27 -0800234 private AsyncChannel mWifiStateMachineChannel;
Wink Saville4b7ba092010-10-20 15:37:41 -0700235
236 /**
Irfan Sheriff227bec42011-02-15 19:30:27 -0800237 * Clients receiving asynchronous messages
Wink Saville4b7ba092010-10-20 15:37:41 -0700238 */
Irfan Sheriff227bec42011-02-15 19:30:27 -0800239 private List<AsyncChannel> mClients = new ArrayList<AsyncChannel>();
Wink Saville4b7ba092010-10-20 15:37:41 -0700240
Irfan Sheriff227bec42011-02-15 19:30:27 -0800241 /**
242 * Handles client connections
243 */
244 private class AsyncServiceHandler extends Handler {
245
246 AsyncServiceHandler(android.os.Looper looper) {
Wink Saville4b7ba092010-10-20 15:37:41 -0700247 super(looper);
Wink Saville4b7ba092010-10-20 15:37:41 -0700248 }
249
250 @Override
251 public void handleMessage(Message msg) {
252 switch (msg.what) {
253 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
254 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
Irfan Sheriff6bfc8882012-08-29 15:35:57 -0700255 if (DBG) Slog.d(TAG, "New client listening to asynchronous messages");
Irfan Sheriff227bec42011-02-15 19:30:27 -0800256 mClients.add((AsyncChannel) msg.obj);
Wink Saville4b7ba092010-10-20 15:37:41 -0700257 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800258 Slog.e(TAG, "Client connection failure, error=" + msg.arg1);
259 }
260 break;
261 }
Irfan Sheriffc23971b2011-03-04 17:06:31 -0800262 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
263 if (msg.arg1 == AsyncChannel.STATUS_SEND_UNSUCCESSFUL) {
Irfan Sheriff6bfc8882012-08-29 15:35:57 -0700264 if (DBG) Slog.d(TAG, "Send failed, client connection lost");
Irfan Sheriffc23971b2011-03-04 17:06:31 -0800265 } else {
Irfan Sheriff6bfc8882012-08-29 15:35:57 -0700266 if (DBG) Slog.d(TAG, "Client connection lost with reason: " + msg.arg1);
Irfan Sheriffc23971b2011-03-04 17:06:31 -0800267 }
268 mClients.remove((AsyncChannel) msg.obj);
269 break;
270 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800271 case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: {
272 AsyncChannel ac = new AsyncChannel();
273 ac.connect(mContext, this, msg.replyTo);
274 break;
275 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800276 case WifiManager.ENABLE_TRAFFIC_STATS_POLL: {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800277 mEnableTrafficStatsPoll = (msg.arg1 == 1);
278 mTrafficStatsPollToken++;
279 if (mEnableTrafficStatsPoll) {
280 notifyOnDataActivity();
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800281 sendMessageDelayed(Message.obtain(this, WifiManager.TRAFFIC_STATS_POLL,
Irfan Sheriff227bec42011-02-15 19:30:27 -0800282 mTrafficStatsPollToken, 0), POLL_TRAFFIC_STATS_INTERVAL_MSECS);
283 }
284 break;
285 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800286 case WifiManager.TRAFFIC_STATS_POLL: {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800287 if (msg.arg1 == mTrafficStatsPollToken) {
288 notifyOnDataActivity();
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800289 sendMessageDelayed(Message.obtain(this, WifiManager.TRAFFIC_STATS_POLL,
Irfan Sheriff227bec42011-02-15 19:30:27 -0800290 mTrafficStatsPollToken, 0), POLL_TRAFFIC_STATS_INTERVAL_MSECS);
Wink Saville4b7ba092010-10-20 15:37:41 -0700291 }
292 break;
293 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800294 case WifiManager.CONNECT_NETWORK: {
295 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800296 break;
297 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800298 case WifiManager.SAVE_NETWORK: {
299 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800300 break;
301 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800302 case WifiManager.FORGET_NETWORK: {
303 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800304 break;
305 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800306 case WifiManager.START_WPS: {
307 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800308 break;
309 }
Irfan Sheriff86a5f5b2012-02-28 17:03:56 -0800310 case WifiManager.CANCEL_WPS: {
311 mWifiStateMachine.sendMessage(Message.obtain(msg));
312 break;
313 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800314 case WifiManager.DISABLE_NETWORK: {
315 mWifiStateMachine.sendMessage(Message.obtain(msg));
Isaac Levy8dc6a1b2011-07-27 08:00:03 -0700316 break;
317 }
Yuhao Zhengf6307822012-08-14 14:21:25 -0700318 case WifiManager.RSSI_PKTCNT_FETCH: {
319 mWifiStateMachine.sendMessage(Message.obtain(msg));
320 break;
321 }
Wink Saville4b7ba092010-10-20 15:37:41 -0700322 default: {
323 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
324 break;
325 }
326 }
327 }
328 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800329 private AsyncServiceHandler mAsyncServiceHandler;
330
331 /**
332 * Handles interaction with WifiStateMachine
333 */
334 private class WifiStateMachineHandler extends Handler {
335 private AsyncChannel mWsmChannel;
336
337 WifiStateMachineHandler(android.os.Looper looper) {
338 super(looper);
339 mWsmChannel = new AsyncChannel();
340 mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
341 }
342
343 @Override
344 public void handleMessage(Message msg) {
345 switch (msg.what) {
346 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
347 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
348 mWifiStateMachineChannel = mWsmChannel;
349 } else {
350 Slog.e(TAG, "WifiStateMachine connection failure, error=" + msg.arg1);
351 mWifiStateMachineChannel = null;
352 }
353 break;
354 }
Irfan Sheriff6da83d52011-06-06 12:54:06 -0700355 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
356 Slog.e(TAG, "WifiStateMachine channel lost, msg.arg1 =" + msg.arg1);
357 mWifiStateMachineChannel = null;
358 //Re-establish connection to state machine
359 mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
360 break;
361 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800362 default: {
363 Slog.d(TAG, "WifiStateMachineHandler.handleMessage ignoring msg=" + msg);
364 break;
365 }
366 }
367 }
368 }
369 WifiStateMachineHandler mWifiStateMachineHandler;
Wink Saville4b7ba092010-10-20 15:37:41 -0700370
371 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700372 * Temporary for computing UIDS that are responsible for starting WIFI.
373 * Protected by mWifiStateTracker lock.
374 */
375 private final WorkSource mTmpWorkSource = new WorkSource();
Isaac Levy654f5092011-07-13 17:41:45 -0700376 private WifiWatchdogStateMachine mWifiWatchdogStateMachine;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700377
378 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 mContext = context;
Irfan Sheriff227bec42011-02-15 19:30:27 -0800380
381 mInterfaceName = SystemProperties.get("wifi.interface", "wlan0");
382
383 mWifiStateMachine = new WifiStateMachine(mContext, mInterfaceName);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700384 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700385 mBatteryStats = BatteryStatsService.getService();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800386 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
389 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
390 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 mContext.registerReceiver(
393 new BroadcastReceiver() {
394 @Override
395 public void onReceive(Context context, Intent intent) {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800396 mAirplaneModeOn.set(isAirplaneModeOn());
Irfan Sheriff42d73bb2012-05-17 14:14:44 -0700397 handleAirplaneModeToggled(mAirplaneModeOn.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 updateWifiState();
399 }
400 },
401 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
402
Irfan Sheriff0d255342010-07-28 09:35:20 -0700403 IntentFilter filter = new IntentFilter();
404 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
405 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
406 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
407
408 mContext.registerReceiver(
409 new BroadcastReceiver() {
410 @Override
411 public void onReceive(Context context, Intent intent) {
412 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800413 int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
414 WifiManager.WIFI_STATE_DISABLED);
415
416 mWifiEnabled = (wifiState == WifiManager.WIFI_STATE_ENABLED);
417
418 // reset & clear notification on any wifi state change
Irfan Sheriff0d255342010-07-28 09:35:20 -0700419 resetNotification();
420 } else if (intent.getAction().equals(
421 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
422 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
423 WifiManager.EXTRA_NETWORK_INFO);
424 // reset & clear notification on a network connect & disconnect
425 switch(mNetworkInfo.getDetailedState()) {
426 case CONNECTED:
427 case DISCONNECTED:
Irfan Sheriffda6da092012-08-16 12:49:23 -0700428 case CAPTIVE_PORTAL_CHECK:
Irfan Sheriff227bec42011-02-15 19:30:27 -0800429 evaluateTrafficStatsPolling();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700430 resetNotification();
431 break;
432 }
433 } else if (intent.getAction().equals(
434 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
Nick Pelly6ccaa542012-06-15 15:22:47 -0700435 noteScanEnd();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700436 checkAndSetNotification();
437 }
438 }
439 }, filter);
440
Irfan Sheriff227bec42011-02-15 19:30:27 -0800441 HandlerThread wifiThread = new HandlerThread("WifiService");
442 wifiThread.start();
443 mAsyncServiceHandler = new AsyncServiceHandler(wifiThread.getLooper());
444 mWifiStateMachineHandler = new WifiStateMachineHandler(wifiThread.getLooper());
445
Irfan Sheriff0d255342010-07-28 09:35:20 -0700446 // Setting is in seconds
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700447 NOTIFICATION_REPEAT_DELAY_MS = Settings.Global.getInt(context.getContentResolver(),
448 Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700449 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
450 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800451 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800452
Nick Pelly6ccaa542012-06-15 15:22:47 -0700453 /** Tell battery stats about a new WIFI scan */
454 private void noteScanStart() {
455 WorkSource scanWorkSource = null;
456 synchronized (WifiService.this) {
457 if (mScanWorkSource != null) {
458 // Scan already in progress, don't add this one to battery stats
459 return;
460 }
461 scanWorkSource = new WorkSource(Binder.getCallingUid());
462 mScanWorkSource = scanWorkSource;
463 }
464
465 long id = Binder.clearCallingIdentity();
466 try {
467 mBatteryStats.noteWifiScanStartedFromSource(scanWorkSource);
468 } catch (RemoteException e) {
469 Log.w(TAG, e);
470 } finally {
471 Binder.restoreCallingIdentity(id);
472 }
473 }
474
475 /** Tell battery stats that the current WIFI scan has completed */
476 private void noteScanEnd() {
477 WorkSource scanWorkSource = null;
478 synchronized (WifiService.this) {
479 scanWorkSource = mScanWorkSource;
480 mScanWorkSource = null;
481 }
482 if (scanWorkSource != null) {
483 try {
484 mBatteryStats.noteWifiScanStoppedFromSource(scanWorkSource);
485 } catch (RemoteException e) {
486 Log.w(TAG, e);
487 }
488 }
489 }
490
Irfan Sheriff7b009782010-03-11 16:37:45 -0800491 /**
492 * Check if Wi-Fi needs to be enabled and start
493 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700494 *
495 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800496 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700497 public void checkAndStartWifi() {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800498 mAirplaneModeOn.set(isAirplaneModeOn());
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800499 mPersistWifiState.set(getPersistedWifiState());
Irfan Sheriff658772f2011-03-08 14:52:31 -0800500 /* Start if Wi-Fi should be enabled or the saved state indicates Wi-Fi was on */
501 boolean wifiEnabled = shouldWifiBeEnabled() || testAndClearWifiSavedState();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800502 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
503 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sherifff03d6202012-05-17 12:33:46 -0700504
505 // If we are already disabled (could be due to airplane mode), avoid changing persist
506 // state here
507 if (wifiEnabled) setWifiEnabled(wifiEnabled);
Isaac Levybc7dfb52011-06-06 15:34:01 -0700508
Isaac Levy654f5092011-07-13 17:41:45 -0700509 mWifiWatchdogStateMachine = WifiWatchdogStateMachine.
510 makeWifiWatchdogStateMachine(mContext);
511
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800512 }
513
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700514 private boolean testAndClearWifiSavedState() {
515 final ContentResolver cr = mContext.getContentResolver();
516 int wifiSavedState = 0;
517 try {
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700518 wifiSavedState = Settings.Global.getInt(cr, Settings.Global.WIFI_SAVED_STATE);
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700519 if(wifiSavedState == 1)
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700520 Settings.Global.putInt(cr, Settings.Global.WIFI_SAVED_STATE, 0);
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700521 } catch (Settings.SettingNotFoundException e) {
522 ;
523 }
524 return (wifiSavedState == 1);
525 }
526
Irfan Sheriff658772f2011-03-08 14:52:31 -0800527 private int getPersistedWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 final ContentResolver cr = mContext.getContentResolver();
529 try {
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700530 return Settings.Global.getInt(cr, Settings.Global.WIFI_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 } catch (Settings.SettingNotFoundException e) {
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700532 Settings.Global.putInt(cr, Settings.Global.WIFI_ON, WIFI_DISABLED);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800533 return WIFI_DISABLED;
534 }
535 }
536
537 private boolean shouldWifiBeEnabled() {
538 if (mAirplaneModeOn.get()) {
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800539 return mPersistWifiState.get() == WIFI_ENABLED_AIRPLANE_OVERRIDE;
Irfan Sheriff658772f2011-03-08 14:52:31 -0800540 } else {
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800541 return mPersistWifiState.get() != WIFI_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 }
543 }
544
Irfan Sheriff42d73bb2012-05-17 14:14:44 -0700545 private void handleWifiToggled(boolean wifiEnabled) {
546 boolean airplaneEnabled = mAirplaneModeOn.get() && isAirplaneToggleable();
547 if (wifiEnabled) {
548 if (airplaneEnabled) {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700549 persistWifiState(WIFI_ENABLED_AIRPLANE_OVERRIDE);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800550 } else {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700551 persistWifiState(WIFI_ENABLED);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800552 }
553 } else {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700554 // When wifi state is disabled, we do not care
555 // if airplane mode is on or not. The scenario of
556 // wifi being disabled due to airplane mode being turned on
557 // is handled handleAirplaneModeToggled()
558 persistWifiState(WIFI_DISABLED);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 }
561
Irfan Sheriff42d73bb2012-05-17 14:14:44 -0700562 private void handleAirplaneModeToggled(boolean airplaneEnabled) {
563 if (airplaneEnabled) {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700564 // Wifi disabled due to airplane on
565 if (mWifiEnabled) {
566 persistWifiState(WIFI_DISABLED_AIRPLANE_ON);
567 }
568 } else {
569 /* On airplane mode disable, restore wifi state if necessary */
570 if (testAndClearWifiSavedState() ||
571 mPersistWifiState.get() == WIFI_ENABLED_AIRPLANE_OVERRIDE) {
572 persistWifiState(WIFI_ENABLED);
573 }
574 }
575 }
576
577 private void persistWifiState(int state) {
578 final ContentResolver cr = mContext.getContentResolver();
579 mPersistWifiState.set(state);
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700580 Settings.Global.putInt(cr, Settings.Global.WIFI_ON, state);
Irfan Sherifff03d6202012-05-17 12:33:46 -0700581 }
Irfan Sheriff658772f2011-03-08 14:52:31 -0800582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 /**
584 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700585 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 */
587 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700588 enforceAccessPermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800589 if (mWifiStateMachineChannel != null) {
590 return mWifiStateMachine.syncPingSupplicant(mWifiStateMachineChannel);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700591 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800592 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700593 return false;
594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 }
596
597 /**
598 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700600 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700602 mWifiStateMachine.startScan(forceActive);
Nick Pelly6ccaa542012-06-15 15:22:47 -0700603 noteScanStart();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 }
605
606 private void enforceAccessPermission() {
607 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
608 "WifiService");
609 }
610
611 private void enforceChangePermission() {
612 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
613 "WifiService");
614
615 }
616
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700617 private void enforceMulticastChangePermission() {
618 mContext.enforceCallingOrSelfPermission(
619 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
620 "WifiService");
621 }
622
Irfan Sheriffda6da092012-08-16 12:49:23 -0700623 private void enforceConnectivityInternalPermission() {
624 mContext.enforceCallingOrSelfPermission(
625 android.Manifest.permission.CONNECTIVITY_INTERNAL,
626 "ConnectivityService");
627 }
628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700630 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
631 * @param enable {@code true} to enable, {@code false} to disable.
632 * @return {@code true} if the enable/disable operation was
633 * started or is already in the queue.
634 */
635 public synchronized boolean setWifiEnabled(boolean enable) {
636 enforceChangePermission();
Irfan Sheriffbd21b782012-05-16 13:13:54 -0700637 Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid()
638 + ", uid=" + Binder.getCallingUid());
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700639 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700640 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700641 }
642
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700643 if (enable) {
644 reportStartWorkSource();
645 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700646 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700647
648 /*
649 * Caller might not have WRITE_SECURE_SETTINGS,
650 * only CHANGE_WIFI_STATE is enforced
651 */
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800652
Irfan Sherifff03d6202012-05-17 12:33:46 -0700653 long ident = Binder.clearCallingIdentity();
Irfan Sheriff3d33a632012-09-16 17:59:13 -0700654 try {
655 handleWifiToggled(enable);
656 } finally {
657 Binder.restoreCallingIdentity(ident);
658 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700659
660 if (enable) {
661 if (!mIsReceiverRegistered) {
662 registerForBroadcasts();
663 mIsReceiverRegistered = true;
664 }
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800665 } else if (mIsReceiverRegistered) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700666 mContext.unregisterReceiver(mReceiver);
667 mIsReceiverRegistered = false;
668 }
669
670 return true;
671 }
672
673 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 * see {@link WifiManager#getWifiState()}
675 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
676 * {@link WifiManager#WIFI_STATE_DISABLING},
677 * {@link WifiManager#WIFI_STATE_ENABLED},
678 * {@link WifiManager#WIFI_STATE_ENABLING},
679 * {@link WifiManager#WIFI_STATE_UNKNOWN}
680 */
681 public int getWifiEnabledState() {
682 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700683 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 }
685
686 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700687 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800688 * @param wifiConfig SSID, security and channel details as
689 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700690 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800691 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700692 public void setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800693 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700694 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800695 }
696
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700697 /**
698 * see {@link WifiManager#getWifiApState()}
699 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
700 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
701 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
702 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
703 * {@link WifiManager#WIFI_AP_STATE_FAILED}
704 */
705 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700706 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700707 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700708 }
709
710 /**
711 * see {@link WifiManager#getWifiApConfiguration()}
712 * @return soft access point configuration
713 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700714 public WifiConfiguration getWifiApConfiguration() {
715 enforceAccessPermission();
Irfan Sheriff9575a1b2011-11-07 10:34:54 -0800716 return mWifiStateMachine.syncGetWifiApConfiguration();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800717 }
718
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700719 /**
720 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
721 * @param wifiConfig WifiConfiguration details for soft access point
722 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700723 public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700724 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800725 if (wifiConfig == null)
726 return;
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700727 mWifiStateMachine.setWifiApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800728 }
729
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800730 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700731 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800732 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700733 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700734 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700735 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800736 }
737
738 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700739 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800740 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700741 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700742 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700743 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800744 }
745
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700746 /**
747 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700748 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700749 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700750 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700751 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800752 }
753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 /**
755 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
756 * @return the list of configured networks
757 */
758 public List<WifiConfiguration> getConfiguredNetworks() {
759 enforceAccessPermission();
Irfan Sheriffe744cff2011-12-11 09:17:50 -0800760 if (mWifiStateMachineChannel != null) {
761 return mWifiStateMachine.syncGetConfiguredNetworks(mWifiStateMachineChannel);
762 } else {
763 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
764 return null;
765 }
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800766 }
767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 /**
769 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
770 * @return the supplicant-assigned identifier for the new or updated
771 * network if the operation succeeds, or {@code -1} if it fails
772 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800773 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800775 if (mWifiStateMachineChannel != null) {
776 return mWifiStateMachine.syncAddOrUpdateNetwork(mWifiStateMachineChannel, config);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700777 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800778 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700779 return -1;
780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 }
782
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700783 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
785 * @param netId the integer that identifies the network configuration
786 * to the supplicant
787 * @return {@code true} if the operation succeeded
788 */
789 public boolean removeNetwork(int netId) {
790 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800791 if (mWifiStateMachineChannel != null) {
792 return mWifiStateMachine.syncRemoveNetwork(mWifiStateMachineChannel, netId);
Wink Saville4b7ba092010-10-20 15:37:41 -0700793 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800794 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Wink Saville4b7ba092010-10-20 15:37:41 -0700795 return false;
796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 }
798
799 /**
800 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
801 * @param netId the integer that identifies the network configuration
802 * to the supplicant
803 * @param disableOthers if true, disable all other networks.
804 * @return {@code true} if the operation succeeded
805 */
806 public boolean enableNetwork(int netId, boolean disableOthers) {
807 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800808 if (mWifiStateMachineChannel != null) {
809 return mWifiStateMachine.syncEnableNetwork(mWifiStateMachineChannel, netId,
810 disableOthers);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700811 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800812 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700813 return false;
814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
816
817 /**
818 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
819 * @param netId the integer that identifies the network configuration
820 * to the supplicant
821 * @return {@code true} if the operation succeeded
822 */
823 public boolean disableNetwork(int netId) {
824 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800825 if (mWifiStateMachineChannel != null) {
826 return mWifiStateMachine.syncDisableNetwork(mWifiStateMachineChannel, netId);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700827 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800828 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700829 return false;
830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 }
832
833 /**
834 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
835 * @return the Wi-Fi information, contained in {@link WifiInfo}.
836 */
837 public WifiInfo getConnectionInfo() {
838 enforceAccessPermission();
839 /*
840 * Make sure we have the latest information, by sending
841 * a status request to the supplicant.
842 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700843 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845
846 /**
847 * Return the results of the most recent access point scan, in the form of
848 * a list of {@link ScanResult} objects.
849 * @return the list of results
850 */
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800851 public List<ScanResult> getScanResults(String callingPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 enforceAccessPermission();
Irfan Sheriffdb831da2012-09-16 17:39:26 -0700853 int userId = UserHandle.getCallingUserId();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800854 int uid = Binder.getCallingUid();
Irfan Sheriffdb831da2012-09-16 17:39:26 -0700855 long ident = Binder.clearCallingIdentity();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800856 if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
857 != AppOpsManager.MODE_ALLOWED) {
858 return new ArrayList<ScanResult>();
859 }
Irfan Sheriff3d33a632012-09-16 17:59:13 -0700860 try {
861 int currentUser = ActivityManager.getCurrentUser();
862 if (userId != currentUser) {
863 return new ArrayList<ScanResult>();
864 } else {
865 return mWifiStateMachine.syncGetScanResultsList();
866 }
867 } finally {
868 Binder.restoreCallingIdentity(ident);
Irfan Sheriff330b1872012-09-16 12:27:57 -0700869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 }
871
872 /**
873 * Tell the supplicant to persist the current list of configured networks.
874 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700875 *
876 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 */
878 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700879 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800881 if (mWifiStateMachineChannel != null) {
882 return mWifiStateMachine.syncSaveConfig(mWifiStateMachineChannel);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700883 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800884 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700885 return false;
886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 }
888
889 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700890 * Set the country code
891 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700892 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700893 *
894 * The persist behavior exists so that wifi can fall back to the last
895 * persisted country code on a restart, when the locale information is
896 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700898 public void setCountryCode(String countryCode, boolean persist) {
899 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
900 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700902 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 }
904
905 /**
Irfan Sheriff36f74132010-11-04 16:57:37 -0700906 * Set the operational frequency band
907 * @param band One of
908 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
909 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
910 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
911 * @param persist {@code true} if the setting should be remembered.
912 *
913 */
914 public void setFrequencyBand(int band, boolean persist) {
915 enforceChangePermission();
916 if (!isDualBandSupported()) return;
917 Slog.i(TAG, "WifiService trying to set frequency band to " + band +
918 " with persist set to " + persist);
919 mWifiStateMachine.setFrequencyBand(band, persist);
920 }
921
922
923 /**
924 * Get the operational frequency band
925 */
926 public int getFrequencyBand() {
927 enforceAccessPermission();
928 return mWifiStateMachine.getFrequencyBand();
929 }
930
931 public boolean isDualBandSupported() {
932 //TODO: Should move towards adding a driver API that checks at runtime
933 return mContext.getResources().getBoolean(
934 com.android.internal.R.bool.config_wifi_dual_band_support);
935 }
936
937 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 * Return the DHCP-assigned addresses from the last successful DHCP request,
939 * if any.
940 * @return the DHCP information
Robert Greenwalt4717c262012-10-31 14:32:53 -0700941 * @deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 */
943 public DhcpInfo getDhcpInfo() {
944 enforceAccessPermission();
Robert Greenwalt4717c262012-10-31 14:32:53 -0700945 DhcpResults dhcpResults = mWifiStateMachine.syncGetDhcpResults();
946 if (dhcpResults.linkProperties == null) return null;
947
948 DhcpInfo info = new DhcpInfo();
949 for (LinkAddress la : dhcpResults.linkProperties.getLinkAddresses()) {
950 InetAddress addr = la.getAddress();
951 if (addr instanceof Inet4Address) {
952 info.ipAddress = NetworkUtils.inetAddressToInt((Inet4Address)addr);
953 break;
954 }
955 }
956 for (RouteInfo r : dhcpResults.linkProperties.getRoutes()) {
957 if (r.isDefaultRoute()) {
958 InetAddress gateway = r.getGateway();
959 if (gateway instanceof Inet4Address) {
960 info.gateway = NetworkUtils.inetAddressToInt((Inet4Address)gateway);
961 }
962 } else if (r.isHostRoute()) {
963 LinkAddress dest = r.getDestination();
964 if (dest.getAddress() instanceof Inet4Address) {
965 info.netmask = NetworkUtils.prefixLengthToNetmaskInt(
966 dest.getNetworkPrefixLength());
967 }
968 }
969 }
970 int dnsFound = 0;
971 for (InetAddress dns : dhcpResults.linkProperties.getDnses()) {
972 if (dns instanceof Inet4Address) {
973 if (dnsFound == 0) {
974 info.dns1 = NetworkUtils.inetAddressToInt((Inet4Address)dns);
975 } else {
976 info.dns2 = NetworkUtils.inetAddressToInt((Inet4Address)dns);
977 }
978 if (++dnsFound > 1) break;
979 }
980 }
981 InetAddress serverAddress = dhcpResults.serverAddress;
982 if (serverAddress instanceof Inet4Address) {
983 info.serverAddress = NetworkUtils.inetAddressToInt((Inet4Address)serverAddress);
984 }
985 info.leaseDuration = dhcpResults.leaseDuration;
986
987 return info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
989
Irfan Sheriff0d255342010-07-28 09:35:20 -0700990 /**
991 * see {@link android.net.wifi.WifiManager#startWifi}
992 *
993 */
994 public void startWifi() {
Irfan Sheriffda6da092012-08-16 12:49:23 -0700995 enforceConnectivityInternalPermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700996 /* TODO: may be add permissions for access only to connectivity service
997 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
998 * of WifiLock & device idle status unless wifi enabled status is toggled
999 */
1000
Irfan Sheriff4494c902011-12-08 10:47:54 -08001001 mWifiStateMachine.setDriverStart(true, mEmergencyCallbackMode);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001002 mWifiStateMachine.reconnectCommand();
1003 }
1004
Irfan Sheriffda6da092012-08-16 12:49:23 -07001005 public void captivePortalCheckComplete() {
1006 enforceConnectivityInternalPermission();
1007 mWifiStateMachine.captivePortalCheckComplete();
1008 }
1009
Irfan Sheriff0d255342010-07-28 09:35:20 -07001010 /**
1011 * see {@link android.net.wifi.WifiManager#stopWifi}
1012 *
1013 */
1014 public void stopWifi() {
Irfan Sheriffda6da092012-08-16 12:49:23 -07001015 enforceConnectivityInternalPermission();
1016 /*
Irfan Sheriff0d255342010-07-28 09:35:20 -07001017 * TODO: if a stop is issued, wifi is brought up only by startWifi
1018 * unless wifi enabled status is toggled
1019 */
Irfan Sheriff4494c902011-12-08 10:47:54 -08001020 mWifiStateMachine.setDriverStart(false, mEmergencyCallbackMode);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001021 }
1022
Irfan Sheriff0d255342010-07-28 09:35:20 -07001023 /**
1024 * see {@link android.net.wifi.WifiManager#addToBlacklist}
1025 *
1026 */
1027 public void addToBlacklist(String bssid) {
1028 enforceChangePermission();
1029
1030 mWifiStateMachine.addToBlacklist(bssid);
1031 }
1032
1033 /**
1034 * see {@link android.net.wifi.WifiManager#clearBlacklist}
1035 *
1036 */
1037 public void clearBlacklist() {
1038 enforceChangePermission();
1039
1040 mWifiStateMachine.clearBlacklist();
1041 }
1042
Irfan Sheriff227bec42011-02-15 19:30:27 -08001043 /**
1044 * Get a reference to handler. This is used by a client to establish
1045 * an AsyncChannel communication with WifiService
1046 */
Irfan Sheriff07573b32012-01-27 21:00:19 -08001047 public Messenger getWifiServiceMessenger() {
Irfan Sheriff35bbe272012-08-23 16:57:43 -07001048 enforceAccessPermission();
1049 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -08001050 return new Messenger(mAsyncServiceHandler);
1051 }
1052
Irfan Sheriff07573b32012-01-27 21:00:19 -08001053 /** Get a reference to WifiStateMachine handler for AsyncChannel communication */
1054 public Messenger getWifiStateMachineMessenger() {
1055 enforceAccessPermission();
1056 enforceChangePermission();
1057 return mWifiStateMachine.getMessenger();
1058 }
1059
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -08001060 /**
1061 * Get the IP and proxy configuration file
1062 */
1063 public String getConfigFile() {
1064 enforceAccessPermission();
1065 return mWifiStateMachine.getConfigFile();
1066 }
1067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1069 @Override
1070 public void onReceive(Context context, Intent intent) {
1071 String action = intent.getAction();
1072
Doug Zongker43866e02010-01-07 12:09:54 -08001073 long idleMillis =
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001074 Settings.Global.getLong(mContext.getContentResolver(),
1075 Settings.Global.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 int stayAwakeConditions =
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001077 Settings.Global.getInt(mContext.getContentResolver(),
1078 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -04001080 if (DBG) {
1081 Slog.d(TAG, "ACTION_SCREEN_ON");
1082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 mAlarmManager.cancel(mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 mScreenOff = false;
Irfan Sheriff227bec42011-02-15 19:30:27 -08001085 evaluateTrafficStatsPolling();
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001086 setDeviceIdleAndUpdateWifi(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -04001088 if (DBG) {
1089 Slog.d(TAG, "ACTION_SCREEN_OFF");
1090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 mScreenOff = true;
Irfan Sheriff227bec42011-02-15 19:30:27 -08001092 evaluateTrafficStatsPolling();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 /*
1094 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1095 * AND the "stay on while plugged in" setting doesn't match the
1096 * current power conditions (i.e, not plugged in, plugged in to USB,
1097 * or plugged in to AC).
1098 */
1099 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001100 //Delayed shutdown if wifi is connected
1101 if (mNetworkInfo.getDetailedState() == DetailedState.CONNECTED) {
1102 if (DBG) Slog.d(TAG, "setting ACTION_DEVICE_IDLE: " + idleMillis + " ms");
1103 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
1104 + idleMillis, mIdleIntent);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001105 } else {
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001106 setDeviceIdleAndUpdateWifi(true);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001110 setDeviceIdleAndUpdateWifi(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1112 /*
1113 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1114 * AND we are transitioning from a state in which the device was supposed
1115 * to stay awake to a state in which it is not supposed to stay awake.
1116 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1117 * the already-set timer.
1118 */
1119 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -04001120 if (DBG) {
1121 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
1122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1124 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1125 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -04001126 if (DBG) {
1127 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 }
Irfan Sheriff8cef0672011-12-13 17:03:59 -08001131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 mPluggedType = pluggedType;
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001133 } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
1134 int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
1135 BluetoothAdapter.STATE_DISCONNECTED);
1136 mWifiStateMachine.sendBluetoothAdapterStateChange(state);
Irfan Sheriff616f3172011-09-11 19:59:01 -07001137 } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
1138 mEmergencyCallbackMode = intent.getBooleanExtra("phoneinECMState", false);
1139 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 }
1142
1143 /**
1144 * Determines whether the Wi-Fi chipset should stay awake or be put to
1145 * sleep. Looks at the setting for the sleep policy and the current
1146 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001147 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 * @see #shouldDeviceStayAwake(int, int)
1149 */
1150 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
Irfan Sheriff739f6bc2011-01-28 16:43:12 -08001151 //Never sleep as long as the user has not changed the settings
Brian Muramatsu35d323a2012-09-20 19:52:34 -07001152 int wifiSleepPolicy = Settings.Global.getInt(mContext.getContentResolver(),
1153 Settings.Global.WIFI_SLEEP_POLICY,
1154 Settings.Global.WIFI_SLEEP_POLICY_NEVER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155
Brian Muramatsu35d323a2012-09-20 19:52:34 -07001156 if (wifiSleepPolicy == Settings.Global.WIFI_SLEEP_POLICY_NEVER) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 // Never sleep
1158 return true;
Brian Muramatsu35d323a2012-09-20 19:52:34 -07001159 } else if ((wifiSleepPolicy == Settings.Global.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 (pluggedType != 0)) {
1161 // Never sleep while plugged, and we're plugged
1162 return true;
1163 } else {
1164 // Default
1165 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1166 }
1167 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 /**
1170 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1171 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1172 * of {@code 0} isn't really a plugged type, but rather an indication that the
1173 * device isn't plugged in at all, there is no bit value corresponding to a
1174 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -07001175 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1177 * keep the device (and hence Wi-Fi) awake.
1178 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1179 * being made
1180 * @return {@code true} if {@code pluggedType} indicates that the device is
1181 * supposed to stay awake, {@code false} otherwise.
1182 */
1183 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1184 return (stayAwakeConditions & pluggedType) != 0;
1185 }
1186 };
1187
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001188 private void setDeviceIdleAndUpdateWifi(boolean deviceIdle) {
1189 mDeviceIdle = deviceIdle;
1190 reportStartWorkSource();
1191 updateWifiState();
1192 }
1193
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001194 private synchronized void reportStartWorkSource() {
1195 mTmpWorkSource.clear();
1196 if (mDeviceIdle) {
1197 for (int i=0; i<mLocks.mList.size(); i++) {
1198 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001199 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001200 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001201 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001202 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 private void updateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001206 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
Irfan Sheriff616f3172011-09-11 19:59:01 -07001207 boolean wifiShouldBeStarted;
1208
1209 if (mEmergencyCallbackMode) {
1210 wifiShouldBeStarted = false;
1211 } else {
1212 wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1213 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001214
1215 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001217 }
1218 /* If device is not idle, lockmode cannot be scan only */
1219 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1221 }
1222
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001223 /* Disable tethering when airplane mode is enabled */
Irfan Sheriff658772f2011-03-08 14:52:31 -08001224 if (mAirplaneModeOn.get()) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001225 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001226 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001227
Irfan Sheriff658772f2011-03-08 14:52:31 -08001228 if (shouldWifiBeEnabled()) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001229 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001230 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001231 mWifiStateMachine.setWifiEnabled(true);
1232 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001233 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff4494c902011-12-08 10:47:54 -08001234 mWifiStateMachine.setDriverStart(true, mEmergencyCallbackMode);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001235 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1236 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 } else {
Irfan Sheriff4494c902011-12-08 10:47:54 -08001238 mWifiStateMachine.setDriverStart(false, mEmergencyCallbackMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001240 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001241 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 }
1243 }
1244
1245 private void registerForBroadcasts() {
1246 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1248 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1249 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1250 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001251 intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
Irfan Sheriff616f3172011-09-11 19:59:01 -07001252 intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 mContext.registerReceiver(mReceiver, intentFilter);
1254 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 private boolean isAirplaneSensitive() {
Christopher Tatec09cdce2012-09-10 16:50:14 -07001257 String airplaneModeRadios = Settings.Global.getString(mContext.getContentResolver(),
1258 Settings.Global.AIRPLANE_MODE_RADIOS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 return airplaneModeRadios == null
Christopher Tatec09cdce2012-09-10 16:50:14 -07001260 || airplaneModeRadios.contains(Settings.Global.RADIO_WIFI);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
1262
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001263 private boolean isAirplaneToggleable() {
Christopher Tatec09cdce2012-09-10 16:50:14 -07001264 String toggleableRadios = Settings.Global.getString(mContext.getContentResolver(),
1265 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001266 return toggleableRadios != null
Christopher Tatec09cdce2012-09-10 16:50:14 -07001267 && toggleableRadios.contains(Settings.Global.RADIO_WIFI);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001268 }
1269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 /**
1271 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1272 * currently on.
1273 * @return {@code true} if airplane mode is on.
1274 */
1275 private boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -07001276 return isAirplaneSensitive() && Settings.Global.getInt(mContext.getContentResolver(),
1277 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 }
1279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 @Override
1281 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1282 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1283 != PackageManager.PERMISSION_GRANTED) {
1284 pw.println("Permission Denial: can't dump WifiService from from pid="
1285 + Binder.getCallingPid()
1286 + ", uid=" + Binder.getCallingUid());
1287 return;
1288 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001289 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 pw.println("Stay-awake conditions: " +
Christopher Tatec09cdce2012-09-10 16:50:14 -07001291 Settings.Global.getInt(mContext.getContentResolver(),
1292 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0));
Irfan Sherifff0afe412012-11-30 14:07:44 -08001293 pw.println("mScreenOff " + mScreenOff);
1294 pw.println("mDeviceIdle " + mDeviceIdle);
1295 pw.println("mPluggedType " + mPluggedType);
1296 pw.println("mEmergencyCallbackMode " + mEmergencyCallbackMode);
1297 pw.println("mMulticastEnabled " + mMulticastEnabled);
1298 pw.println("mMulticastDisabled " + mMulticastDisabled);
1299 pw.println("mEnableTrafficStatsPoll " + mEnableTrafficStatsPoll);
1300 pw.println("mTrafficStatsPollToken " + mTrafficStatsPollToken);
1301 pw.println("mTxPkts " + mTxPkts);
1302 pw.println("mRxPkts " + mRxPkts);
1303 pw.println("mDataActivity " + mDataActivity);
1304 pw.println("mPersistWifiState " + mPersistWifiState.get());
1305 pw.println("mAirplaneModeOn " + mAirplaneModeOn.get());
1306 pw.println("mWifiEnabled " + mWifiEnabled);
1307 pw.println("mNotificationEnabled " + mNotificationEnabled);
1308 pw.println("mNotificationRepeatTime " + mNotificationRepeatTime);
1309 pw.println("mNotificationShown " + mNotificationShown);
1310 pw.println("mNumScansSinceNetworkStateChange " + mNumScansSinceNetworkStateChange);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001313 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 if (scanResults != null && scanResults.size() != 0) {
1315 pw.println(" BSSID Frequency RSSI Flags SSID");
1316 for (ScanResult r : scanResults) {
1317 pw.printf(" %17s %9d %5d %-16s %s%n",
1318 r.BSSID,
1319 r.frequency,
1320 r.level,
1321 r.capabilities,
1322 r.SSID == null ? "" : r.SSID);
1323 }
1324 }
1325 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001326 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001327 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001328 mScanLocksAcquired + " scan");
1329 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001330 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001331 mScanLocksReleased + " scan");
1332 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 pw.println("Locks held:");
1334 mLocks.dump(pw);
Isaac Levybc7dfb52011-06-06 15:34:01 -07001335
Irfan Sherifff0afe412012-11-30 14:07:44 -08001336 mWifiWatchdogStateMachine.dump(fd, pw, args);
Isaac Levybc7dfb52011-06-06 15:34:01 -07001337 pw.println();
Irfan Sheriff60792372012-04-16 16:47:10 -07001338 mWifiStateMachine.dump(fd, pw, args);
Irfan Sherifff0afe412012-11-30 14:07:44 -08001339 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
1341
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001342 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001343 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1344 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 }
1346
1347 public void binderDied() {
1348 synchronized (mLocks) {
1349 releaseWifiLockLocked(mBinder);
1350 }
1351 }
1352
1353 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001354 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 }
1356 }
1357
1358 private class LockList {
1359 private List<WifiLock> mList;
1360
1361 private LockList() {
1362 mList = new ArrayList<WifiLock>();
1363 }
1364
1365 private synchronized boolean hasLocks() {
1366 return !mList.isEmpty();
1367 }
1368
1369 private synchronized int getStrongestLockMode() {
1370 if (mList.isEmpty()) {
1371 return WifiManager.WIFI_MODE_FULL;
1372 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001373
1374 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1375 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001377
1378 if (mFullLocksAcquired > mFullLocksReleased) {
1379 return WifiManager.WIFI_MODE_FULL;
1380 }
1381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 return WifiManager.WIFI_MODE_SCAN_ONLY;
1383 }
1384
1385 private void addLock(WifiLock lock) {
1386 if (findLockByBinder(lock.mBinder) < 0) {
1387 mList.add(lock);
1388 }
1389 }
1390
1391 private WifiLock removeLock(IBinder binder) {
1392 int index = findLockByBinder(binder);
1393 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001394 WifiLock ret = mList.remove(index);
1395 ret.unlinkDeathRecipient();
1396 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 } else {
1398 return null;
1399 }
1400 }
1401
1402 private int findLockByBinder(IBinder binder) {
1403 int size = mList.size();
1404 for (int i = size - 1; i >= 0; i--)
1405 if (mList.get(i).mBinder == binder)
1406 return i;
1407 return -1;
1408 }
1409
1410 private void dump(PrintWriter pw) {
1411 for (WifiLock l : mList) {
1412 pw.print(" ");
1413 pw.println(l);
1414 }
1415 }
1416 }
1417
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001418 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001419 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001420 return;
1421 }
1422 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1423 pid, uid, null);
1424 }
1425
1426 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001428 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1429 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1430 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1431 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1432 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 return false;
1434 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001435 if (ws != null && ws.size() == 0) {
1436 ws = null;
1437 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001438 if (ws != null) {
1439 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1440 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001441 if (ws == null) {
1442 ws = new WorkSource(Binder.getCallingUid());
1443 }
1444 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 synchronized (mLocks) {
1446 return acquireWifiLockLocked(wifiLock);
1447 }
1448 }
1449
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001450 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1451 switch(wifiLock.mMode) {
1452 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001453 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001454 case WifiManager.WIFI_MODE_SCAN_ONLY:
Nick Pelly6ccaa542012-06-15 15:22:47 -07001455 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001456 break;
1457 }
1458 }
1459
1460 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1461 switch(wifiLock.mMode) {
1462 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001463 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001464 case WifiManager.WIFI_MODE_SCAN_ONLY:
Nick Pelly6ccaa542012-06-15 15:22:47 -07001465 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001466 break;
1467 }
1468 }
1469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001471 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001474
The Android Open Source Project10592532009-03-18 17:39:46 -07001475 long ident = Binder.clearCallingIdentity();
1476 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001477 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001478 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001479 case WifiManager.WIFI_MODE_FULL:
1480 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001481 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001482 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1483 ++mFullHighPerfLocksAcquired;
1484 break;
1485
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001486 case WifiManager.WIFI_MODE_SCAN_ONLY:
1487 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001488 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001489 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001490
1491 // Be aggressive about adding new locks into the accounted state...
1492 // we want to over-report rather than under-report.
1493 reportStartWorkSource();
1494
1495 updateWifiState();
1496 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001497 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001498 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001499 } finally {
1500 Binder.restoreCallingIdentity(ident);
1501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
1503
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001504 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1505 int uid = Binder.getCallingUid();
1506 int pid = Binder.getCallingPid();
1507 if (ws != null && ws.size() == 0) {
1508 ws = null;
1509 }
1510 if (ws != null) {
1511 enforceWakeSourcePermission(uid, pid);
1512 }
1513 long ident = Binder.clearCallingIdentity();
1514 try {
1515 synchronized (mLocks) {
1516 int index = mLocks.findLockByBinder(lock);
1517 if (index < 0) {
1518 throw new IllegalArgumentException("Wifi lock not active");
1519 }
1520 WifiLock wl = mLocks.mList.get(index);
1521 noteReleaseWifiLock(wl);
1522 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1523 noteAcquireWifiLock(wl);
1524 }
1525 } catch (RemoteException e) {
1526 } finally {
1527 Binder.restoreCallingIdentity(ident);
1528 }
1529 }
1530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 public boolean releaseWifiLock(IBinder lock) {
1532 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1533 synchronized (mLocks) {
1534 return releaseWifiLockLocked(lock);
1535 }
1536 }
1537
1538 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001539 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001540
The Android Open Source Project10592532009-03-18 17:39:46 -07001541 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001542
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001543 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001544
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001545 hadLock = (wifiLock != null);
1546
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001547 long ident = Binder.clearCallingIdentity();
1548 try {
1549 if (hadLock) {
Wink Savillece0ea1f2b2011-10-13 16:55:20 -07001550 noteReleaseWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001551 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001552 case WifiManager.WIFI_MODE_FULL:
1553 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001554 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001555 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1556 ++mFullHighPerfLocksReleased;
1557 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001558 case WifiManager.WIFI_MODE_SCAN_ONLY:
1559 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001560 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001561 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001562 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001563
1564 // TODO - should this only happen if you hadLock?
1565 updateWifiState();
1566
1567 } catch (RemoteException e) {
1568 } finally {
1569 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001570 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001571
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001572 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001574
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001575 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001576 implements IBinder.DeathRecipient {
1577 String mTag;
1578 int mMode;
1579 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001580 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001581
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001582 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001583 super();
1584 mTag = tag;
1585 mMode = mode;
1586 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001587 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001588 try {
1589 mBinder.linkToDeath(this, 0);
1590 } catch (RemoteException e) {
1591 binderDied();
1592 }
1593 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001594
1595 void unlinkDeathRecipient() {
1596 mBinder.unlinkToDeath(this, 0);
1597 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001598 }
1599
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001600 private class Multicaster extends DeathRecipient {
1601 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001602 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001603 }
1604
1605 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001606 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001607 synchronized (mMulticasters) {
1608 int i = mMulticasters.indexOf(this);
1609 if (i != -1) {
1610 removeMulticasterLocked(i, mMode);
1611 }
1612 }
1613 }
1614
1615 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001616 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001617 }
1618
1619 public int getUid() {
1620 return mMode;
1621 }
1622 }
1623
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001624 public void initializeMulticastFiltering() {
1625 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001626
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001627 synchronized (mMulticasters) {
1628 // if anybody had requested filters be off, leave off
1629 if (mMulticasters.size() != 0) {
1630 return;
1631 } else {
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001632 mWifiStateMachine.startFilteringMulticastV4Packets();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001633 }
1634 }
1635 }
1636
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001637 public void acquireMulticastLock(IBinder binder, String tag) {
1638 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001639
1640 synchronized (mMulticasters) {
1641 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001642 mMulticasters.add(new Multicaster(tag, binder));
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001643 // Note that we could call stopFilteringMulticastV4Packets only when
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001644 // our new size == 1 (first call), but this function won't
1645 // be called often and by making the stopPacket call each
1646 // time we're less fragile and self-healing.
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001647 mWifiStateMachine.stopFilteringMulticastV4Packets();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001648 }
1649
1650 int uid = Binder.getCallingUid();
You Kim2bea5852012-10-23 22:56:51 +09001651 final long ident = Binder.clearCallingIdentity();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001652 try {
1653 mBatteryStats.noteWifiMulticastEnabled(uid);
1654 } catch (RemoteException e) {
1655 } finally {
1656 Binder.restoreCallingIdentity(ident);
1657 }
1658 }
1659
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001660 public void releaseMulticastLock() {
1661 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001662
1663 int uid = Binder.getCallingUid();
1664 synchronized (mMulticasters) {
1665 mMulticastDisabled++;
1666 int size = mMulticasters.size();
1667 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001668 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001669 if ((m != null) && (m.getUid() == uid)) {
1670 removeMulticasterLocked(i, uid);
1671 }
1672 }
1673 }
1674 }
1675
1676 private void removeMulticasterLocked(int i, int uid)
1677 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001678 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001679
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001680 if (removed != null) {
1681 removed.unlinkDeathRecipient();
1682 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001683 if (mMulticasters.size() == 0) {
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001684 mWifiStateMachine.startFilteringMulticastV4Packets();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001685 }
1686
You Kim2bea5852012-10-23 22:56:51 +09001687 final long ident = Binder.clearCallingIdentity();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001688 try {
1689 mBatteryStats.noteWifiMulticastDisabled(uid);
1690 } catch (RemoteException e) {
1691 } finally {
1692 Binder.restoreCallingIdentity(ident);
1693 }
1694 }
1695
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001696 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001697 enforceAccessPermission();
1698
1699 synchronized (mMulticasters) {
1700 return (mMulticasters.size() > 0);
1701 }
1702 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001703
Irfan Sheriff227bec42011-02-15 19:30:27 -08001704 /**
1705 * Evaluate if traffic stats polling is needed based on
1706 * connection and screen on status
1707 */
1708 private void evaluateTrafficStatsPolling() {
1709 Message msg;
1710 if (mNetworkInfo.getDetailedState() == DetailedState.CONNECTED && !mScreenOff) {
Irfan Sheriffebe606f2011-02-24 11:39:15 -08001711 msg = Message.obtain(mAsyncServiceHandler,
Irfan Sheriffd3975a92012-02-24 10:54:13 -08001712 WifiManager.ENABLE_TRAFFIC_STATS_POLL, 1, 0);
Irfan Sheriff227bec42011-02-15 19:30:27 -08001713 } else {
Irfan Sheriffebe606f2011-02-24 11:39:15 -08001714 msg = Message.obtain(mAsyncServiceHandler,
Irfan Sheriffd3975a92012-02-24 10:54:13 -08001715 WifiManager.ENABLE_TRAFFIC_STATS_POLL, 0, 0);
Irfan Sheriff227bec42011-02-15 19:30:27 -08001716 }
1717 msg.sendToTarget();
1718 }
1719
1720 private void notifyOnDataActivity() {
1721 long sent, received;
1722 long preTxPkts = mTxPkts, preRxPkts = mRxPkts;
1723 int dataActivity = WifiManager.DATA_ACTIVITY_NONE;
1724
1725 mTxPkts = TrafficStats.getTxPackets(mInterfaceName);
1726 mRxPkts = TrafficStats.getRxPackets(mInterfaceName);
1727
1728 if (preTxPkts > 0 || preRxPkts > 0) {
1729 sent = mTxPkts - preTxPkts;
1730 received = mRxPkts - preRxPkts;
1731 if (sent > 0) {
1732 dataActivity |= WifiManager.DATA_ACTIVITY_OUT;
1733 }
1734 if (received > 0) {
1735 dataActivity |= WifiManager.DATA_ACTIVITY_IN;
1736 }
1737
1738 if (dataActivity != mDataActivity && !mScreenOff) {
1739 mDataActivity = dataActivity;
1740 for (AsyncChannel client : mClients) {
1741 client.sendMessage(WifiManager.DATA_ACTIVITY_NOTIFICATION, mDataActivity);
1742 }
1743 }
1744 }
1745 }
1746
1747
Irfan Sheriff0d255342010-07-28 09:35:20 -07001748 private void checkAndSetNotification() {
1749 // If we shouldn't place a notification on available networks, then
1750 // don't bother doing any of the following
1751 if (!mNotificationEnabled) return;
1752
1753 State state = mNetworkInfo.getState();
1754 if ((state == NetworkInfo.State.DISCONNECTED)
1755 || (state == NetworkInfo.State.UNKNOWN)) {
1756 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001757 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001758 if (scanResults != null) {
1759 int numOpenNetworks = 0;
1760 for (int i = scanResults.size() - 1; i >= 0; i--) {
1761 ScanResult scanResult = scanResults.get(i);
1762
Irfan Sherifffdd5f952011-08-04 16:55:54 -07001763 //A capability of [ESS] represents an open access point
1764 //that is available for an STA to connect
1765 if (scanResult.capabilities != null &&
1766 scanResult.capabilities.equals("[ESS]")) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001767 numOpenNetworks++;
1768 }
1769 }
1770
1771 if (numOpenNetworks > 0) {
1772 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1773 /*
1774 * We've scanned continuously at least
1775 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1776 * probably does not have a remembered network in range,
1777 * since otherwise supplicant would have tried to
1778 * associate and thus resetting this counter.
1779 */
1780 setNotificationVisible(true, numOpenNetworks, false, 0);
1781 }
1782 return;
1783 }
1784 }
1785 }
1786
1787 // No open networks in range, remove the notification
1788 setNotificationVisible(false, 0, false, 0);
1789 }
1790
1791 /**
1792 * Clears variables related to tracking whether a notification has been
1793 * shown recently and clears the current notification.
1794 */
1795 private void resetNotification() {
1796 mNotificationRepeatTime = 0;
1797 mNumScansSinceNetworkStateChange = 0;
1798 setNotificationVisible(false, 0, false, 0);
1799 }
1800
1801 /**
1802 * Display or don't display a notification that there are open Wi-Fi networks.
1803 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1804 * @param numNetworks the number networks seen
1805 * @param force {@code true} to force notification to be shown/not-shown,
1806 * even if it is already shown/not-shown.
1807 * @param delay time in milliseconds after which the notification should be made
1808 * visible or invisible.
1809 */
1810 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1811 int delay) {
1812
1813 // Since we use auto cancel on the notification, when the
1814 // mNetworksAvailableNotificationShown is true, the notification may
1815 // have actually been canceled. However, when it is false we know
1816 // for sure that it is not being shown (it will not be shown any other
1817 // place than here)
1818
1819 // If it should be hidden and it is already hidden, then noop
1820 if (!visible && !mNotificationShown && !force) {
1821 return;
1822 }
1823
1824 NotificationManager notificationManager = (NotificationManager) mContext
1825 .getSystemService(Context.NOTIFICATION_SERVICE);
1826
1827 Message message;
1828 if (visible) {
1829
1830 // Not enough time has passed to show the notification again
1831 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1832 return;
1833 }
1834
1835 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001836 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001837 mNotification = new Notification();
1838 mNotification.when = 0;
1839 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1840 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
Adam Powelld56b4d12012-09-30 18:27:31 -07001841 mNotification.contentIntent = TaskStackBuilder.create(mContext)
1842 .addNextIntentWithParentStack(
1843 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK))
1844 .getPendingIntent(0, 0, null, UserHandle.CURRENT);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001845 }
1846
1847 CharSequence title = mContext.getResources().getQuantityText(
1848 com.android.internal.R.plurals.wifi_available, numNetworks);
1849 CharSequence details = mContext.getResources().getQuantityText(
1850 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1851 mNotification.tickerText = title;
1852 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1853
1854 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1855
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001856 notificationManager.notifyAsUser(null, ICON_NETWORKS_AVAILABLE, mNotification,
1857 UserHandle.ALL);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001858 } else {
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001859 notificationManager.cancelAsUser(null, ICON_NETWORKS_AVAILABLE, UserHandle.ALL);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001860 }
1861
Irfan Sheriff0d255342010-07-28 09:35:20 -07001862 mNotificationShown = visible;
1863 }
1864
1865 private class NotificationEnabledSettingObserver extends ContentObserver {
1866
1867 public NotificationEnabledSettingObserver(Handler handler) {
1868 super(handler);
1869 }
1870
1871 public void register() {
1872 ContentResolver cr = mContext.getContentResolver();
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001873 cr.registerContentObserver(Settings.Global.getUriFor(
1874 Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001875 mNotificationEnabled = getValue();
1876 }
1877
1878 @Override
1879 public void onChange(boolean selfChange) {
1880 super.onChange(selfChange);
1881
1882 mNotificationEnabled = getValue();
1883 resetNotification();
1884 }
1885
1886 private boolean getValue() {
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001887 return Settings.Global.getInt(mContext.getContentResolver(),
1888 Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
Irfan Sheriff0d255342010-07-28 09:35:20 -07001889 }
1890 }
1891
1892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893}