blob: 5e78353d36d5594e0bab7b2500c22a9121d49914 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
Irfan Sheriffa2a1b912010-06-07 09:03:04 -07002 * Copyright (C) 2010 The Android Open Source Project
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080019import android.app.AlarmManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070020import android.app.Notification;
21import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.app.PendingIntent;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -070023import android.bluetooth.BluetoothAdapter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.BroadcastReceiver;
25import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070030import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.net.wifi.IWifiManager;
32import android.net.wifi.WifiInfo;
33import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070034import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.wifi.ScanResult;
36import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070037import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080038import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff02fb46a2010-12-08 11:27:37 -080039import android.net.wifi.WpsConfiguration;
Irfan Sheriffe4c56c92011-01-12 16:33:58 -080040import android.net.wifi.WpsResult;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080041import android.net.ConnectivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.net.DhcpInfo;
Irfan Sheriff0d255342010-07-28 09:35:20 -070043import android.net.NetworkInfo;
44import android.net.NetworkInfo.State;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Binder;
Irfan Sheriff0d255342010-07-28 09:35:20 -070046import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.HandlerThread;
48import android.os.IBinder;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080049import android.os.INetworkManagementService;
Irfan Sheriff0d255342010-07-28 09:35:20 -070050import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.RemoteException;
Amith Yamasani47873e52009-07-02 12:05:32 -070052import android.os.ServiceManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070053import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070055import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080056import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057
58import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080060import java.util.Set;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070061import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.io.FileDescriptor;
63import java.io.PrintWriter;
64
The Android Open Source Project10592532009-03-18 17:39:46 -070065import com.android.internal.app.IBatteryStats;
Wink Saville4b7ba092010-10-20 15:37:41 -070066import com.android.internal.util.AsyncChannel;
The Android Open Source Project10592532009-03-18 17:39:46 -070067import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080068import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070/**
71 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070072 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 *
74 * @hide
75 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070076//TODO: Clean up multiple locks and implement WifiService
77// as a SM to track soft AP/client/adhoc bring up based
78// on device idle state, airplane mode and boot.
79
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080public class WifiService extends IWifiManager.Stub {
81 private static final String TAG = "WifiService";
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070082 private static final boolean DBG = true;
83
Irfan Sheriff0d255342010-07-28 09:35:20 -070084 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
86 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087
88 private AlarmManager mAlarmManager;
89 private PendingIntent mIdleIntent;
90 private static final int IDLE_REQUEST = 0;
91 private boolean mScreenOff;
92 private boolean mDeviceIdle;
93 private int mPluggedType;
94
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070095 // true if the user enabled Wifi while in airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070096 private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -070099 // some wifi lock statistics
Irfan Sheriff5876a422010-08-12 20:26:23 -0700100 private int mFullHighPerfLocksAcquired;
101 private int mFullHighPerfLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -0700102 private int mFullLocksAcquired;
103 private int mFullLocksReleased;
104 private int mScanLocksAcquired;
105 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700106
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700107 private final List<Multicaster> mMulticasters =
108 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700109 private int mMulticastEnabled;
110 private int mMulticastDisabled;
111
The Android Open Source Project10592532009-03-18 17:39:46 -0700112 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800115 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
116 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 * the approximate point at which the battery drain caused by Wi-Fi
118 * being enabled but not active exceeds the battery drain caused by
119 * re-establishing a connection to the mobile data network.
120 */
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700121 private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private static final String ACTION_DEVICE_IDLE =
124 "com.android.server.WifiManager.action.DEVICE_IDLE";
125
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700126 private boolean mIsReceiverRegistered = false;
127
Irfan Sheriff0d255342010-07-28 09:35:20 -0700128
129 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
130
131 // Variables relating to the 'available networks' notification
132 /**
133 * The icon to show in the 'available networks' notification. This will also
134 * be the ID of the Notification given to the NotificationManager.
135 */
136 private static final int ICON_NETWORKS_AVAILABLE =
137 com.android.internal.R.drawable.stat_notify_wifi_in_range;
138 /**
139 * When a notification is shown, we wait this amount before possibly showing it again.
140 */
141 private final long NOTIFICATION_REPEAT_DELAY_MS;
142 /**
143 * Whether the user has set the setting to show the 'available networks' notification.
144 */
145 private boolean mNotificationEnabled;
146 /**
147 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
148 */
149 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
150 /**
151 * The {@link System#currentTimeMillis()} must be at least this value for us
152 * to show the notification again.
153 */
154 private long mNotificationRepeatTime;
155 /**
156 * The Notification object given to the NotificationManager.
157 */
158 private Notification mNotification;
159 /**
160 * Whether the notification is being shown, as set by us. That is, if the
161 * user cancels the notification, we will not receive the callback so this
162 * will still be true. We only guarantee if this is false, then the
163 * notification is not showing.
164 */
165 private boolean mNotificationShown;
166 /**
167 * The number of continuous scans that must occur before consider the
168 * supplicant in a scanning state. This allows supplicant to associate with
169 * remembered networks that are in the scan results.
170 */
171 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
172 /**
173 * The number of scans since the last network state change. When this
174 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
175 * supplicant to actually be scanning. When the network state changes to
176 * something other than scanning, we reset this to 0.
177 */
178 private int mNumScansSinceNetworkStateChange;
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700179
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700180 /**
Wink Saville4b7ba092010-10-20 15:37:41 -0700181 * Asynchronous channel to WifiStateMachine
182 */
183 private AsyncChannel mChannel;
184
185 /**
186 * TODO: Possibly change WifiService into an AsyncService.
187 */
188 private class WifiServiceHandler extends Handler {
189 private AsyncChannel mWshChannel;
190
191 WifiServiceHandler(android.os.Looper looper, Context context) {
192 super(looper);
193 mWshChannel = new AsyncChannel();
Wink Savillecfce3032010-12-01 23:20:25 -0800194 mWshChannel.connect(context, this, mWifiStateMachine.getHandler());
Wink Saville4b7ba092010-10-20 15:37:41 -0700195 }
196
197 @Override
198 public void handleMessage(Message msg) {
199 switch (msg.what) {
200 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
201 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
202 mChannel = mWshChannel;
203 } else {
204 Slog.d(TAG, "WifiServicehandler.handleMessage could not connect error=" +
205 msg.arg1);
206 mChannel = null;
207 }
208 break;
209 }
210 default: {
211 Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
212 break;
213 }
214 }
215 }
216 }
217 WifiServiceHandler mHandler;
218
219 /**
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700220 * Temporary for computing UIDS that are responsible for starting WIFI.
221 * Protected by mWifiStateTracker lock.
222 */
223 private final WorkSource mTmpWorkSource = new WorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700224
225 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700227 mWifiStateMachine = new WifiStateMachine(mContext);
228 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700229 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
232 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
233 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
234
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700235 HandlerThread wifiThread = new HandlerThread("WifiService");
236 wifiThread.start();
Wink Saville4b7ba092010-10-20 15:37:41 -0700237 mHandler = new WifiServiceHandler(wifiThread.getLooper(), context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 mContext.registerReceiver(
240 new BroadcastReceiver() {
241 @Override
242 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700243 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700244 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700245 // on airplane disable, restore Wifi if the saved state indicates so
246 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
247 persistWifiEnabled(true);
248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 updateWifiState();
250 }
251 },
252 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
253
Irfan Sheriff0d255342010-07-28 09:35:20 -0700254 IntentFilter filter = new IntentFilter();
255 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
256 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
257 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
258
259 mContext.registerReceiver(
260 new BroadcastReceiver() {
261 @Override
262 public void onReceive(Context context, Intent intent) {
263 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
264 // reset & clear notification on any wifi state change
265 resetNotification();
266 } else if (intent.getAction().equals(
267 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
268 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
269 WifiManager.EXTRA_NETWORK_INFO);
270 // reset & clear notification on a network connect & disconnect
271 switch(mNetworkInfo.getDetailedState()) {
272 case CONNECTED:
273 case DISCONNECTED:
274 resetNotification();
275 break;
276 }
277 } else if (intent.getAction().equals(
278 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
279 checkAndSetNotification();
280 }
281 }
282 }, filter);
283
284 // Setting is in seconds
285 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
286 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
287 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
288 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800289 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800290
Irfan Sheriff7b009782010-03-11 16:37:45 -0800291 /**
292 * Check if Wi-Fi needs to be enabled and start
293 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700294 *
295 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800296 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700297 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700298 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700299 boolean wifiEnabled = !isAirplaneModeOn()
300 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800301 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
302 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700303 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800304 }
305
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700306 private boolean testAndClearWifiSavedState() {
307 final ContentResolver cr = mContext.getContentResolver();
308 int wifiSavedState = 0;
309 try {
310 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
311 if(wifiSavedState == 1)
312 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
313 } catch (Settings.SettingNotFoundException e) {
314 ;
315 }
316 return (wifiSavedState == 1);
317 }
318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 private boolean getPersistedWifiEnabled() {
320 final ContentResolver cr = mContext.getContentResolver();
321 try {
322 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
323 } catch (Settings.SettingNotFoundException e) {
324 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
325 return false;
326 }
327 }
328
329 private void persistWifiEnabled(boolean enabled) {
330 final ContentResolver cr = mContext.getContentResolver();
331 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
332 }
333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 /**
335 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700336 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 */
338 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700339 enforceAccessPermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700340 if (mChannel != null) {
341 return mWifiStateMachine.syncPingSupplicant(mChannel);
342 } else {
343 Slog.e(TAG, "mChannel is not initialized");
344 return false;
345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 }
347
348 /**
349 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700351 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700353 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 }
355
356 private void enforceAccessPermission() {
357 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
358 "WifiService");
359 }
360
361 private void enforceChangePermission() {
362 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
363 "WifiService");
364
365 }
366
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700367 private void enforceMulticastChangePermission() {
368 mContext.enforceCallingOrSelfPermission(
369 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
370 "WifiService");
371 }
372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700374 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
375 * @param enable {@code true} to enable, {@code false} to disable.
376 * @return {@code true} if the enable/disable operation was
377 * started or is already in the queue.
378 */
379 public synchronized boolean setWifiEnabled(boolean enable) {
380 enforceChangePermission();
381
382 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700383 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700384 }
385
386 // set a flag if the user is enabling Wifi while in airplane mode
387 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
388 mAirplaneModeOverwridden.set(true);
389 }
390
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700391 if (enable) {
392 reportStartWorkSource();
393 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700394 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700395
396 /*
397 * Caller might not have WRITE_SECURE_SETTINGS,
398 * only CHANGE_WIFI_STATE is enforced
399 */
400 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700401 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700402 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700403
404 if (enable) {
405 if (!mIsReceiverRegistered) {
406 registerForBroadcasts();
407 mIsReceiverRegistered = true;
408 }
409 } else if (mIsReceiverRegistered){
410 mContext.unregisterReceiver(mReceiver);
411 mIsReceiverRegistered = false;
412 }
413
414 return true;
415 }
416
417 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 * see {@link WifiManager#getWifiState()}
419 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
420 * {@link WifiManager#WIFI_STATE_DISABLING},
421 * {@link WifiManager#WIFI_STATE_ENABLED},
422 * {@link WifiManager#WIFI_STATE_ENABLING},
423 * {@link WifiManager#WIFI_STATE_UNKNOWN}
424 */
425 public int getWifiEnabledState() {
426 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700427 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 }
429
430 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700431 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800432 * @param wifiConfig SSID, security and channel details as
433 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700434 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800435 * @return {@code true} if the start operation was
436 * started or is already in the queue.
437 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700438 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800439 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800440
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700441 if (enabled) {
442 /* Use default config if there is no existing config */
443 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
444 wifiConfig = new WifiConfiguration();
445 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
446 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
447 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700448 /*
449 * Caller might not have WRITE_SECURE_SETTINGS,
450 * only CHANGE_WIFI_STATE is enforced
451 */
452 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700453 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700454 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800455 }
456
Irfan Sheriff0d255342010-07-28 09:35:20 -0700457 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700458
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800459 return true;
460 }
461
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700462 /**
463 * see {@link WifiManager#getWifiApState()}
464 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
465 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
466 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
467 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
468 * {@link WifiManager#WIFI_AP_STATE_FAILED}
469 */
470 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700471 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700472 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700473 }
474
475 /**
476 * see {@link WifiManager#getWifiApConfiguration()}
477 * @return soft access point configuration
478 */
479 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800480 final ContentResolver cr = mContext.getContentResolver();
481 WifiConfiguration wifiConfig = new WifiConfiguration();
482 int authType;
483 try {
484 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
485 if (wifiConfig.SSID == null)
486 return null;
487 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
488 wifiConfig.allowedKeyManagement.set(authType);
489 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
490 return wifiConfig;
491 } catch (Settings.SettingNotFoundException e) {
492 Slog.e(TAG,"AP settings not found, returning");
493 return null;
494 }
495 }
496
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700497 /**
498 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
499 * @param wifiConfig WifiConfiguration details for soft access point
500 */
501 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700502 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800503 final ContentResolver cr = mContext.getContentResolver();
504 boolean isWpa;
505 if (wifiConfig == null)
506 return;
507 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
508 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
509 Settings.Secure.putInt(cr,
510 Settings.Secure.WIFI_AP_SECURITY,
511 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
512 if (isWpa)
513 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
514 }
515
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800516 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700517 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800518 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700519 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700520 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700521 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800522 }
523
524 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700525 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800526 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700527 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700528 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700529 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800530 }
531
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700532 /**
533 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700534 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700535 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700536 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700537 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800538 }
539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 /**
541 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
542 * @return the list of configured networks
543 */
544 public List<WifiConfiguration> getConfiguredNetworks() {
545 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700546 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800547 }
548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 /**
550 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
551 * @return the supplicant-assigned identifier for the new or updated
552 * network if the operation succeeds, or {@code -1} if it fails
553 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800554 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700556 if (mChannel != null) {
557 return mWifiStateMachine.syncAddOrUpdateNetwork(mChannel, config);
558 } else {
559 Slog.e(TAG, "mChannel is not initialized");
560 return -1;
561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 }
563
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700564 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
566 * @param netId the integer that identifies the network configuration
567 * to the supplicant
568 * @return {@code true} if the operation succeeded
569 */
570 public boolean removeNetwork(int netId) {
571 enforceChangePermission();
Wink Saville4b7ba092010-10-20 15:37:41 -0700572 if (mChannel != null) {
573 return mWifiStateMachine.syncRemoveNetwork(mChannel, netId);
574 } else {
575 Slog.e(TAG, "mChannel is not initialized");
576 return false;
577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 }
579
580 /**
581 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
582 * @param netId the integer that identifies the network configuration
583 * to the supplicant
584 * @param disableOthers if true, disable all other networks.
585 * @return {@code true} if the operation succeeded
586 */
587 public boolean enableNetwork(int netId, boolean disableOthers) {
588 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700589 if (mChannel != null) {
590 return mWifiStateMachine.syncEnableNetwork(mChannel, netId, disableOthers);
591 } else {
592 Slog.e(TAG, "mChannel is not initialized");
593 return false;
594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 }
596
597 /**
598 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
599 * @param netId the integer that identifies the network configuration
600 * to the supplicant
601 * @return {@code true} if the operation succeeded
602 */
603 public boolean disableNetwork(int netId) {
604 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700605 if (mChannel != null) {
606 return mWifiStateMachine.syncDisableNetwork(mChannel, netId);
607 } else {
608 Slog.e(TAG, "mChannel is not initialized");
609 return false;
610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 }
612
613 /**
614 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
615 * @return the Wi-Fi information, contained in {@link WifiInfo}.
616 */
617 public WifiInfo getConnectionInfo() {
618 enforceAccessPermission();
619 /*
620 * Make sure we have the latest information, by sending
621 * a status request to the supplicant.
622 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700623 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 }
625
626 /**
627 * Return the results of the most recent access point scan, in the form of
628 * a list of {@link ScanResult} objects.
629 * @return the list of results
630 */
631 public List<ScanResult> getScanResults() {
632 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700633 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 }
635
636 /**
637 * Tell the supplicant to persist the current list of configured networks.
638 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700639 *
640 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 */
642 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700643 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700645 if (mChannel != null) {
646 return mWifiStateMachine.syncSaveConfig(mChannel);
647 } else {
648 Slog.e(TAG, "mChannel is not initialized");
649 return false;
650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 }
652
653 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700654 * Set the country code
655 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700656 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700657 *
658 * The persist behavior exists so that wifi can fall back to the last
659 * persisted country code on a restart, when the locale information is
660 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700662 public void setCountryCode(String countryCode, boolean persist) {
663 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
664 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700666 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 }
668
669 /**
Irfan Sheriff36f74132010-11-04 16:57:37 -0700670 * Set the operational frequency band
671 * @param band One of
672 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
673 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
674 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
675 * @param persist {@code true} if the setting should be remembered.
676 *
677 */
678 public void setFrequencyBand(int band, boolean persist) {
679 enforceChangePermission();
680 if (!isDualBandSupported()) return;
681 Slog.i(TAG, "WifiService trying to set frequency band to " + band +
682 " with persist set to " + persist);
683 mWifiStateMachine.setFrequencyBand(band, persist);
684 }
685
686
687 /**
688 * Get the operational frequency band
689 */
690 public int getFrequencyBand() {
691 enforceAccessPermission();
692 return mWifiStateMachine.getFrequencyBand();
693 }
694
695 public boolean isDualBandSupported() {
696 //TODO: Should move towards adding a driver API that checks at runtime
697 return mContext.getResources().getBoolean(
698 com.android.internal.R.bool.config_wifi_dual_band_support);
699 }
700
701 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 * Return the DHCP-assigned addresses from the last successful DHCP request,
703 * if any.
704 * @return the DHCP information
705 */
706 public DhcpInfo getDhcpInfo() {
707 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700708 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 }
710
Irfan Sheriff0d255342010-07-28 09:35:20 -0700711 /**
712 * see {@link android.net.wifi.WifiManager#startWifi}
713 *
714 */
715 public void startWifi() {
716 enforceChangePermission();
717 /* TODO: may be add permissions for access only to connectivity service
718 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
719 * of WifiLock & device idle status unless wifi enabled status is toggled
720 */
721
722 mWifiStateMachine.setDriverStart(true);
723 mWifiStateMachine.reconnectCommand();
724 }
725
726 /**
727 * see {@link android.net.wifi.WifiManager#stopWifi}
728 *
729 */
730 public void stopWifi() {
731 enforceChangePermission();
732 /* TODO: may be add permissions for access only to connectivity service
733 * TODO: if a stop is issued, wifi is brought up only by startWifi
734 * unless wifi enabled status is toggled
735 */
736 mWifiStateMachine.setDriverStart(false);
737 }
738
739
740 /**
741 * see {@link android.net.wifi.WifiManager#addToBlacklist}
742 *
743 */
744 public void addToBlacklist(String bssid) {
745 enforceChangePermission();
746
747 mWifiStateMachine.addToBlacklist(bssid);
748 }
749
750 /**
751 * see {@link android.net.wifi.WifiManager#clearBlacklist}
752 *
753 */
754 public void clearBlacklist() {
755 enforceChangePermission();
756
757 mWifiStateMachine.clearBlacklist();
758 }
759
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700760 public void connectNetworkWithId(int networkId) {
761 enforceChangePermission();
762 mWifiStateMachine.connectNetwork(networkId);
763 }
764
765 public void connectNetworkWithConfig(WifiConfiguration config) {
766 enforceChangePermission();
767 mWifiStateMachine.connectNetwork(config);
768 }
769
770 public void saveNetwork(WifiConfiguration config) {
771 enforceChangePermission();
772 mWifiStateMachine.saveNetwork(config);
773 }
774
775 public void forgetNetwork(int netId) {
776 enforceChangePermission();
777 mWifiStateMachine.forgetNetwork(netId);
778 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700779
Irfan Sheriffe4c56c92011-01-12 16:33:58 -0800780 public WpsResult startWps(WpsConfiguration config) {
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700781 enforceChangePermission();
782 if (mChannel != null) {
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800783 return mWifiStateMachine.startWps(mChannel, config);
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700784 } else {
785 Slog.e(TAG, "mChannel is not initialized");
Irfan Sheriffe4c56c92011-01-12 16:33:58 -0800786 return new WpsResult(WpsResult.Status.FAILURE);
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700787 }
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700788 }
789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
791 @Override
792 public void onReceive(Context context, Intent intent) {
793 String action = intent.getAction();
794
Doug Zongker43866e02010-01-07 12:09:54 -0800795 long idleMillis =
796 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700797 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800799 Settings.System.getInt(mContext.getContentResolver(),
800 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400802 if (DBG) {
803 Slog.d(TAG, "ACTION_SCREEN_ON");
804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 mAlarmManager.cancel(mIdleIntent);
806 mDeviceIdle = false;
807 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700808 // Once the screen is on, we are not keeping WIFI running
809 // because of any locks so clear that tracking immediately.
810 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700811 mWifiStateMachine.enableRssiPolling(true);
Irfan Sheriff8e86b892010-12-22 11:02:20 -0800812 mWifiStateMachine.enableAllNetworks();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700813 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400815 if (DBG) {
816 Slog.d(TAG, "ACTION_SCREEN_OFF");
817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700819 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 /*
821 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
822 * AND the "stay on while plugged in" setting doesn't match the
823 * current power conditions (i.e, not plugged in, plugged in to USB,
824 * or plugged in to AC).
825 */
826 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700827 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700828 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700829 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700830 // we don't have time to track down for this release. Delay instead,
831 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700832 // TODO - fix the race conditions and switch back to the immediate turn-off
833 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400834 if (DBG) {
835 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
836 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700837 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
838 // // do not keep Wifi awake when screen is off if Wifi is not associated
839 // mDeviceIdle = true;
840 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400841 } else {
842 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400843 if (DBG) {
844 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
845 + "ms");
846 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400847 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400851 if (DBG) {
852 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700855 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700856 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
858 /*
859 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
860 * AND we are transitioning from a state in which the device was supposed
861 * to stay awake to a state in which it is not supposed to stay awake.
862 * If "stay awake" state is not changing, we do nothing, to avoid resetting
863 * the already-set timer.
864 */
865 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400866 if (DBG) {
867 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
870 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
871 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400872 if (DBG) {
873 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 }
877 mPluggedType = pluggedType;
Irfan Sheriff65eaec82011-01-05 22:00:16 -0800878 } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
879 int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
880 BluetoothAdapter.STATE_DISCONNECTED);
881 mWifiStateMachine.sendBluetoothAdapterStateChange(state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
884
885 /**
886 * Determines whether the Wi-Fi chipset should stay awake or be put to
887 * sleep. Looks at the setting for the sleep policy and the current
888 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800889 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 * @see #shouldDeviceStayAwake(int, int)
891 */
892 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
Irfan Sheriff739f6bc2011-01-28 16:43:12 -0800893 //Never sleep as long as the user has not changed the settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
Irfan Sheriff96b10d62011-01-11 15:40:35 -0800895 Settings.System.WIFI_SLEEP_POLICY,
Irfan Sheriff739f6bc2011-01-28 16:43:12 -0800896 Settings.System.WIFI_SLEEP_POLICY_NEVER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897
898 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
899 // Never sleep
900 return true;
901 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
902 (pluggedType != 0)) {
903 // Never sleep while plugged, and we're plugged
904 return true;
905 } else {
906 // Default
907 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
908 }
909 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 /**
912 * Determine whether the bit value corresponding to {@code pluggedType} is set in
913 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
914 * of {@code 0} isn't really a plugged type, but rather an indication that the
915 * device isn't plugged in at all, there is no bit value corresponding to a
916 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700917 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 * @param stayAwakeConditions a bit string specifying which "plugged types" should
919 * keep the device (and hence Wi-Fi) awake.
920 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
921 * being made
922 * @return {@code true} if {@code pluggedType} indicates that the device is
923 * supposed to stay awake, {@code false} otherwise.
924 */
925 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
926 return (stayAwakeConditions & pluggedType) != 0;
927 }
928 };
929
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700930 private synchronized void reportStartWorkSource() {
931 mTmpWorkSource.clear();
932 if (mDeviceIdle) {
933 for (int i=0; i<mLocks.mList.size(); i++) {
934 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700935 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700936 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700937 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700938 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 private void updateWifiState() {
941 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700942 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -0700944 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
946 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff5876a422010-08-12 20:26:23 -0700947
948 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -0700950 }
951 /* If device is not idle, lockmode cannot be scan only */
952 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 strongestLockMode = WifiManager.WIFI_MODE_FULL;
954 }
955
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700956 /* Disable tethering when airplane mode is enabled */
957 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700958 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700959 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700960
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700961 if (wifiShouldBeEnabled) {
962 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700963 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700964 mWifiStateMachine.setWifiEnabled(true);
965 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700966 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700967 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff5876a422010-08-12 20:26:23 -0700968 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
969 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700971 mWifiStateMachine.requestCmWakeLock();
972 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700974 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700975 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
977 }
978
979 private void registerForBroadcasts() {
980 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
982 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
983 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
984 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff65eaec82011-01-05 22:00:16 -0800985 intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 mContext.registerReceiver(mReceiver, intentFilter);
987 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 private boolean isAirplaneSensitive() {
990 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
991 Settings.System.AIRPLANE_MODE_RADIOS);
992 return airplaneModeRadios == null
993 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
994 }
995
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700996 private boolean isAirplaneToggleable() {
997 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
998 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
999 return toggleableRadios != null
1000 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1001 }
1002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 /**
1004 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1005 * currently on.
1006 * @return {@code true} if airplane mode is on.
1007 */
1008 private boolean isAirplaneModeOn() {
1009 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1010 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1011 }
1012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 @Override
1014 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1015 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1016 != PackageManager.PERMISSION_GRANTED) {
1017 pw.println("Permission Denial: can't dump WifiService from from pid="
1018 + Binder.getCallingPid()
1019 + ", uid=" + Binder.getCallingUid());
1020 return;
1021 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001022 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 pw.println("Stay-awake conditions: " +
1024 Settings.System.getInt(mContext.getContentResolver(),
1025 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1026 pw.println();
1027
1028 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001029 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 pw.println();
1031 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001032 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 if (scanResults != null && scanResults.size() != 0) {
1034 pw.println(" BSSID Frequency RSSI Flags SSID");
1035 for (ScanResult r : scanResults) {
1036 pw.printf(" %17s %9d %5d %-16s %s%n",
1037 r.BSSID,
1038 r.frequency,
1039 r.level,
1040 r.capabilities,
1041 r.SSID == null ? "" : r.SSID);
1042 }
1043 }
1044 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001045 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001046 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001047 mScanLocksAcquired + " scan");
1048 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001049 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001050 mScanLocksReleased + " scan");
1051 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 pw.println("Locks held:");
1053 mLocks.dump(pw);
1054 }
1055
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001056 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001057 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1058 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
1060
1061 public void binderDied() {
1062 synchronized (mLocks) {
1063 releaseWifiLockLocked(mBinder);
1064 }
1065 }
1066
1067 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001068 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
1070 }
1071
1072 private class LockList {
1073 private List<WifiLock> mList;
1074
1075 private LockList() {
1076 mList = new ArrayList<WifiLock>();
1077 }
1078
1079 private synchronized boolean hasLocks() {
1080 return !mList.isEmpty();
1081 }
1082
1083 private synchronized int getStrongestLockMode() {
1084 if (mList.isEmpty()) {
1085 return WifiManager.WIFI_MODE_FULL;
1086 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001087
1088 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1089 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001091
1092 if (mFullLocksAcquired > mFullLocksReleased) {
1093 return WifiManager.WIFI_MODE_FULL;
1094 }
1095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 return WifiManager.WIFI_MODE_SCAN_ONLY;
1097 }
1098
1099 private void addLock(WifiLock lock) {
1100 if (findLockByBinder(lock.mBinder) < 0) {
1101 mList.add(lock);
1102 }
1103 }
1104
1105 private WifiLock removeLock(IBinder binder) {
1106 int index = findLockByBinder(binder);
1107 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001108 WifiLock ret = mList.remove(index);
1109 ret.unlinkDeathRecipient();
1110 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 } else {
1112 return null;
1113 }
1114 }
1115
1116 private int findLockByBinder(IBinder binder) {
1117 int size = mList.size();
1118 for (int i = size - 1; i >= 0; i--)
1119 if (mList.get(i).mBinder == binder)
1120 return i;
1121 return -1;
1122 }
1123
1124 private void dump(PrintWriter pw) {
1125 for (WifiLock l : mList) {
1126 pw.print(" ");
1127 pw.println(l);
1128 }
1129 }
1130 }
1131
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001132 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001133 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001134 return;
1135 }
1136 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1137 pid, uid, null);
1138 }
1139
1140 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001142 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1143 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1144 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1145 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1146 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 return false;
1148 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001149 if (ws != null && ws.size() == 0) {
1150 ws = null;
1151 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001152 if (ws != null) {
1153 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1154 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001155 if (ws == null) {
1156 ws = new WorkSource(Binder.getCallingUid());
1157 }
1158 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 synchronized (mLocks) {
1160 return acquireWifiLockLocked(wifiLock);
1161 }
1162 }
1163
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001164 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1165 switch(wifiLock.mMode) {
1166 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001167 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001168 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1169 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001170 case WifiManager.WIFI_MODE_SCAN_ONLY:
1171 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1172 break;
1173 }
1174 }
1175
1176 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1177 switch(wifiLock.mMode) {
1178 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001179 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001180 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1181 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001182 case WifiManager.WIFI_MODE_SCAN_ONLY:
1183 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1184 break;
1185 }
1186 }
1187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001189 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001192
The Android Open Source Project10592532009-03-18 17:39:46 -07001193 long ident = Binder.clearCallingIdentity();
1194 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001195 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001196 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001197 case WifiManager.WIFI_MODE_FULL:
1198 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001199 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001200 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1201 ++mFullHighPerfLocksAcquired;
1202 break;
1203
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001204 case WifiManager.WIFI_MODE_SCAN_ONLY:
1205 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001206 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001207 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001208
1209 // Be aggressive about adding new locks into the accounted state...
1210 // we want to over-report rather than under-report.
1211 reportStartWorkSource();
1212
1213 updateWifiState();
1214 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001215 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001216 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001217 } finally {
1218 Binder.restoreCallingIdentity(ident);
1219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
1221
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001222 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1223 int uid = Binder.getCallingUid();
1224 int pid = Binder.getCallingPid();
1225 if (ws != null && ws.size() == 0) {
1226 ws = null;
1227 }
1228 if (ws != null) {
1229 enforceWakeSourcePermission(uid, pid);
1230 }
1231 long ident = Binder.clearCallingIdentity();
1232 try {
1233 synchronized (mLocks) {
1234 int index = mLocks.findLockByBinder(lock);
1235 if (index < 0) {
1236 throw new IllegalArgumentException("Wifi lock not active");
1237 }
1238 WifiLock wl = mLocks.mList.get(index);
1239 noteReleaseWifiLock(wl);
1240 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1241 noteAcquireWifiLock(wl);
1242 }
1243 } catch (RemoteException e) {
1244 } finally {
1245 Binder.restoreCallingIdentity(ident);
1246 }
1247 }
1248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 public boolean releaseWifiLock(IBinder lock) {
1250 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1251 synchronized (mLocks) {
1252 return releaseWifiLockLocked(lock);
1253 }
1254 }
1255
1256 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001257 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001258
The Android Open Source Project10592532009-03-18 17:39:46 -07001259 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001260
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001261 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001262
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001263 hadLock = (wifiLock != null);
1264
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001265 long ident = Binder.clearCallingIdentity();
1266 try {
1267 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001268 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001269 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001270 case WifiManager.WIFI_MODE_FULL:
1271 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001272 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001273 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1274 ++mFullHighPerfLocksReleased;
1275 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001276 case WifiManager.WIFI_MODE_SCAN_ONLY:
1277 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001278 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001279 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001280 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001281
1282 // TODO - should this only happen if you hadLock?
1283 updateWifiState();
1284
1285 } catch (RemoteException e) {
1286 } finally {
1287 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001288 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001289
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001290 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001292
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001293 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001294 implements IBinder.DeathRecipient {
1295 String mTag;
1296 int mMode;
1297 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001298 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001299
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001300 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001301 super();
1302 mTag = tag;
1303 mMode = mode;
1304 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001305 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001306 try {
1307 mBinder.linkToDeath(this, 0);
1308 } catch (RemoteException e) {
1309 binderDied();
1310 }
1311 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001312
1313 void unlinkDeathRecipient() {
1314 mBinder.unlinkToDeath(this, 0);
1315 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001316 }
1317
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001318 private class Multicaster extends DeathRecipient {
1319 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001320 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001321 }
1322
1323 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001324 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001325 synchronized (mMulticasters) {
1326 int i = mMulticasters.indexOf(this);
1327 if (i != -1) {
1328 removeMulticasterLocked(i, mMode);
1329 }
1330 }
1331 }
1332
1333 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001334 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001335 }
1336
1337 public int getUid() {
1338 return mMode;
1339 }
1340 }
1341
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001342 public void initializeMulticastFiltering() {
1343 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001344
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001345 synchronized (mMulticasters) {
1346 // if anybody had requested filters be off, leave off
1347 if (mMulticasters.size() != 0) {
1348 return;
1349 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001350 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001351 }
1352 }
1353 }
1354
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001355 public void acquireMulticastLock(IBinder binder, String tag) {
1356 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001357
1358 synchronized (mMulticasters) {
1359 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001360 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001361 // Note that we could call stopPacketFiltering only when
1362 // our new size == 1 (first call), but this function won't
1363 // be called often and by making the stopPacket call each
1364 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001365 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001366 }
1367
1368 int uid = Binder.getCallingUid();
1369 Long ident = Binder.clearCallingIdentity();
1370 try {
1371 mBatteryStats.noteWifiMulticastEnabled(uid);
1372 } catch (RemoteException e) {
1373 } finally {
1374 Binder.restoreCallingIdentity(ident);
1375 }
1376 }
1377
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001378 public void releaseMulticastLock() {
1379 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001380
1381 int uid = Binder.getCallingUid();
1382 synchronized (mMulticasters) {
1383 mMulticastDisabled++;
1384 int size = mMulticasters.size();
1385 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001386 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001387 if ((m != null) && (m.getUid() == uid)) {
1388 removeMulticasterLocked(i, uid);
1389 }
1390 }
1391 }
1392 }
1393
1394 private void removeMulticasterLocked(int i, int uid)
1395 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001396 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001397
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001398 if (removed != null) {
1399 removed.unlinkDeathRecipient();
1400 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001401 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001402 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001403 }
1404
1405 Long ident = Binder.clearCallingIdentity();
1406 try {
1407 mBatteryStats.noteWifiMulticastDisabled(uid);
1408 } catch (RemoteException e) {
1409 } finally {
1410 Binder.restoreCallingIdentity(ident);
1411 }
1412 }
1413
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001414 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001415 enforceAccessPermission();
1416
1417 synchronized (mMulticasters) {
1418 return (mMulticasters.size() > 0);
1419 }
1420 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001421
1422 private void checkAndSetNotification() {
1423 // If we shouldn't place a notification on available networks, then
1424 // don't bother doing any of the following
1425 if (!mNotificationEnabled) return;
1426
1427 State state = mNetworkInfo.getState();
1428 if ((state == NetworkInfo.State.DISCONNECTED)
1429 || (state == NetworkInfo.State.UNKNOWN)) {
1430 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001431 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001432 if (scanResults != null) {
1433 int numOpenNetworks = 0;
1434 for (int i = scanResults.size() - 1; i >= 0; i--) {
1435 ScanResult scanResult = scanResults.get(i);
1436
1437 if (TextUtils.isEmpty(scanResult.capabilities)) {
1438 numOpenNetworks++;
1439 }
1440 }
1441
1442 if (numOpenNetworks > 0) {
1443 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1444 /*
1445 * We've scanned continuously at least
1446 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1447 * probably does not have a remembered network in range,
1448 * since otherwise supplicant would have tried to
1449 * associate and thus resetting this counter.
1450 */
1451 setNotificationVisible(true, numOpenNetworks, false, 0);
1452 }
1453 return;
1454 }
1455 }
1456 }
1457
1458 // No open networks in range, remove the notification
1459 setNotificationVisible(false, 0, false, 0);
1460 }
1461
1462 /**
1463 * Clears variables related to tracking whether a notification has been
1464 * shown recently and clears the current notification.
1465 */
1466 private void resetNotification() {
1467 mNotificationRepeatTime = 0;
1468 mNumScansSinceNetworkStateChange = 0;
1469 setNotificationVisible(false, 0, false, 0);
1470 }
1471
1472 /**
1473 * Display or don't display a notification that there are open Wi-Fi networks.
1474 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1475 * @param numNetworks the number networks seen
1476 * @param force {@code true} to force notification to be shown/not-shown,
1477 * even if it is already shown/not-shown.
1478 * @param delay time in milliseconds after which the notification should be made
1479 * visible or invisible.
1480 */
1481 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1482 int delay) {
1483
1484 // Since we use auto cancel on the notification, when the
1485 // mNetworksAvailableNotificationShown is true, the notification may
1486 // have actually been canceled. However, when it is false we know
1487 // for sure that it is not being shown (it will not be shown any other
1488 // place than here)
1489
1490 // If it should be hidden and it is already hidden, then noop
1491 if (!visible && !mNotificationShown && !force) {
1492 return;
1493 }
1494
1495 NotificationManager notificationManager = (NotificationManager) mContext
1496 .getSystemService(Context.NOTIFICATION_SERVICE);
1497
1498 Message message;
1499 if (visible) {
1500
1501 // Not enough time has passed to show the notification again
1502 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1503 return;
1504 }
1505
1506 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001507 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001508 mNotification = new Notification();
1509 mNotification.when = 0;
1510 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1511 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1512 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1513 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1514 }
1515
1516 CharSequence title = mContext.getResources().getQuantityText(
1517 com.android.internal.R.plurals.wifi_available, numNetworks);
1518 CharSequence details = mContext.getResources().getQuantityText(
1519 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1520 mNotification.tickerText = title;
1521 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1522
1523 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1524
1525 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001526 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001527 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001528 }
1529
Irfan Sheriff0d255342010-07-28 09:35:20 -07001530 mNotificationShown = visible;
1531 }
1532
1533 private class NotificationEnabledSettingObserver extends ContentObserver {
1534
1535 public NotificationEnabledSettingObserver(Handler handler) {
1536 super(handler);
1537 }
1538
1539 public void register() {
1540 ContentResolver cr = mContext.getContentResolver();
1541 cr.registerContentObserver(Settings.Secure.getUriFor(
1542 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1543 mNotificationEnabled = getValue();
1544 }
1545
1546 @Override
1547 public void onChange(boolean selfChange) {
1548 super.onChange(selfChange);
1549
1550 mNotificationEnabled = getValue();
1551 resetNotification();
1552 }
1553
1554 private boolean getValue() {
1555 return Settings.Secure.getInt(mContext.getContentResolver(),
1556 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1557 }
1558 }
1559
1560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561}