blob: 5789a53ba5f53614ea1b0209eced891abc46ad42 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07002 * Copyright (C) 2010 The Android Open Source Project
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Irfan Sheriff330b1872012-09-16 12:27:57 -070019import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.app.AlarmManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070021import android.app.Notification;
22import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.app.PendingIntent;
Adam Powelld56b4d12012-09-30 18:27:31 -070024import android.app.TaskStackBuilder;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070025import android.bluetooth.BluetoothAdapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.BroadcastReceiver;
27import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070032import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.net.wifi.IWifiManager;
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -080034import android.net.wifi.ScanResult;
35import android.net.wifi.SupplicantState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.wifi.WifiInfo;
37import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070038import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.net.wifi.WifiConfiguration;
Isaac Levy654f5092011-07-13 17:41:45 -070040import android.net.wifi.WifiWatchdogStateMachine;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080041import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff651cdfc2011-09-07 00:31:20 -070042import android.net.wifi.WpsInfo;
Irfan Sheriffe4c56c92011-01-12 16:33:58 -080043import android.net.wifi.WpsResult;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080044import android.net.ConnectivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.net.DhcpInfo;
Robert Greenwalt4717c262012-10-31 14:32:53 -070046import android.net.DhcpResults;
47import android.net.LinkAddress;
48import android.net.LinkProperties;
Irfan Sheriff0d255342010-07-28 09:35:20 -070049import android.net.NetworkInfo;
50import android.net.NetworkInfo.State;
Irfan Sheriff227bec42011-02-15 19:30:27 -080051import android.net.NetworkInfo.DetailedState;
Robert Greenwalt4717c262012-10-31 14:32:53 -070052import android.net.NetworkUtils;
53import android.net.RouteInfo;
Irfan Sheriff227bec42011-02-15 19:30:27 -080054import android.net.TrafficStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070056import android.os.Handler;
Irfan Sheriff227bec42011-02-15 19:30:27 -080057import android.os.Messenger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.HandlerThread;
59import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080060import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070061import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070063import android.os.ServiceManager;
Irfan Sheriff227bec42011-02-15 19:30:27 -080064import android.os.SystemProperties;
Irfan Sheriff330b1872012-09-16 12:27:57 -070065import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070066import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070068import android.text.TextUtils;
Nick Pelly6ccaa542012-06-15 15:22:47 -070069import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080070import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
Irfan Sherifff0afe412012-11-30 14:07:44 -080072import java.io.FileDescriptor;
73import java.io.PrintWriter;
Robert Greenwalt4717c262012-10-31 14:32:53 -070074import java.net.InetAddress;
75import java.net.Inet4Address;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.util.ArrayList;
Irfan Sheriff8cef0672011-12-13 17:03:59 -080077import java.util.HashMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080079import java.util.Set;
Irfan Sheriff658772f2011-03-08 14:52:31 -080080import java.util.concurrent.atomic.AtomicInteger;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070081import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
The Android Open Source Project10592532009-03-18 17:39:46 -070083import com.android.internal.app.IBatteryStats;
Irfan Sheriff616f3172011-09-11 19:59:01 -070084import com.android.internal.telephony.TelephonyIntents;
Wink Saville4b7ba092010-10-20 15:37:41 -070085import com.android.internal.util.AsyncChannel;
The Android Open Source Project10592532009-03-18 17:39:46 -070086import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080087import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089/**
90 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070091 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 *
93 * @hide
94 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070095//TODO: Clean up multiple locks and implement WifiService
96// as a SM to track soft AP/client/adhoc bring up based
97// on device idle state, airplane mode and boot.
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099public class WifiService extends IWifiManager.Stub {
100 private static final String TAG = "WifiService";
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700101 private static final boolean DBG = false;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700102
Irfan Sheriff0d255342010-07-28 09:35:20 -0700103 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
105 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106
107 private AlarmManager mAlarmManager;
108 private PendingIntent mIdleIntent;
109 private static final int IDLE_REQUEST = 0;
110 private boolean mScreenOff;
111 private boolean mDeviceIdle;
Irfan Sheriff616f3172011-09-11 19:59:01 -0700112 private boolean mEmergencyCallbackMode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 private int mPluggedType;
114
115 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700116 // some wifi lock statistics
Irfan Sheriff5876a422010-08-12 20:26:23 -0700117 private int mFullHighPerfLocksAcquired;
118 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700119 private int mFullLocksAcquired;
120 private int mFullLocksReleased;
121 private int mScanLocksAcquired;
122 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700123
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700124 private final List<Multicaster> mMulticasters =
125 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700126 private int mMulticastEnabled;
127 private int mMulticastDisabled;
128
The Android Open Source Project10592532009-03-18 17:39:46 -0700129 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800130
Irfan Sheriff227bec42011-02-15 19:30:27 -0800131 private boolean mEnableTrafficStatsPoll = false;
132 private int mTrafficStatsPollToken = 0;
133 private long mTxPkts;
134 private long mRxPkts;
135 /* Tracks last reported data activity */
136 private int mDataActivity;
137 private String mInterfaceName;
138
139 /**
140 * Interval in milliseconds between polling for traffic
141 * statistics
142 */
143 private static final int POLL_TRAFFIC_STATS_INTERVAL_MSECS = 1000;
144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 /**
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700146 * See {@link Settings.Global#WIFI_IDLE_MS}. This is the default value if a
147 * Settings.Global value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 * the approximate point at which the battery drain caused by Wi-Fi
149 * being enabled but not active exceeds the battery drain caused by
150 * re-establishing a connection to the mobile data network.
151 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700152 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 private static final String ACTION_DEVICE_IDLE =
155 "com.android.server.WifiManager.action.DEVICE_IDLE";
156
Irfan Sheriff658772f2011-03-08 14:52:31 -0800157 private static final int WIFI_DISABLED = 0;
158 private static final int WIFI_ENABLED = 1;
159 /* Wifi enabled while in airplane mode */
160 private static final int WIFI_ENABLED_AIRPLANE_OVERRIDE = 2;
Irfan Sheriff31b92e22011-10-03 12:13:20 -0700161 /* Wifi disabled due to airplane mode on */
162 private static final int WIFI_DISABLED_AIRPLANE_ON = 3;
Irfan Sheriff658772f2011-03-08 14:52:31 -0800163
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800164 /* Persisted state that tracks the wifi & airplane interaction from settings */
165 private AtomicInteger mPersistWifiState = new AtomicInteger(WIFI_DISABLED);
166 /* Tracks current airplane mode state */
Irfan Sheriff658772f2011-03-08 14:52:31 -0800167 private AtomicBoolean mAirplaneModeOn = new AtomicBoolean(false);
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800168 /* Tracks whether wifi is enabled from WifiStateMachine's perspective */
169 private boolean mWifiEnabled;
Irfan Sheriff658772f2011-03-08 14:52:31 -0800170
Nick Pelly6ccaa542012-06-15 15:22:47 -0700171 /* The work source (UID) that triggered the current WIFI scan, synchronized
172 * on this */
173 private WorkSource mScanWorkSource;
174
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700175 private boolean mIsReceiverRegistered = false;
176
Irfan Sheriff0d255342010-07-28 09:35:20 -0700177
178 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
179
180 // Variables relating to the 'available networks' notification
181 /**
182 * The icon to show in the 'available networks' notification. This will also
183 * be the ID of the Notification given to the NotificationManager.
184 */
185 private static final int ICON_NETWORKS_AVAILABLE =
186 com.android.internal.R.drawable.stat_notify_wifi_in_range;
187 /**
188 * When a notification is shown, we wait this amount before possibly showing it again.
189 */
190 private final long NOTIFICATION_REPEAT_DELAY_MS;
191 /**
192 * Whether the user has set the setting to show the 'available networks' notification.
193 */
194 private boolean mNotificationEnabled;
195 /**
196 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
197 */
198 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
199 /**
200 * The {@link System#currentTimeMillis()} must be at least this value for us
201 * to show the notification again.
202 */
203 private long mNotificationRepeatTime;
204 /**
205 * The Notification object given to the NotificationManager.
206 */
207 private Notification mNotification;
208 /**
209 * Whether the notification is being shown, as set by us. That is, if the
210 * user cancels the notification, we will not receive the callback so this
211 * will still be true. We only guarantee if this is false, then the
212 * notification is not showing.
213 */
214 private boolean mNotificationShown;
215 /**
216 * The number of continuous scans that must occur before consider the
217 * supplicant in a scanning state. This allows supplicant to associate with
218 * remembered networks that are in the scan results.
219 */
220 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
221 /**
222 * The number of scans since the last network state change. When this
223 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
224 * supplicant to actually be scanning. When the network state changes to
225 * something other than scanning, we reset this to 0.
226 */
227 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700228
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700229 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700230 * Asynchronous channel to WifiStateMachine
231 */
Irfan Sheriff227bec42011-02-15 19:30:27 -0800232 private AsyncChannel mWifiStateMachineChannel;
Wink Saville4b7ba092010-10-20 15:37:41 -0700233
234 /**
Irfan Sheriff227bec42011-02-15 19:30:27 -0800235 * Clients receiving asynchronous messages
Wink Saville4b7ba092010-10-20 15:37:41 -0700236 */
Irfan Sheriff227bec42011-02-15 19:30:27 -0800237 private List<AsyncChannel> mClients = new ArrayList<AsyncChannel>();
Wink Saville4b7ba092010-10-20 15:37:41 -0700238
Irfan Sheriff227bec42011-02-15 19:30:27 -0800239 /**
240 * Handles client connections
241 */
242 private class AsyncServiceHandler extends Handler {
243
244 AsyncServiceHandler(android.os.Looper looper) {
Wink Saville4b7ba092010-10-20 15:37:41 -0700245 super(looper);
Wink Saville4b7ba092010-10-20 15:37:41 -0700246 }
247
248 @Override
249 public void handleMessage(Message msg) {
250 switch (msg.what) {
251 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
252 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
Irfan Sheriff6bfc8882012-08-29 15:35:57 -0700253 if (DBG) Slog.d(TAG, "New client listening to asynchronous messages");
Irfan Sheriff227bec42011-02-15 19:30:27 -0800254 mClients.add((AsyncChannel) msg.obj);
Wink Saville4b7ba092010-10-20 15:37:41 -0700255 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800256 Slog.e(TAG, "Client connection failure, error=" + msg.arg1);
257 }
258 break;
259 }
Irfan Sheriffc23971b2011-03-04 17:06:31 -0800260 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
261 if (msg.arg1 == AsyncChannel.STATUS_SEND_UNSUCCESSFUL) {
Irfan Sheriff6bfc8882012-08-29 15:35:57 -0700262 if (DBG) Slog.d(TAG, "Send failed, client connection lost");
Irfan Sheriffc23971b2011-03-04 17:06:31 -0800263 } else {
Irfan Sheriff6bfc8882012-08-29 15:35:57 -0700264 if (DBG) Slog.d(TAG, "Client connection lost with reason: " + msg.arg1);
Irfan Sheriffc23971b2011-03-04 17:06:31 -0800265 }
266 mClients.remove((AsyncChannel) msg.obj);
267 break;
268 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800269 case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: {
270 AsyncChannel ac = new AsyncChannel();
271 ac.connect(mContext, this, msg.replyTo);
272 break;
273 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800274 case WifiManager.ENABLE_TRAFFIC_STATS_POLL: {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800275 mEnableTrafficStatsPoll = (msg.arg1 == 1);
276 mTrafficStatsPollToken++;
277 if (mEnableTrafficStatsPoll) {
278 notifyOnDataActivity();
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800279 sendMessageDelayed(Message.obtain(this, WifiManager.TRAFFIC_STATS_POLL,
Irfan Sheriff227bec42011-02-15 19:30:27 -0800280 mTrafficStatsPollToken, 0), POLL_TRAFFIC_STATS_INTERVAL_MSECS);
281 }
282 break;
283 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800284 case WifiManager.TRAFFIC_STATS_POLL: {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800285 if (msg.arg1 == mTrafficStatsPollToken) {
286 notifyOnDataActivity();
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800287 sendMessageDelayed(Message.obtain(this, WifiManager.TRAFFIC_STATS_POLL,
Irfan Sheriff227bec42011-02-15 19:30:27 -0800288 mTrafficStatsPollToken, 0), POLL_TRAFFIC_STATS_INTERVAL_MSECS);
Wink Saville4b7ba092010-10-20 15:37:41 -0700289 }
290 break;
291 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800292 case WifiManager.CONNECT_NETWORK: {
293 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800294 break;
295 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800296 case WifiManager.SAVE_NETWORK: {
297 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800298 break;
299 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800300 case WifiManager.FORGET_NETWORK: {
301 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800302 break;
303 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800304 case WifiManager.START_WPS: {
305 mWifiStateMachine.sendMessage(Message.obtain(msg));
Irfan Sheriffebe606f2011-02-24 11:39:15 -0800306 break;
307 }
Irfan Sheriff86a5f5b2012-02-28 17:03:56 -0800308 case WifiManager.CANCEL_WPS: {
309 mWifiStateMachine.sendMessage(Message.obtain(msg));
310 break;
311 }
Irfan Sheriffd3975a92012-02-24 10:54:13 -0800312 case WifiManager.DISABLE_NETWORK: {
313 mWifiStateMachine.sendMessage(Message.obtain(msg));
Isaac Levy8dc6a1b2011-07-27 08:00:03 -0700314 break;
315 }
Yuhao Zhengf6307822012-08-14 14:21:25 -0700316 case WifiManager.RSSI_PKTCNT_FETCH: {
317 mWifiStateMachine.sendMessage(Message.obtain(msg));
318 break;
319 }
Wink Saville4b7ba092010-10-20 15:37:41 -0700320 default: {
321 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
322 break;
323 }
324 }
325 }
326 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800327 private AsyncServiceHandler mAsyncServiceHandler;
328
329 /**
330 * Handles interaction with WifiStateMachine
331 */
332 private class WifiStateMachineHandler extends Handler {
333 private AsyncChannel mWsmChannel;
334
335 WifiStateMachineHandler(android.os.Looper looper) {
336 super(looper);
337 mWsmChannel = new AsyncChannel();
338 mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
339 }
340
341 @Override
342 public void handleMessage(Message msg) {
343 switch (msg.what) {
344 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
345 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
346 mWifiStateMachineChannel = mWsmChannel;
347 } else {
348 Slog.e(TAG, "WifiStateMachine connection failure, error=" + msg.arg1);
349 mWifiStateMachineChannel = null;
350 }
351 break;
352 }
Irfan Sheriff6da83d52011-06-06 12:54:06 -0700353 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
354 Slog.e(TAG, "WifiStateMachine channel lost, msg.arg1 =" + msg.arg1);
355 mWifiStateMachineChannel = null;
356 //Re-establish connection to state machine
357 mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
358 break;
359 }
Irfan Sheriff227bec42011-02-15 19:30:27 -0800360 default: {
361 Slog.d(TAG, "WifiStateMachineHandler.handleMessage ignoring msg=" + msg);
362 break;
363 }
364 }
365 }
366 }
367 WifiStateMachineHandler mWifiStateMachineHandler;
Wink Saville4b7ba092010-10-20 15:37:41 -0700368
369 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700370 * Temporary for computing UIDS that are responsible for starting WIFI.
371 * Protected by mWifiStateTracker lock.
372 */
373 private final WorkSource mTmpWorkSource = new WorkSource();
Isaac Levy654f5092011-07-13 17:41:45 -0700374 private WifiWatchdogStateMachine mWifiWatchdogStateMachine;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700375
376 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 mContext = context;
Irfan Sheriff227bec42011-02-15 19:30:27 -0800378
379 mInterfaceName = SystemProperties.get("wifi.interface", "wlan0");
380
381 mWifiStateMachine = new WifiStateMachine(mContext, mInterfaceName);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700382 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700383 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
386 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
387 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 mContext.registerReceiver(
390 new BroadcastReceiver() {
391 @Override
392 public void onReceive(Context context, Intent intent) {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800393 mAirplaneModeOn.set(isAirplaneModeOn());
Irfan Sheriff42d73bb2012-05-17 14:14:44 -0700394 handleAirplaneModeToggled(mAirplaneModeOn.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 updateWifiState();
396 }
397 },
398 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
399
Irfan Sheriff0d255342010-07-28 09:35:20 -0700400 IntentFilter filter = new IntentFilter();
401 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
402 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
403 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
404
405 mContext.registerReceiver(
406 new BroadcastReceiver() {
407 @Override
408 public void onReceive(Context context, Intent intent) {
409 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800410 int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
411 WifiManager.WIFI_STATE_DISABLED);
412
413 mWifiEnabled = (wifiState == WifiManager.WIFI_STATE_ENABLED);
414
415 // reset & clear notification on any wifi state change
Irfan Sheriff0d255342010-07-28 09:35:20 -0700416 resetNotification();
417 } else if (intent.getAction().equals(
418 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
419 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
420 WifiManager.EXTRA_NETWORK_INFO);
421 // reset & clear notification on a network connect & disconnect
422 switch(mNetworkInfo.getDetailedState()) {
423 case CONNECTED:
424 case DISCONNECTED:
Irfan Sheriffda6da092012-08-16 12:49:23 -0700425 case CAPTIVE_PORTAL_CHECK:
Irfan Sheriff227bec42011-02-15 19:30:27 -0800426 evaluateTrafficStatsPolling();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700427 resetNotification();
428 break;
429 }
430 } else if (intent.getAction().equals(
431 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
Nick Pelly6ccaa542012-06-15 15:22:47 -0700432 noteScanEnd();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700433 checkAndSetNotification();
434 }
435 }
436 }, filter);
437
Irfan Sheriff227bec42011-02-15 19:30:27 -0800438 HandlerThread wifiThread = new HandlerThread("WifiService");
439 wifiThread.start();
440 mAsyncServiceHandler = new AsyncServiceHandler(wifiThread.getLooper());
441 mWifiStateMachineHandler = new WifiStateMachineHandler(wifiThread.getLooper());
442
Irfan Sheriff0d255342010-07-28 09:35:20 -0700443 // Setting is in seconds
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700444 NOTIFICATION_REPEAT_DELAY_MS = Settings.Global.getInt(context.getContentResolver(),
445 Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700446 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
447 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800448 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800449
Nick Pelly6ccaa542012-06-15 15:22:47 -0700450 /** Tell battery stats about a new WIFI scan */
451 private void noteScanStart() {
452 WorkSource scanWorkSource = null;
453 synchronized (WifiService.this) {
454 if (mScanWorkSource != null) {
455 // Scan already in progress, don't add this one to battery stats
456 return;
457 }
458 scanWorkSource = new WorkSource(Binder.getCallingUid());
459 mScanWorkSource = scanWorkSource;
460 }
461
462 long id = Binder.clearCallingIdentity();
463 try {
464 mBatteryStats.noteWifiScanStartedFromSource(scanWorkSource);
465 } catch (RemoteException e) {
466 Log.w(TAG, e);
467 } finally {
468 Binder.restoreCallingIdentity(id);
469 }
470 }
471
472 /** Tell battery stats that the current WIFI scan has completed */
473 private void noteScanEnd() {
474 WorkSource scanWorkSource = null;
475 synchronized (WifiService.this) {
476 scanWorkSource = mScanWorkSource;
477 mScanWorkSource = null;
478 }
479 if (scanWorkSource != null) {
480 try {
481 mBatteryStats.noteWifiScanStoppedFromSource(scanWorkSource);
482 } catch (RemoteException e) {
483 Log.w(TAG, e);
484 }
485 }
486 }
487
Irfan Sheriff7b009782010-03-11 16:37:45 -0800488 /**
489 * Check if Wi-Fi needs to be enabled and start
490 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700491 *
492 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800493 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700494 public void checkAndStartWifi() {
Irfan Sheriff658772f2011-03-08 14:52:31 -0800495 mAirplaneModeOn.set(isAirplaneModeOn());
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800496 mPersistWifiState.set(getPersistedWifiState());
Irfan Sheriff658772f2011-03-08 14:52:31 -0800497 /* Start if Wi-Fi should be enabled or the saved state indicates Wi-Fi was on */
498 boolean wifiEnabled = shouldWifiBeEnabled() || testAndClearWifiSavedState();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800499 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
500 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sherifff03d6202012-05-17 12:33:46 -0700501
502 // If we are already disabled (could be due to airplane mode), avoid changing persist
503 // state here
504 if (wifiEnabled) setWifiEnabled(wifiEnabled);
Isaac Levybc7dfb52011-06-06 15:34:01 -0700505
Isaac Levy654f5092011-07-13 17:41:45 -0700506 mWifiWatchdogStateMachine = WifiWatchdogStateMachine.
507 makeWifiWatchdogStateMachine(mContext);
508
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800509 }
510
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700511 private boolean testAndClearWifiSavedState() {
512 final ContentResolver cr = mContext.getContentResolver();
513 int wifiSavedState = 0;
514 try {
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700515 wifiSavedState = Settings.Global.getInt(cr, Settings.Global.WIFI_SAVED_STATE);
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700516 if(wifiSavedState == 1)
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700517 Settings.Global.putInt(cr, Settings.Global.WIFI_SAVED_STATE, 0);
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700518 } catch (Settings.SettingNotFoundException e) {
519 ;
520 }
521 return (wifiSavedState == 1);
522 }
523
Irfan Sheriff658772f2011-03-08 14:52:31 -0800524 private int getPersistedWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 final ContentResolver cr = mContext.getContentResolver();
526 try {
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700527 return Settings.Global.getInt(cr, Settings.Global.WIFI_ON);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 } catch (Settings.SettingNotFoundException e) {
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700529 Settings.Global.putInt(cr, Settings.Global.WIFI_ON, WIFI_DISABLED);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800530 return WIFI_DISABLED;
531 }
532 }
533
534 private boolean shouldWifiBeEnabled() {
535 if (mAirplaneModeOn.get()) {
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800536 return mPersistWifiState.get() == WIFI_ENABLED_AIRPLANE_OVERRIDE;
Irfan Sheriff658772f2011-03-08 14:52:31 -0800537 } else {
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800538 return mPersistWifiState.get() != WIFI_DISABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 }
540 }
541
Irfan Sheriff42d73bb2012-05-17 14:14:44 -0700542 private void handleWifiToggled(boolean wifiEnabled) {
543 boolean airplaneEnabled = mAirplaneModeOn.get() && isAirplaneToggleable();
544 if (wifiEnabled) {
545 if (airplaneEnabled) {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700546 persistWifiState(WIFI_ENABLED_AIRPLANE_OVERRIDE);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800547 } else {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700548 persistWifiState(WIFI_ENABLED);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800549 }
550 } else {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700551 // When wifi state is disabled, we do not care
552 // if airplane mode is on or not. The scenario of
553 // wifi being disabled due to airplane mode being turned on
554 // is handled handleAirplaneModeToggled()
555 persistWifiState(WIFI_DISABLED);
Irfan Sheriff658772f2011-03-08 14:52:31 -0800556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 }
558
Irfan Sheriff42d73bb2012-05-17 14:14:44 -0700559 private void handleAirplaneModeToggled(boolean airplaneEnabled) {
560 if (airplaneEnabled) {
Irfan Sherifff03d6202012-05-17 12:33:46 -0700561 // Wifi disabled due to airplane on
562 if (mWifiEnabled) {
563 persistWifiState(WIFI_DISABLED_AIRPLANE_ON);
564 }
565 } else {
566 /* On airplane mode disable, restore wifi state if necessary */
567 if (testAndClearWifiSavedState() ||
568 mPersistWifiState.get() == WIFI_ENABLED_AIRPLANE_OVERRIDE) {
569 persistWifiState(WIFI_ENABLED);
570 }
571 }
572 }
573
574 private void persistWifiState(int state) {
575 final ContentResolver cr = mContext.getContentResolver();
576 mPersistWifiState.set(state);
Christopher Tate6f5a9a92012-09-14 17:24:28 -0700577 Settings.Global.putInt(cr, Settings.Global.WIFI_ON, state);
Irfan Sherifff03d6202012-05-17 12:33:46 -0700578 }
Irfan Sheriff658772f2011-03-08 14:52:31 -0800579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 /**
581 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700582 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 */
584 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700585 enforceAccessPermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800586 if (mWifiStateMachineChannel != null) {
587 return mWifiStateMachine.syncPingSupplicant(mWifiStateMachineChannel);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700588 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800589 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700590 return false;
591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 }
593
594 /**
595 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700597 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700599 mWifiStateMachine.startScan(forceActive);
Nick Pelly6ccaa542012-06-15 15:22:47 -0700600 noteScanStart();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
602
603 private void enforceAccessPermission() {
604 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
605 "WifiService");
606 }
607
608 private void enforceChangePermission() {
609 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
610 "WifiService");
611
612 }
613
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700614 private void enforceMulticastChangePermission() {
615 mContext.enforceCallingOrSelfPermission(
616 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
617 "WifiService");
618 }
619
Irfan Sheriffda6da092012-08-16 12:49:23 -0700620 private void enforceConnectivityInternalPermission() {
621 mContext.enforceCallingOrSelfPermission(
622 android.Manifest.permission.CONNECTIVITY_INTERNAL,
623 "ConnectivityService");
624 }
625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700627 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
628 * @param enable {@code true} to enable, {@code false} to disable.
629 * @return {@code true} if the enable/disable operation was
630 * started or is already in the queue.
631 */
632 public synchronized boolean setWifiEnabled(boolean enable) {
633 enforceChangePermission();
Irfan Sheriffbd21b782012-05-16 13:13:54 -0700634 Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid()
635 + ", uid=" + Binder.getCallingUid());
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700636 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700637 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700638 }
639
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700640 if (enable) {
641 reportStartWorkSource();
642 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700643 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700644
645 /*
646 * Caller might not have WRITE_SECURE_SETTINGS,
647 * only CHANGE_WIFI_STATE is enforced
648 */
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800649
Irfan Sherifff03d6202012-05-17 12:33:46 -0700650 long ident = Binder.clearCallingIdentity();
Irfan Sheriff3d33a632012-09-16 17:59:13 -0700651 try {
652 handleWifiToggled(enable);
653 } finally {
654 Binder.restoreCallingIdentity(ident);
655 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700656
657 if (enable) {
658 if (!mIsReceiverRegistered) {
659 registerForBroadcasts();
660 mIsReceiverRegistered = true;
661 }
Irfan Sheriff5401f0b2011-12-07 16:27:49 -0800662 } else if (mIsReceiverRegistered) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700663 mContext.unregisterReceiver(mReceiver);
664 mIsReceiverRegistered = false;
665 }
666
667 return true;
668 }
669
670 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 * see {@link WifiManager#getWifiState()}
672 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
673 * {@link WifiManager#WIFI_STATE_DISABLING},
674 * {@link WifiManager#WIFI_STATE_ENABLED},
675 * {@link WifiManager#WIFI_STATE_ENABLING},
676 * {@link WifiManager#WIFI_STATE_UNKNOWN}
677 */
678 public int getWifiEnabledState() {
679 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700680 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 }
682
683 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700684 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800685 * @param wifiConfig SSID, security and channel details as
686 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700687 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800688 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700689 public void setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800690 enforceChangePermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700691 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800692 }
693
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700694 /**
695 * see {@link WifiManager#getWifiApState()}
696 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
697 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
698 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
699 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
700 * {@link WifiManager#WIFI_AP_STATE_FAILED}
701 */
702 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700703 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700704 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700705 }
706
707 /**
708 * see {@link WifiManager#getWifiApConfiguration()}
709 * @return soft access point configuration
710 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700711 public WifiConfiguration getWifiApConfiguration() {
712 enforceAccessPermission();
Irfan Sheriff9575a1b2011-11-07 10:34:54 -0800713 return mWifiStateMachine.syncGetWifiApConfiguration();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800714 }
715
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700716 /**
717 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
718 * @param wifiConfig WifiConfiguration details for soft access point
719 */
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700720 public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700721 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800722 if (wifiConfig == null)
723 return;
Irfan Sheriffffcea7a2011-05-10 16:26:06 -0700724 mWifiStateMachine.setWifiApConfiguration(wifiConfig);
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800725 }
726
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800727 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700728 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800729 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700730 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700731 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700732 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800733 }
734
735 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700736 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800737 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700738 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700739 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700740 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800741 }
742
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700743 /**
744 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700745 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700746 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700747 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700748 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800749 }
750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 /**
752 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
753 * @return the list of configured networks
754 */
755 public List<WifiConfiguration> getConfiguredNetworks() {
756 enforceAccessPermission();
Irfan Sheriffe744cff2011-12-11 09:17:50 -0800757 if (mWifiStateMachineChannel != null) {
758 return mWifiStateMachine.syncGetConfiguredNetworks(mWifiStateMachineChannel);
759 } else {
760 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
761 return null;
762 }
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800763 }
764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 /**
766 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
767 * @return the supplicant-assigned identifier for the new or updated
768 * network if the operation succeeds, or {@code -1} if it fails
769 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800770 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800772 if (mWifiStateMachineChannel != null) {
773 return mWifiStateMachine.syncAddOrUpdateNetwork(mWifiStateMachineChannel, config);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700774 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800775 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700776 return -1;
777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 }
779
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700780 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
782 * @param netId the integer that identifies the network configuration
783 * to the supplicant
784 * @return {@code true} if the operation succeeded
785 */
786 public boolean removeNetwork(int netId) {
787 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800788 if (mWifiStateMachineChannel != null) {
789 return mWifiStateMachine.syncRemoveNetwork(mWifiStateMachineChannel, netId);
Wink Saville4b7ba092010-10-20 15:37:41 -0700790 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800791 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Wink Saville4b7ba092010-10-20 15:37:41 -0700792 return false;
793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 }
795
796 /**
797 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
798 * @param netId the integer that identifies the network configuration
799 * to the supplicant
800 * @param disableOthers if true, disable all other networks.
801 * @return {@code true} if the operation succeeded
802 */
803 public boolean enableNetwork(int netId, boolean disableOthers) {
804 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800805 if (mWifiStateMachineChannel != null) {
806 return mWifiStateMachine.syncEnableNetwork(mWifiStateMachineChannel, netId,
807 disableOthers);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700808 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800809 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700810 return false;
811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 }
813
814 /**
815 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
816 * @param netId the integer that identifies the network configuration
817 * to the supplicant
818 * @return {@code true} if the operation succeeded
819 */
820 public boolean disableNetwork(int netId) {
821 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800822 if (mWifiStateMachineChannel != null) {
823 return mWifiStateMachine.syncDisableNetwork(mWifiStateMachineChannel, netId);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700824 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800825 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700826 return false;
827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
829
830 /**
831 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
832 * @return the Wi-Fi information, contained in {@link WifiInfo}.
833 */
834 public WifiInfo getConnectionInfo() {
835 enforceAccessPermission();
836 /*
837 * Make sure we have the latest information, by sending
838 * a status request to the supplicant.
839 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700840 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 }
842
843 /**
844 * Return the results of the most recent access point scan, in the form of
845 * a list of {@link ScanResult} objects.
846 * @return the list of results
847 */
848 public List<ScanResult> getScanResults() {
849 enforceAccessPermission();
Irfan Sheriffdb831da2012-09-16 17:39:26 -0700850 int userId = UserHandle.getCallingUserId();
851 long ident = Binder.clearCallingIdentity();
Irfan Sheriff3d33a632012-09-16 17:59:13 -0700852 try {
853 int currentUser = ActivityManager.getCurrentUser();
854 if (userId != currentUser) {
855 return new ArrayList<ScanResult>();
856 } else {
857 return mWifiStateMachine.syncGetScanResultsList();
858 }
859 } finally {
860 Binder.restoreCallingIdentity(ident);
Irfan Sheriff330b1872012-09-16 12:27:57 -0700861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
863
864 /**
865 * Tell the supplicant to persist the current list of configured networks.
866 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700867 *
868 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 */
870 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700871 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -0800873 if (mWifiStateMachineChannel != null) {
874 return mWifiStateMachine.syncSaveConfig(mWifiStateMachineChannel);
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700875 } else {
Irfan Sheriff227bec42011-02-15 19:30:27 -0800876 Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700877 return false;
878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 }
880
881 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700882 * Set the country code
883 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700884 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700885 *
886 * The persist behavior exists so that wifi can fall back to the last
887 * persisted country code on a restart, when the locale information is
888 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700890 public void setCountryCode(String countryCode, boolean persist) {
891 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
892 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700894 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
896
897 /**
Irfan Sheriff36f74132010-11-04 16:57:37 -0700898 * Set the operational frequency band
899 * @param band One of
900 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
901 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
902 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
903 * @param persist {@code true} if the setting should be remembered.
904 *
905 */
906 public void setFrequencyBand(int band, boolean persist) {
907 enforceChangePermission();
908 if (!isDualBandSupported()) return;
909 Slog.i(TAG, "WifiService trying to set frequency band to " + band +
910 " with persist set to " + persist);
911 mWifiStateMachine.setFrequencyBand(band, persist);
912 }
913
914
915 /**
916 * Get the operational frequency band
917 */
918 public int getFrequencyBand() {
919 enforceAccessPermission();
920 return mWifiStateMachine.getFrequencyBand();
921 }
922
923 public boolean isDualBandSupported() {
924 //TODO: Should move towards adding a driver API that checks at runtime
925 return mContext.getResources().getBoolean(
926 com.android.internal.R.bool.config_wifi_dual_band_support);
927 }
928
929 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 * Return the DHCP-assigned addresses from the last successful DHCP request,
931 * if any.
932 * @return the DHCP information
Robert Greenwalt4717c262012-10-31 14:32:53 -0700933 * @deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 */
935 public DhcpInfo getDhcpInfo() {
936 enforceAccessPermission();
Robert Greenwalt4717c262012-10-31 14:32:53 -0700937 DhcpResults dhcpResults = mWifiStateMachine.syncGetDhcpResults();
938 if (dhcpResults.linkProperties == null) return null;
939
940 DhcpInfo info = new DhcpInfo();
941 for (LinkAddress la : dhcpResults.linkProperties.getLinkAddresses()) {
942 InetAddress addr = la.getAddress();
943 if (addr instanceof Inet4Address) {
944 info.ipAddress = NetworkUtils.inetAddressToInt((Inet4Address)addr);
945 break;
946 }
947 }
948 for (RouteInfo r : dhcpResults.linkProperties.getRoutes()) {
949 if (r.isDefaultRoute()) {
950 InetAddress gateway = r.getGateway();
951 if (gateway instanceof Inet4Address) {
952 info.gateway = NetworkUtils.inetAddressToInt((Inet4Address)gateway);
953 }
954 } else if (r.isHostRoute()) {
955 LinkAddress dest = r.getDestination();
956 if (dest.getAddress() instanceof Inet4Address) {
957 info.netmask = NetworkUtils.prefixLengthToNetmaskInt(
958 dest.getNetworkPrefixLength());
959 }
960 }
961 }
962 int dnsFound = 0;
963 for (InetAddress dns : dhcpResults.linkProperties.getDnses()) {
964 if (dns instanceof Inet4Address) {
965 if (dnsFound == 0) {
966 info.dns1 = NetworkUtils.inetAddressToInt((Inet4Address)dns);
967 } else {
968 info.dns2 = NetworkUtils.inetAddressToInt((Inet4Address)dns);
969 }
970 if (++dnsFound > 1) break;
971 }
972 }
973 InetAddress serverAddress = dhcpResults.serverAddress;
974 if (serverAddress instanceof Inet4Address) {
975 info.serverAddress = NetworkUtils.inetAddressToInt((Inet4Address)serverAddress);
976 }
977 info.leaseDuration = dhcpResults.leaseDuration;
978
979 return info;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
981
Irfan Sheriff0d255342010-07-28 09:35:20 -0700982 /**
983 * see {@link android.net.wifi.WifiManager#startWifi}
984 *
985 */
986 public void startWifi() {
Irfan Sheriffda6da092012-08-16 12:49:23 -0700987 enforceConnectivityInternalPermission();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700988 /* TODO: may be add permissions for access only to connectivity service
989 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
990 * of WifiLock & device idle status unless wifi enabled status is toggled
991 */
992
Irfan Sheriff4494c902011-12-08 10:47:54 -0800993 mWifiStateMachine.setDriverStart(true, mEmergencyCallbackMode);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700994 mWifiStateMachine.reconnectCommand();
995 }
996
Irfan Sheriffda6da092012-08-16 12:49:23 -0700997 public void captivePortalCheckComplete() {
998 enforceConnectivityInternalPermission();
999 mWifiStateMachine.captivePortalCheckComplete();
1000 }
1001
Irfan Sheriff0d255342010-07-28 09:35:20 -07001002 /**
1003 * see {@link android.net.wifi.WifiManager#stopWifi}
1004 *
1005 */
1006 public void stopWifi() {
Irfan Sheriffda6da092012-08-16 12:49:23 -07001007 enforceConnectivityInternalPermission();
1008 /*
Irfan Sheriff0d255342010-07-28 09:35:20 -07001009 * TODO: if a stop is issued, wifi is brought up only by startWifi
1010 * unless wifi enabled status is toggled
1011 */
Irfan Sheriff4494c902011-12-08 10:47:54 -08001012 mWifiStateMachine.setDriverStart(false, mEmergencyCallbackMode);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001013 }
1014
Irfan Sheriff0d255342010-07-28 09:35:20 -07001015 /**
1016 * see {@link android.net.wifi.WifiManager#addToBlacklist}
1017 *
1018 */
1019 public void addToBlacklist(String bssid) {
1020 enforceChangePermission();
1021
1022 mWifiStateMachine.addToBlacklist(bssid);
1023 }
1024
1025 /**
1026 * see {@link android.net.wifi.WifiManager#clearBlacklist}
1027 *
1028 */
1029 public void clearBlacklist() {
1030 enforceChangePermission();
1031
1032 mWifiStateMachine.clearBlacklist();
1033 }
1034
Irfan Sheriff227bec42011-02-15 19:30:27 -08001035 /**
1036 * Get a reference to handler. This is used by a client to establish
1037 * an AsyncChannel communication with WifiService
1038 */
Irfan Sheriff07573b32012-01-27 21:00:19 -08001039 public Messenger getWifiServiceMessenger() {
Irfan Sheriff35bbe272012-08-23 16:57:43 -07001040 enforceAccessPermission();
1041 enforceChangePermission();
Irfan Sheriff227bec42011-02-15 19:30:27 -08001042 return new Messenger(mAsyncServiceHandler);
1043 }
1044
Irfan Sheriff07573b32012-01-27 21:00:19 -08001045 /** Get a reference to WifiStateMachine handler for AsyncChannel communication */
1046 public Messenger getWifiStateMachineMessenger() {
1047 enforceAccessPermission();
1048 enforceChangePermission();
1049 return mWifiStateMachine.getMessenger();
1050 }
1051
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -08001052 /**
1053 * Get the IP and proxy configuration file
1054 */
1055 public String getConfigFile() {
1056 enforceAccessPermission();
1057 return mWifiStateMachine.getConfigFile();
1058 }
1059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1061 @Override
1062 public void onReceive(Context context, Intent intent) {
1063 String action = intent.getAction();
1064
Doug Zongker43866e02010-01-07 12:09:54 -08001065 long idleMillis =
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001066 Settings.Global.getLong(mContext.getContentResolver(),
1067 Settings.Global.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 int stayAwakeConditions =
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001069 Settings.Global.getInt(mContext.getContentResolver(),
1070 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -04001072 if (DBG) {
1073 Slog.d(TAG, "ACTION_SCREEN_ON");
1074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 mAlarmManager.cancel(mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 mScreenOff = false;
Irfan Sheriff227bec42011-02-15 19:30:27 -08001077 evaluateTrafficStatsPolling();
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001078 setDeviceIdleAndUpdateWifi(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -04001080 if (DBG) {
1081 Slog.d(TAG, "ACTION_SCREEN_OFF");
1082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 mScreenOff = true;
Irfan Sheriff227bec42011-02-15 19:30:27 -08001084 evaluateTrafficStatsPolling();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 /*
1086 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1087 * AND the "stay on while plugged in" setting doesn't match the
1088 * current power conditions (i.e, not plugged in, plugged in to USB,
1089 * or plugged in to AC).
1090 */
1091 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001092 //Delayed shutdown if wifi is connected
1093 if (mNetworkInfo.getDetailedState() == DetailedState.CONNECTED) {
1094 if (DBG) Slog.d(TAG, "setting ACTION_DEVICE_IDLE: " + idleMillis + " ms");
1095 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
1096 + idleMillis, mIdleIntent);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001097 } else {
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001098 setDeviceIdleAndUpdateWifi(true);
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -04001099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001102 setDeviceIdleAndUpdateWifi(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1104 /*
1105 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
1106 * AND we are transitioning from a state in which the device was supposed
1107 * to stay awake to a state in which it is not supposed to stay awake.
1108 * If "stay awake" state is not changing, we do nothing, to avoid resetting
1109 * the already-set timer.
1110 */
1111 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -04001112 if (DBG) {
1113 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
1114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
1116 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
1117 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -04001118 if (DBG) {
1119 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
1120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 }
Irfan Sheriff8cef0672011-12-13 17:03:59 -08001123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 mPluggedType = pluggedType;
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001125 } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
1126 int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
1127 BluetoothAdapter.STATE_DISCONNECTED);
1128 mWifiStateMachine.sendBluetoothAdapterStateChange(state);
Irfan Sheriff616f3172011-09-11 19:59:01 -07001129 } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
1130 mEmergencyCallbackMode = intent.getBooleanExtra("phoneinECMState", false);
1131 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
1134
1135 /**
1136 * Determines whether the Wi-Fi chipset should stay awake or be put to
1137 * sleep. Looks at the setting for the sleep policy and the current
1138 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001139 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 * @see #shouldDeviceStayAwake(int, int)
1141 */
1142 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
Irfan Sheriff739f6bc2011-01-28 16:43:12 -08001143 //Never sleep as long as the user has not changed the settings
Brian Muramatsu35d323a2012-09-20 19:52:34 -07001144 int wifiSleepPolicy = Settings.Global.getInt(mContext.getContentResolver(),
1145 Settings.Global.WIFI_SLEEP_POLICY,
1146 Settings.Global.WIFI_SLEEP_POLICY_NEVER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147
Brian Muramatsu35d323a2012-09-20 19:52:34 -07001148 if (wifiSleepPolicy == Settings.Global.WIFI_SLEEP_POLICY_NEVER) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 // Never sleep
1150 return true;
Brian Muramatsu35d323a2012-09-20 19:52:34 -07001151 } else if ((wifiSleepPolicy == Settings.Global.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 (pluggedType != 0)) {
1153 // Never sleep while plugged, and we're plugged
1154 return true;
1155 } else {
1156 // Default
1157 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
1158 }
1159 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 /**
1162 * Determine whether the bit value corresponding to {@code pluggedType} is set in
1163 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
1164 * of {@code 0} isn't really a plugged type, but rather an indication that the
1165 * device isn't plugged in at all, there is no bit value corresponding to a
1166 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -07001167 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 * @param stayAwakeConditions a bit string specifying which "plugged types" should
1169 * keep the device (and hence Wi-Fi) awake.
1170 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
1171 * being made
1172 * @return {@code true} if {@code pluggedType} indicates that the device is
1173 * supposed to stay awake, {@code false} otherwise.
1174 */
1175 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
1176 return (stayAwakeConditions & pluggedType) != 0;
1177 }
1178 };
1179
Irfan Sheriffe6daca52011-11-03 15:46:50 -07001180 private void setDeviceIdleAndUpdateWifi(boolean deviceIdle) {
1181 mDeviceIdle = deviceIdle;
1182 reportStartWorkSource();
1183 updateWifiState();
1184 }
1185
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001186 private synchronized void reportStartWorkSource() {
1187 mTmpWorkSource.clear();
1188 if (mDeviceIdle) {
1189 for (int i=0; i<mLocks.mList.size(); i++) {
1190 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001191 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001192 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001193 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001194 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -07001195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 private void updateWifiState() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001198 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
Irfan Sheriff616f3172011-09-11 19:59:01 -07001199 boolean wifiShouldBeStarted;
1200
1201 if (mEmergencyCallbackMode) {
1202 wifiShouldBeStarted = false;
1203 } else {
1204 wifiShouldBeStarted = !mDeviceIdle || lockHeld;
1205 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001206
1207 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -07001209 }
1210 /* If device is not idle, lockmode cannot be scan only */
1211 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 strongestLockMode = WifiManager.WIFI_MODE_FULL;
1213 }
1214
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001215 /* Disable tethering when airplane mode is enabled */
Irfan Sheriff658772f2011-03-08 14:52:31 -08001216 if (mAirplaneModeOn.get()) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001217 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001218 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -07001219
Irfan Sheriff658772f2011-03-08 14:52:31 -08001220 if (shouldWifiBeEnabled()) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001221 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001222 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001223 mWifiStateMachine.setWifiEnabled(true);
1224 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001225 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff4494c902011-12-08 10:47:54 -08001226 mWifiStateMachine.setDriverStart(true, mEmergencyCallbackMode);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001227 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
1228 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 } else {
Irfan Sheriff4494c902011-12-08 10:47:54 -08001230 mWifiStateMachine.setDriverStart(false, mEmergencyCallbackMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07001232 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001233 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
1235 }
1236
1237 private void registerForBroadcasts() {
1238 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
1240 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1241 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1242 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff65eaec82011-01-05 22:00:16 -08001243 intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
Irfan Sheriff616f3172011-09-11 19:59:01 -07001244 intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 mContext.registerReceiver(mReceiver, intentFilter);
1246 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 private boolean isAirplaneSensitive() {
Christopher Tatec09cdce2012-09-10 16:50:14 -07001249 String airplaneModeRadios = Settings.Global.getString(mContext.getContentResolver(),
1250 Settings.Global.AIRPLANE_MODE_RADIOS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 return airplaneModeRadios == null
Christopher Tatec09cdce2012-09-10 16:50:14 -07001252 || airplaneModeRadios.contains(Settings.Global.RADIO_WIFI);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 }
1254
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001255 private boolean isAirplaneToggleable() {
Christopher Tatec09cdce2012-09-10 16:50:14 -07001256 String toggleableRadios = Settings.Global.getString(mContext.getContentResolver(),
1257 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001258 return toggleableRadios != null
Christopher Tatec09cdce2012-09-10 16:50:14 -07001259 && toggleableRadios.contains(Settings.Global.RADIO_WIFI);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001260 }
1261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 /**
1263 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1264 * currently on.
1265 * @return {@code true} if airplane mode is on.
1266 */
1267 private boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -07001268 return isAirplaneSensitive() && Settings.Global.getInt(mContext.getContentResolver(),
1269 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
1271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 @Override
1273 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1274 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1275 != PackageManager.PERMISSION_GRANTED) {
1276 pw.println("Permission Denial: can't dump WifiService from from pid="
1277 + Binder.getCallingPid()
1278 + ", uid=" + Binder.getCallingUid());
1279 return;
1280 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001281 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 pw.println("Stay-awake conditions: " +
Christopher Tatec09cdce2012-09-10 16:50:14 -07001283 Settings.Global.getInt(mContext.getContentResolver(),
1284 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0));
Irfan Sherifff0afe412012-11-30 14:07:44 -08001285 pw.println("mScreenOff " + mScreenOff);
1286 pw.println("mDeviceIdle " + mDeviceIdle);
1287 pw.println("mPluggedType " + mPluggedType);
1288 pw.println("mEmergencyCallbackMode " + mEmergencyCallbackMode);
1289 pw.println("mMulticastEnabled " + mMulticastEnabled);
1290 pw.println("mMulticastDisabled " + mMulticastDisabled);
1291 pw.println("mEnableTrafficStatsPoll " + mEnableTrafficStatsPoll);
1292 pw.println("mTrafficStatsPollToken " + mTrafficStatsPollToken);
1293 pw.println("mTxPkts " + mTxPkts);
1294 pw.println("mRxPkts " + mRxPkts);
1295 pw.println("mDataActivity " + mDataActivity);
1296 pw.println("mPersistWifiState " + mPersistWifiState.get());
1297 pw.println("mAirplaneModeOn " + mAirplaneModeOn.get());
1298 pw.println("mWifiEnabled " + mWifiEnabled);
1299 pw.println("mNotificationEnabled " + mNotificationEnabled);
1300 pw.println("mNotificationRepeatTime " + mNotificationRepeatTime);
1301 pw.println("mNotificationShown " + mNotificationShown);
1302 pw.println("mNumScansSinceNetworkStateChange " + mNumScansSinceNetworkStateChange);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001305 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 if (scanResults != null && scanResults.size() != 0) {
1307 pw.println(" BSSID Frequency RSSI Flags SSID");
1308 for (ScanResult r : scanResults) {
1309 pw.printf(" %17s %9d %5d %-16s %s%n",
1310 r.BSSID,
1311 r.frequency,
1312 r.level,
1313 r.capabilities,
1314 r.SSID == null ? "" : r.SSID);
1315 }
1316 }
1317 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001318 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001319 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001320 mScanLocksAcquired + " scan");
1321 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001322 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001323 mScanLocksReleased + " scan");
1324 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 pw.println("Locks held:");
1326 mLocks.dump(pw);
Isaac Levybc7dfb52011-06-06 15:34:01 -07001327
Irfan Sherifff0afe412012-11-30 14:07:44 -08001328 mWifiWatchdogStateMachine.dump(fd, pw, args);
Isaac Levybc7dfb52011-06-06 15:34:01 -07001329 pw.println();
Irfan Sheriff60792372012-04-16 16:47:10 -07001330 mWifiStateMachine.dump(fd, pw, args);
Irfan Sherifff0afe412012-11-30 14:07:44 -08001331 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 }
1333
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001334 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001335 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1336 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 }
1338
1339 public void binderDied() {
1340 synchronized (mLocks) {
1341 releaseWifiLockLocked(mBinder);
1342 }
1343 }
1344
1345 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001346 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 }
1348 }
1349
1350 private class LockList {
1351 private List<WifiLock> mList;
1352
1353 private LockList() {
1354 mList = new ArrayList<WifiLock>();
1355 }
1356
1357 private synchronized boolean hasLocks() {
1358 return !mList.isEmpty();
1359 }
1360
1361 private synchronized int getStrongestLockMode() {
1362 if (mList.isEmpty()) {
1363 return WifiManager.WIFI_MODE_FULL;
1364 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001365
1366 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1367 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001369
1370 if (mFullLocksAcquired > mFullLocksReleased) {
1371 return WifiManager.WIFI_MODE_FULL;
1372 }
1373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 return WifiManager.WIFI_MODE_SCAN_ONLY;
1375 }
1376
1377 private void addLock(WifiLock lock) {
1378 if (findLockByBinder(lock.mBinder) < 0) {
1379 mList.add(lock);
1380 }
1381 }
1382
1383 private WifiLock removeLock(IBinder binder) {
1384 int index = findLockByBinder(binder);
1385 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001386 WifiLock ret = mList.remove(index);
1387 ret.unlinkDeathRecipient();
1388 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 } else {
1390 return null;
1391 }
1392 }
1393
1394 private int findLockByBinder(IBinder binder) {
1395 int size = mList.size();
1396 for (int i = size - 1; i >= 0; i--)
1397 if (mList.get(i).mBinder == binder)
1398 return i;
1399 return -1;
1400 }
1401
1402 private void dump(PrintWriter pw) {
1403 for (WifiLock l : mList) {
1404 pw.print(" ");
1405 pw.println(l);
1406 }
1407 }
1408 }
1409
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001410 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001411 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001412 return;
1413 }
1414 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1415 pid, uid, null);
1416 }
1417
1418 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001420 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1421 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1422 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1423 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1424 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 return false;
1426 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001427 if (ws != null && ws.size() == 0) {
1428 ws = null;
1429 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001430 if (ws != null) {
1431 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1432 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001433 if (ws == null) {
1434 ws = new WorkSource(Binder.getCallingUid());
1435 }
1436 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 synchronized (mLocks) {
1438 return acquireWifiLockLocked(wifiLock);
1439 }
1440 }
1441
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001442 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1443 switch(wifiLock.mMode) {
1444 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001445 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001446 case WifiManager.WIFI_MODE_SCAN_ONLY:
Nick Pelly6ccaa542012-06-15 15:22:47 -07001447 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001448 break;
1449 }
1450 }
1451
1452 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1453 switch(wifiLock.mMode) {
1454 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001455 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001456 case WifiManager.WIFI_MODE_SCAN_ONLY:
Nick Pelly6ccaa542012-06-15 15:22:47 -07001457 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001458 break;
1459 }
1460 }
1461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001463 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001466
The Android Open Source Project10592532009-03-18 17:39:46 -07001467 long ident = Binder.clearCallingIdentity();
1468 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001469 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001470 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001471 case WifiManager.WIFI_MODE_FULL:
1472 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001473 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001474 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1475 ++mFullHighPerfLocksAcquired;
1476 break;
1477
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001478 case WifiManager.WIFI_MODE_SCAN_ONLY:
1479 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001480 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001481 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001482
1483 // Be aggressive about adding new locks into the accounted state...
1484 // we want to over-report rather than under-report.
1485 reportStartWorkSource();
1486
1487 updateWifiState();
1488 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001489 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001490 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001491 } finally {
1492 Binder.restoreCallingIdentity(ident);
1493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001496 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1497 int uid = Binder.getCallingUid();
1498 int pid = Binder.getCallingPid();
1499 if (ws != null && ws.size() == 0) {
1500 ws = null;
1501 }
1502 if (ws != null) {
1503 enforceWakeSourcePermission(uid, pid);
1504 }
1505 long ident = Binder.clearCallingIdentity();
1506 try {
1507 synchronized (mLocks) {
1508 int index = mLocks.findLockByBinder(lock);
1509 if (index < 0) {
1510 throw new IllegalArgumentException("Wifi lock not active");
1511 }
1512 WifiLock wl = mLocks.mList.get(index);
1513 noteReleaseWifiLock(wl);
1514 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1515 noteAcquireWifiLock(wl);
1516 }
1517 } catch (RemoteException e) {
1518 } finally {
1519 Binder.restoreCallingIdentity(ident);
1520 }
1521 }
1522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 public boolean releaseWifiLock(IBinder lock) {
1524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1525 synchronized (mLocks) {
1526 return releaseWifiLockLocked(lock);
1527 }
1528 }
1529
1530 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001531 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001532
The Android Open Source Project10592532009-03-18 17:39:46 -07001533 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001534
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001535 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001536
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001537 hadLock = (wifiLock != null);
1538
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001539 long ident = Binder.clearCallingIdentity();
1540 try {
1541 if (hadLock) {
Wink Savillece0ea1f2b2011-10-13 16:55:20 -07001542 noteReleaseWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001543 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001544 case WifiManager.WIFI_MODE_FULL:
1545 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001546 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001547 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1548 ++mFullHighPerfLocksReleased;
1549 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001550 case WifiManager.WIFI_MODE_SCAN_ONLY:
1551 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001552 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001553 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001554 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001555
1556 // TODO - should this only happen if you hadLock?
1557 updateWifiState();
1558
1559 } catch (RemoteException e) {
1560 } finally {
1561 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001562 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001563
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001564 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001566
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001567 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001568 implements IBinder.DeathRecipient {
1569 String mTag;
1570 int mMode;
1571 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001572 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001573
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001574 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001575 super();
1576 mTag = tag;
1577 mMode = mode;
1578 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001579 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001580 try {
1581 mBinder.linkToDeath(this, 0);
1582 } catch (RemoteException e) {
1583 binderDied();
1584 }
1585 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001586
1587 void unlinkDeathRecipient() {
1588 mBinder.unlinkToDeath(this, 0);
1589 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001590 }
1591
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001592 private class Multicaster extends DeathRecipient {
1593 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001594 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001595 }
1596
1597 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001598 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001599 synchronized (mMulticasters) {
1600 int i = mMulticasters.indexOf(this);
1601 if (i != -1) {
1602 removeMulticasterLocked(i, mMode);
1603 }
1604 }
1605 }
1606
1607 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001608 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001609 }
1610
1611 public int getUid() {
1612 return mMode;
1613 }
1614 }
1615
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001616 public void initializeMulticastFiltering() {
1617 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001618
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001619 synchronized (mMulticasters) {
1620 // if anybody had requested filters be off, leave off
1621 if (mMulticasters.size() != 0) {
1622 return;
1623 } else {
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001624 mWifiStateMachine.startFilteringMulticastV4Packets();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001625 }
1626 }
1627 }
1628
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001629 public void acquireMulticastLock(IBinder binder, String tag) {
1630 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001631
1632 synchronized (mMulticasters) {
1633 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001634 mMulticasters.add(new Multicaster(tag, binder));
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001635 // Note that we could call stopFilteringMulticastV4Packets only when
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001636 // our new size == 1 (first call), but this function won't
1637 // be called often and by making the stopPacket call each
1638 // time we're less fragile and self-healing.
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001639 mWifiStateMachine.stopFilteringMulticastV4Packets();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001640 }
1641
1642 int uid = Binder.getCallingUid();
You Kim2bea5852012-10-23 22:56:51 +09001643 final long ident = Binder.clearCallingIdentity();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001644 try {
1645 mBatteryStats.noteWifiMulticastEnabled(uid);
1646 } catch (RemoteException e) {
1647 } finally {
1648 Binder.restoreCallingIdentity(ident);
1649 }
1650 }
1651
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001652 public void releaseMulticastLock() {
1653 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001654
1655 int uid = Binder.getCallingUid();
1656 synchronized (mMulticasters) {
1657 mMulticastDisabled++;
1658 int size = mMulticasters.size();
1659 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001660 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001661 if ((m != null) && (m.getUid() == uid)) {
1662 removeMulticasterLocked(i, uid);
1663 }
1664 }
1665 }
1666 }
1667
1668 private void removeMulticasterLocked(int i, int uid)
1669 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001670 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001671
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001672 if (removed != null) {
1673 removed.unlinkDeathRecipient();
1674 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001675 if (mMulticasters.size() == 0) {
Irfan Sheriffb0c1b80f2011-07-19 15:44:25 -07001676 mWifiStateMachine.startFilteringMulticastV4Packets();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001677 }
1678
You Kim2bea5852012-10-23 22:56:51 +09001679 final long ident = Binder.clearCallingIdentity();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001680 try {
1681 mBatteryStats.noteWifiMulticastDisabled(uid);
1682 } catch (RemoteException e) {
1683 } finally {
1684 Binder.restoreCallingIdentity(ident);
1685 }
1686 }
1687
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001688 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001689 enforceAccessPermission();
1690
1691 synchronized (mMulticasters) {
1692 return (mMulticasters.size() > 0);
1693 }
1694 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001695
Irfan Sheriff227bec42011-02-15 19:30:27 -08001696 /**
1697 * Evaluate if traffic stats polling is needed based on
1698 * connection and screen on status
1699 */
1700 private void evaluateTrafficStatsPolling() {
1701 Message msg;
1702 if (mNetworkInfo.getDetailedState() == DetailedState.CONNECTED && !mScreenOff) {
Irfan Sheriffebe606f2011-02-24 11:39:15 -08001703 msg = Message.obtain(mAsyncServiceHandler,
Irfan Sheriffd3975a92012-02-24 10:54:13 -08001704 WifiManager.ENABLE_TRAFFIC_STATS_POLL, 1, 0);
Irfan Sheriff227bec42011-02-15 19:30:27 -08001705 } else {
Irfan Sheriffebe606f2011-02-24 11:39:15 -08001706 msg = Message.obtain(mAsyncServiceHandler,
Irfan Sheriffd3975a92012-02-24 10:54:13 -08001707 WifiManager.ENABLE_TRAFFIC_STATS_POLL, 0, 0);
Irfan Sheriff227bec42011-02-15 19:30:27 -08001708 }
1709 msg.sendToTarget();
1710 }
1711
1712 private void notifyOnDataActivity() {
1713 long sent, received;
1714 long preTxPkts = mTxPkts, preRxPkts = mRxPkts;
1715 int dataActivity = WifiManager.DATA_ACTIVITY_NONE;
1716
1717 mTxPkts = TrafficStats.getTxPackets(mInterfaceName);
1718 mRxPkts = TrafficStats.getRxPackets(mInterfaceName);
1719
1720 if (preTxPkts > 0 || preRxPkts > 0) {
1721 sent = mTxPkts - preTxPkts;
1722 received = mRxPkts - preRxPkts;
1723 if (sent > 0) {
1724 dataActivity |= WifiManager.DATA_ACTIVITY_OUT;
1725 }
1726 if (received > 0) {
1727 dataActivity |= WifiManager.DATA_ACTIVITY_IN;
1728 }
1729
1730 if (dataActivity != mDataActivity && !mScreenOff) {
1731 mDataActivity = dataActivity;
1732 for (AsyncChannel client : mClients) {
1733 client.sendMessage(WifiManager.DATA_ACTIVITY_NOTIFICATION, mDataActivity);
1734 }
1735 }
1736 }
1737 }
1738
1739
Irfan Sheriff0d255342010-07-28 09:35:20 -07001740 private void checkAndSetNotification() {
1741 // If we shouldn't place a notification on available networks, then
1742 // don't bother doing any of the following
1743 if (!mNotificationEnabled) return;
1744
1745 State state = mNetworkInfo.getState();
1746 if ((state == NetworkInfo.State.DISCONNECTED)
1747 || (state == NetworkInfo.State.UNKNOWN)) {
1748 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001749 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001750 if (scanResults != null) {
1751 int numOpenNetworks = 0;
1752 for (int i = scanResults.size() - 1; i >= 0; i--) {
1753 ScanResult scanResult = scanResults.get(i);
1754
Irfan Sherifffdd5f952011-08-04 16:55:54 -07001755 //A capability of [ESS] represents an open access point
1756 //that is available for an STA to connect
1757 if (scanResult.capabilities != null &&
1758 scanResult.capabilities.equals("[ESS]")) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001759 numOpenNetworks++;
1760 }
1761 }
1762
1763 if (numOpenNetworks > 0) {
1764 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1765 /*
1766 * We've scanned continuously at least
1767 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1768 * probably does not have a remembered network in range,
1769 * since otherwise supplicant would have tried to
1770 * associate and thus resetting this counter.
1771 */
1772 setNotificationVisible(true, numOpenNetworks, false, 0);
1773 }
1774 return;
1775 }
1776 }
1777 }
1778
1779 // No open networks in range, remove the notification
1780 setNotificationVisible(false, 0, false, 0);
1781 }
1782
1783 /**
1784 * Clears variables related to tracking whether a notification has been
1785 * shown recently and clears the current notification.
1786 */
1787 private void resetNotification() {
1788 mNotificationRepeatTime = 0;
1789 mNumScansSinceNetworkStateChange = 0;
1790 setNotificationVisible(false, 0, false, 0);
1791 }
1792
1793 /**
1794 * Display or don't display a notification that there are open Wi-Fi networks.
1795 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1796 * @param numNetworks the number networks seen
1797 * @param force {@code true} to force notification to be shown/not-shown,
1798 * even if it is already shown/not-shown.
1799 * @param delay time in milliseconds after which the notification should be made
1800 * visible or invisible.
1801 */
1802 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1803 int delay) {
1804
1805 // Since we use auto cancel on the notification, when the
1806 // mNetworksAvailableNotificationShown is true, the notification may
1807 // have actually been canceled. However, when it is false we know
1808 // for sure that it is not being shown (it will not be shown any other
1809 // place than here)
1810
1811 // If it should be hidden and it is already hidden, then noop
1812 if (!visible && !mNotificationShown && !force) {
1813 return;
1814 }
1815
1816 NotificationManager notificationManager = (NotificationManager) mContext
1817 .getSystemService(Context.NOTIFICATION_SERVICE);
1818
1819 Message message;
1820 if (visible) {
1821
1822 // Not enough time has passed to show the notification again
1823 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1824 return;
1825 }
1826
1827 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001828 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001829 mNotification = new Notification();
1830 mNotification.when = 0;
1831 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1832 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
Adam Powelld56b4d12012-09-30 18:27:31 -07001833 mNotification.contentIntent = TaskStackBuilder.create(mContext)
1834 .addNextIntentWithParentStack(
1835 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK))
1836 .getPendingIntent(0, 0, null, UserHandle.CURRENT);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001837 }
1838
1839 CharSequence title = mContext.getResources().getQuantityText(
1840 com.android.internal.R.plurals.wifi_available, numNetworks);
1841 CharSequence details = mContext.getResources().getQuantityText(
1842 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1843 mNotification.tickerText = title;
1844 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1845
1846 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1847
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001848 notificationManager.notifyAsUser(null, ICON_NETWORKS_AVAILABLE, mNotification,
1849 UserHandle.ALL);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001850 } else {
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001851 notificationManager.cancelAsUser(null, ICON_NETWORKS_AVAILABLE, UserHandle.ALL);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001852 }
1853
Irfan Sheriff0d255342010-07-28 09:35:20 -07001854 mNotificationShown = visible;
1855 }
1856
1857 private class NotificationEnabledSettingObserver extends ContentObserver {
1858
1859 public NotificationEnabledSettingObserver(Handler handler) {
1860 super(handler);
1861 }
1862
1863 public void register() {
1864 ContentResolver cr = mContext.getContentResolver();
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001865 cr.registerContentObserver(Settings.Global.getUriFor(
1866 Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001867 mNotificationEnabled = getValue();
1868 }
1869
1870 @Override
1871 public void onChange(boolean selfChange) {
1872 super.onChange(selfChange);
1873
1874 mNotificationEnabled = getValue();
1875 resetNotification();
1876 }
1877
1878 private boolean getValue() {
Christopher Tate6f5a9a92012-09-14 17:24:28 -07001879 return Settings.Global.getInt(mContext.getContentResolver(),
1880 Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
Irfan Sheriff0d255342010-07-28 09:35:20 -07001881 }
1882 }
1883
1884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885}