blob: 56fae819a8dc2b621a7e49ef634330a20b5a7fd5 [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();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800504 if (wifiConfig == null)
505 return;
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800506 int authType = wifiConfig.getAuthType();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800507 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
Irfan Sheriffec8d23a2011-02-16 17:00:33 -0800508 Settings.Secure.putInt(cr, Settings.Secure.WIFI_AP_SECURITY, authType);
509 if (authType != KeyMgmt.NONE)
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800510 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
511 }
512
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800513 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700514 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800515 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700516 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700517 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700518 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800519 }
520
521 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700522 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800523 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700524 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700525 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700526 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800527 }
528
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700529 /**
530 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700531 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700532 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700533 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700534 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800535 }
536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 /**
538 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
539 * @return the list of configured networks
540 */
541 public List<WifiConfiguration> getConfiguredNetworks() {
542 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700543 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800544 }
545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 /**
547 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
548 * @return the supplicant-assigned identifier for the new or updated
549 * network if the operation succeeds, or {@code -1} if it fails
550 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800551 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700553 if (mChannel != null) {
554 return mWifiStateMachine.syncAddOrUpdateNetwork(mChannel, config);
555 } else {
556 Slog.e(TAG, "mChannel is not initialized");
557 return -1;
558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 }
560
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700561 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
563 * @param netId the integer that identifies the network configuration
564 * to the supplicant
565 * @return {@code true} if the operation succeeded
566 */
567 public boolean removeNetwork(int netId) {
568 enforceChangePermission();
Wink Saville4b7ba092010-10-20 15:37:41 -0700569 if (mChannel != null) {
570 return mWifiStateMachine.syncRemoveNetwork(mChannel, netId);
571 } else {
572 Slog.e(TAG, "mChannel is not initialized");
573 return false;
574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
576
577 /**
578 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
579 * @param netId the integer that identifies the network configuration
580 * to the supplicant
581 * @param disableOthers if true, disable all other networks.
582 * @return {@code true} if the operation succeeded
583 */
584 public boolean enableNetwork(int netId, boolean disableOthers) {
585 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700586 if (mChannel != null) {
587 return mWifiStateMachine.syncEnableNetwork(mChannel, netId, disableOthers);
588 } else {
589 Slog.e(TAG, "mChannel is not initialized");
590 return false;
591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 }
593
594 /**
595 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
596 * @param netId the integer that identifies the network configuration
597 * to the supplicant
598 * @return {@code true} if the operation succeeded
599 */
600 public boolean disableNetwork(int netId) {
601 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700602 if (mChannel != null) {
603 return mWifiStateMachine.syncDisableNetwork(mChannel, netId);
604 } else {
605 Slog.e(TAG, "mChannel is not initialized");
606 return false;
607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 }
609
610 /**
611 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
612 * @return the Wi-Fi information, contained in {@link WifiInfo}.
613 */
614 public WifiInfo getConnectionInfo() {
615 enforceAccessPermission();
616 /*
617 * Make sure we have the latest information, by sending
618 * a status request to the supplicant.
619 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700620 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 }
622
623 /**
624 * Return the results of the most recent access point scan, in the form of
625 * a list of {@link ScanResult} objects.
626 * @return the list of results
627 */
628 public List<ScanResult> getScanResults() {
629 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700630 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 }
632
633 /**
634 * Tell the supplicant to persist the current list of configured networks.
635 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700636 *
637 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 */
639 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700640 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 enforceChangePermission();
Irfan Sheriff1406bcb2010-10-28 14:41:39 -0700642 if (mChannel != null) {
643 return mWifiStateMachine.syncSaveConfig(mChannel);
644 } else {
645 Slog.e(TAG, "mChannel is not initialized");
646 return false;
647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 }
649
650 /**
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700651 * Set the country code
652 * @param countryCode ISO 3166 country code.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700653 * @param persist {@code true} if the setting should be remembered.
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700654 *
655 * The persist behavior exists so that wifi can fall back to the last
656 * persisted country code on a restart, when the locale information is
657 * not available from telephony.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 */
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700659 public void setCountryCode(String countryCode, boolean persist) {
660 Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
661 " with persist set to " + persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 enforceChangePermission();
Irfan Sheriffed4f28b2010-10-29 15:32:10 -0700663 mWifiStateMachine.setCountryCode(countryCode, persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 }
665
666 /**
Irfan Sheriff36f74132010-11-04 16:57:37 -0700667 * Set the operational frequency band
668 * @param band One of
669 * {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
670 * {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
671 * {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
672 * @param persist {@code true} if the setting should be remembered.
673 *
674 */
675 public void setFrequencyBand(int band, boolean persist) {
676 enforceChangePermission();
677 if (!isDualBandSupported()) return;
678 Slog.i(TAG, "WifiService trying to set frequency band to " + band +
679 " with persist set to " + persist);
680 mWifiStateMachine.setFrequencyBand(band, persist);
681 }
682
683
684 /**
685 * Get the operational frequency band
686 */
687 public int getFrequencyBand() {
688 enforceAccessPermission();
689 return mWifiStateMachine.getFrequencyBand();
690 }
691
692 public boolean isDualBandSupported() {
693 //TODO: Should move towards adding a driver API that checks at runtime
694 return mContext.getResources().getBoolean(
695 com.android.internal.R.bool.config_wifi_dual_band_support);
696 }
697
698 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 * Return the DHCP-assigned addresses from the last successful DHCP request,
700 * if any.
701 * @return the DHCP information
702 */
703 public DhcpInfo getDhcpInfo() {
704 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700705 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 }
707
Irfan Sheriff0d255342010-07-28 09:35:20 -0700708 /**
709 * see {@link android.net.wifi.WifiManager#startWifi}
710 *
711 */
712 public void startWifi() {
713 enforceChangePermission();
714 /* TODO: may be add permissions for access only to connectivity service
715 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
716 * of WifiLock & device idle status unless wifi enabled status is toggled
717 */
718
719 mWifiStateMachine.setDriverStart(true);
720 mWifiStateMachine.reconnectCommand();
721 }
722
723 /**
724 * see {@link android.net.wifi.WifiManager#stopWifi}
725 *
726 */
727 public void stopWifi() {
728 enforceChangePermission();
729 /* TODO: may be add permissions for access only to connectivity service
730 * TODO: if a stop is issued, wifi is brought up only by startWifi
731 * unless wifi enabled status is toggled
732 */
733 mWifiStateMachine.setDriverStart(false);
734 }
735
736
737 /**
738 * see {@link android.net.wifi.WifiManager#addToBlacklist}
739 *
740 */
741 public void addToBlacklist(String bssid) {
742 enforceChangePermission();
743
744 mWifiStateMachine.addToBlacklist(bssid);
745 }
746
747 /**
748 * see {@link android.net.wifi.WifiManager#clearBlacklist}
749 *
750 */
751 public void clearBlacklist() {
752 enforceChangePermission();
753
754 mWifiStateMachine.clearBlacklist();
755 }
756
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700757 public void connectNetworkWithId(int networkId) {
758 enforceChangePermission();
759 mWifiStateMachine.connectNetwork(networkId);
760 }
761
762 public void connectNetworkWithConfig(WifiConfiguration config) {
763 enforceChangePermission();
764 mWifiStateMachine.connectNetwork(config);
765 }
766
767 public void saveNetwork(WifiConfiguration config) {
768 enforceChangePermission();
769 mWifiStateMachine.saveNetwork(config);
770 }
771
772 public void forgetNetwork(int netId) {
773 enforceChangePermission();
774 mWifiStateMachine.forgetNetwork(netId);
775 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700776
Irfan Sheriffe4c56c92011-01-12 16:33:58 -0800777 public WpsResult startWps(WpsConfiguration config) {
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700778 enforceChangePermission();
779 if (mChannel != null) {
Irfan Sheriff02fb46a2010-12-08 11:27:37 -0800780 return mWifiStateMachine.startWps(mChannel, config);
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700781 } else {
782 Slog.e(TAG, "mChannel is not initialized");
Irfan Sheriffe4c56c92011-01-12 16:33:58 -0800783 return new WpsResult(WpsResult.Status.FAILURE);
Irfan Sherifff235c5a2010-10-21 16:44:48 -0700784 }
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700785 }
786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
788 @Override
789 public void onReceive(Context context, Intent intent) {
790 String action = intent.getAction();
791
Doug Zongker43866e02010-01-07 12:09:54 -0800792 long idleMillis =
793 Settings.Secure.getLong(mContext.getContentResolver(),
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700794 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800796 Settings.System.getInt(mContext.getContentResolver(),
797 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400799 if (DBG) {
800 Slog.d(TAG, "ACTION_SCREEN_ON");
801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 mAlarmManager.cancel(mIdleIntent);
803 mDeviceIdle = false;
804 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700805 // Once the screen is on, we are not keeping WIFI running
806 // because of any locks so clear that tracking immediately.
807 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700808 mWifiStateMachine.enableRssiPolling(true);
Irfan Sheriff8e86b892010-12-22 11:02:20 -0800809 mWifiStateMachine.enableAllNetworks();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700810 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400812 if (DBG) {
813 Slog.d(TAG, "ACTION_SCREEN_OFF");
814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700816 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 /*
818 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
819 * AND the "stay on while plugged in" setting doesn't match the
820 * current power conditions (i.e, not plugged in, plugged in to USB,
821 * or plugged in to AC).
822 */
823 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700824 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700825 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700826 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700827 // we don't have time to track down for this release. Delay instead,
828 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700829 // TODO - fix the race conditions and switch back to the immediate turn-off
830 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato431bb222010-10-18 19:13:23 -0400831 if (DBG) {
832 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
833 }
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700834 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
835 // // do not keep Wifi awake when screen is off if Wifi is not associated
836 // mDeviceIdle = true;
837 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400838 } else {
839 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400840 if (DBG) {
841 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis
842 + "ms");
843 }
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400844 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato431bb222010-10-18 19:13:23 -0400848 if (DBG) {
849 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700852 reportStartWorkSource();
Irfan Sheriff4f5f7c92010-10-14 17:01:27 -0700853 updateWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
855 /*
856 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
857 * AND we are transitioning from a state in which the device was supposed
858 * to stay awake to a state in which it is not supposed to stay awake.
859 * If "stay awake" state is not changing, we do nothing, to avoid resetting
860 * the already-set timer.
861 */
862 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato431bb222010-10-18 19:13:23 -0400863 if (DBG) {
864 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
867 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
868 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato431bb222010-10-18 19:13:23 -0400869 if (DBG) {
870 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874 mPluggedType = pluggedType;
Irfan Sheriff65eaec82011-01-05 22:00:16 -0800875 } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
876 int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
877 BluetoothAdapter.STATE_DISCONNECTED);
878 mWifiStateMachine.sendBluetoothAdapterStateChange(state);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 }
881
882 /**
883 * Determines whether the Wi-Fi chipset should stay awake or be put to
884 * sleep. Looks at the setting for the sleep policy and the current
885 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800886 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 * @see #shouldDeviceStayAwake(int, int)
888 */
889 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
Irfan Sheriff739f6bc2011-01-28 16:43:12 -0800890 //Never sleep as long as the user has not changed the settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
Irfan Sheriff96b10d62011-01-11 15:40:35 -0800892 Settings.System.WIFI_SLEEP_POLICY,
Irfan Sheriff739f6bc2011-01-28 16:43:12 -0800893 Settings.System.WIFI_SLEEP_POLICY_NEVER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894
895 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
896 // Never sleep
897 return true;
898 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
899 (pluggedType != 0)) {
900 // Never sleep while plugged, and we're plugged
901 return true;
902 } else {
903 // Default
904 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
905 }
906 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 /**
909 * Determine whether the bit value corresponding to {@code pluggedType} is set in
910 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
911 * of {@code 0} isn't really a plugged type, but rather an indication that the
912 * device isn't plugged in at all, there is no bit value corresponding to a
913 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700914 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 * @param stayAwakeConditions a bit string specifying which "plugged types" should
916 * keep the device (and hence Wi-Fi) awake.
917 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
918 * being made
919 * @return {@code true} if {@code pluggedType} indicates that the device is
920 * supposed to stay awake, {@code false} otherwise.
921 */
922 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
923 return (stayAwakeConditions & pluggedType) != 0;
924 }
925 };
926
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700927 private synchronized void reportStartWorkSource() {
928 mTmpWorkSource.clear();
929 if (mDeviceIdle) {
930 for (int i=0; i<mLocks.mList.size(); i++) {
931 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700932 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700933 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700934 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700935 }
Jaikumar Ganesh7440fc22010-09-27 17:04:14 -0700936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 private void updateWifiState() {
938 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700939 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 boolean lockHeld = mLocks.hasLocks();
Irfan Sheriff5876a422010-08-12 20:26:23 -0700941 int strongestLockMode = WifiManager.WIFI_MODE_FULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
943 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
Irfan Sheriff5876a422010-08-12 20:26:23 -0700944
945 if (lockHeld) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 strongestLockMode = mLocks.getStrongestLockMode();
Irfan Sheriff5876a422010-08-12 20:26:23 -0700947 }
948 /* If device is not idle, lockmode cannot be scan only */
949 if (!mDeviceIdle && strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 strongestLockMode = WifiManager.WIFI_MODE_FULL;
951 }
952
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700953 /* Disable tethering when airplane mode is enabled */
954 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700955 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700956 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700957
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700958 if (wifiShouldBeEnabled) {
959 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700960 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700961 mWifiStateMachine.setWifiEnabled(true);
962 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700963 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700964 mWifiStateMachine.setDriverStart(true);
Irfan Sheriff5876a422010-08-12 20:26:23 -0700965 mWifiStateMachine.setHighPerfModeEnabled(strongestLockMode
966 == WifiManager.WIFI_MODE_FULL_HIGH_PERF);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700968 mWifiStateMachine.requestCmWakeLock();
969 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700971 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700972 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
974 }
975
976 private void registerForBroadcasts() {
977 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
979 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
980 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
981 intentFilter.addAction(ACTION_DEVICE_IDLE);
Irfan Sheriff65eaec82011-01-05 22:00:16 -0800982 intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 mContext.registerReceiver(mReceiver, intentFilter);
984 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 private boolean isAirplaneSensitive() {
987 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
988 Settings.System.AIRPLANE_MODE_RADIOS);
989 return airplaneModeRadios == null
990 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
991 }
992
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700993 private boolean isAirplaneToggleable() {
994 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
995 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
996 return toggleableRadios != null
997 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
998 }
999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 /**
1001 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1002 * currently on.
1003 * @return {@code true} if airplane mode is on.
1004 */
1005 private boolean isAirplaneModeOn() {
1006 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1007 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1008 }
1009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 @Override
1011 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1012 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1013 != PackageManager.PERMISSION_GRANTED) {
1014 pw.println("Permission Denial: can't dump WifiService from from pid="
1015 + Binder.getCallingPid()
1016 + ", uid=" + Binder.getCallingUid());
1017 return;
1018 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001019 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 pw.println("Stay-awake conditions: " +
1021 Settings.System.getInt(mContext.getContentResolver(),
1022 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1023 pw.println();
1024
1025 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001026 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 pw.println();
1028 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001029 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 if (scanResults != null && scanResults.size() != 0) {
1031 pw.println(" BSSID Frequency RSSI Flags SSID");
1032 for (ScanResult r : scanResults) {
1033 pw.printf(" %17s %9d %5d %-16s %s%n",
1034 r.BSSID,
1035 r.frequency,
1036 r.level,
1037 r.capabilities,
1038 r.SSID == null ? "" : r.SSID);
1039 }
1040 }
1041 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001042 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001043 mFullHighPerfLocksAcquired + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001044 mScanLocksAcquired + " scan");
1045 pw.println("Locks released: " + mFullLocksReleased + " full, " +
Irfan Sheriff5876a422010-08-12 20:26:23 -07001046 mFullHighPerfLocksReleased + " full high perf, " +
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001047 mScanLocksReleased + " scan");
1048 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 pw.println("Locks held:");
1050 mLocks.dump(pw);
1051 }
1052
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001053 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001054 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1055 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
1057
1058 public void binderDied() {
1059 synchronized (mLocks) {
1060 releaseWifiLockLocked(mBinder);
1061 }
1062 }
1063
1064 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001065 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
1067 }
1068
1069 private class LockList {
1070 private List<WifiLock> mList;
1071
1072 private LockList() {
1073 mList = new ArrayList<WifiLock>();
1074 }
1075
1076 private synchronized boolean hasLocks() {
1077 return !mList.isEmpty();
1078 }
1079
1080 private synchronized int getStrongestLockMode() {
1081 if (mList.isEmpty()) {
1082 return WifiManager.WIFI_MODE_FULL;
1083 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001084
1085 if (mFullHighPerfLocksAcquired > mFullHighPerfLocksReleased) {
1086 return WifiManager.WIFI_MODE_FULL_HIGH_PERF;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 }
Irfan Sheriff5876a422010-08-12 20:26:23 -07001088
1089 if (mFullLocksAcquired > mFullLocksReleased) {
1090 return WifiManager.WIFI_MODE_FULL;
1091 }
1092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 return WifiManager.WIFI_MODE_SCAN_ONLY;
1094 }
1095
1096 private void addLock(WifiLock lock) {
1097 if (findLockByBinder(lock.mBinder) < 0) {
1098 mList.add(lock);
1099 }
1100 }
1101
1102 private WifiLock removeLock(IBinder binder) {
1103 int index = findLockByBinder(binder);
1104 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001105 WifiLock ret = mList.remove(index);
1106 ret.unlinkDeathRecipient();
1107 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 } else {
1109 return null;
1110 }
1111 }
1112
1113 private int findLockByBinder(IBinder binder) {
1114 int size = mList.size();
1115 for (int i = size - 1; i >= 0; i--)
1116 if (mList.get(i).mBinder == binder)
1117 return i;
1118 return -1;
1119 }
1120
1121 private void dump(PrintWriter pw) {
1122 for (WifiLock l : mList) {
1123 pw.print(" ");
1124 pw.println(l);
1125 }
1126 }
1127 }
1128
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001129 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001130 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001131 return;
1132 }
1133 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1134 pid, uid, null);
1135 }
1136
1137 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Irfan Sheriff5876a422010-08-12 20:26:23 -07001139 if (lockMode != WifiManager.WIFI_MODE_FULL &&
1140 lockMode != WifiManager.WIFI_MODE_SCAN_ONLY &&
1141 lockMode != WifiManager.WIFI_MODE_FULL_HIGH_PERF) {
1142 Slog.e(TAG, "Illegal argument, lockMode= " + lockMode);
1143 if (DBG) throw new IllegalArgumentException("lockMode=" + lockMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 return false;
1145 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001146 if (ws != null && ws.size() == 0) {
1147 ws = null;
1148 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001149 if (ws != null) {
1150 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1151 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001152 if (ws == null) {
1153 ws = new WorkSource(Binder.getCallingUid());
1154 }
1155 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 synchronized (mLocks) {
1157 return acquireWifiLockLocked(wifiLock);
1158 }
1159 }
1160
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001161 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1162 switch(wifiLock.mMode) {
1163 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001164 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001165 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1166 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001167 case WifiManager.WIFI_MODE_SCAN_ONLY:
1168 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1169 break;
1170 }
1171 }
1172
1173 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1174 switch(wifiLock.mMode) {
1175 case WifiManager.WIFI_MODE_FULL:
Irfan Sheriff5876a422010-08-12 20:26:23 -07001176 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001177 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1178 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001179 case WifiManager.WIFI_MODE_SCAN_ONLY:
1180 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1181 break;
1182 }
1183 }
1184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001186 if (DBG) Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001189
The Android Open Source Project10592532009-03-18 17:39:46 -07001190 long ident = Binder.clearCallingIdentity();
1191 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001192 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001193 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001194 case WifiManager.WIFI_MODE_FULL:
1195 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001196 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001197 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1198 ++mFullHighPerfLocksAcquired;
1199 break;
1200
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001201 case WifiManager.WIFI_MODE_SCAN_ONLY:
1202 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001203 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001204 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001205
1206 // Be aggressive about adding new locks into the accounted state...
1207 // we want to over-report rather than under-report.
1208 reportStartWorkSource();
1209
1210 updateWifiState();
1211 return true;
The Android Open Source Project10592532009-03-18 17:39:46 -07001212 } catch (RemoteException e) {
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001213 return false;
The Android Open Source Project10592532009-03-18 17:39:46 -07001214 } finally {
1215 Binder.restoreCallingIdentity(ident);
1216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 }
1218
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001219 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1220 int uid = Binder.getCallingUid();
1221 int pid = Binder.getCallingPid();
1222 if (ws != null && ws.size() == 0) {
1223 ws = null;
1224 }
1225 if (ws != null) {
1226 enforceWakeSourcePermission(uid, pid);
1227 }
1228 long ident = Binder.clearCallingIdentity();
1229 try {
1230 synchronized (mLocks) {
1231 int index = mLocks.findLockByBinder(lock);
1232 if (index < 0) {
1233 throw new IllegalArgumentException("Wifi lock not active");
1234 }
1235 WifiLock wl = mLocks.mList.get(index);
1236 noteReleaseWifiLock(wl);
1237 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1238 noteAcquireWifiLock(wl);
1239 }
1240 } catch (RemoteException e) {
1241 } finally {
1242 Binder.restoreCallingIdentity(ident);
1243 }
1244 }
1245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 public boolean releaseWifiLock(IBinder lock) {
1247 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1248 synchronized (mLocks) {
1249 return releaseWifiLockLocked(lock);
1250 }
1251 }
1252
1253 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001254 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001255
The Android Open Source Project10592532009-03-18 17:39:46 -07001256 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001257
Irfan Sheriffc89dd542010-09-28 08:40:54 -07001258 if (DBG) Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001259
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001260 hadLock = (wifiLock != null);
1261
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001262 long ident = Binder.clearCallingIdentity();
1263 try {
1264 if (hadLock) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001265 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001266 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001267 case WifiManager.WIFI_MODE_FULL:
1268 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001269 break;
Irfan Sheriff5876a422010-08-12 20:26:23 -07001270 case WifiManager.WIFI_MODE_FULL_HIGH_PERF:
1271 ++mFullHighPerfLocksReleased;
1272 break;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001273 case WifiManager.WIFI_MODE_SCAN_ONLY:
1274 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001275 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001276 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001277 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001278
1279 // TODO - should this only happen if you hadLock?
1280 updateWifiState();
1281
1282 } catch (RemoteException e) {
1283 } finally {
1284 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001285 }
Dianne Hackbornecfd7f72010-10-08 14:23:40 -07001286
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001287 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001289
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001290 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001291 implements IBinder.DeathRecipient {
1292 String mTag;
1293 int mMode;
1294 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001295 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001296
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001297 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001298 super();
1299 mTag = tag;
1300 mMode = mode;
1301 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001302 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001303 try {
1304 mBinder.linkToDeath(this, 0);
1305 } catch (RemoteException e) {
1306 binderDied();
1307 }
1308 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001309
1310 void unlinkDeathRecipient() {
1311 mBinder.unlinkToDeath(this, 0);
1312 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001313 }
1314
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001315 private class Multicaster extends DeathRecipient {
1316 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001317 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001318 }
1319
1320 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001321 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001322 synchronized (mMulticasters) {
1323 int i = mMulticasters.indexOf(this);
1324 if (i != -1) {
1325 removeMulticasterLocked(i, mMode);
1326 }
1327 }
1328 }
1329
1330 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001331 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001332 }
1333
1334 public int getUid() {
1335 return mMode;
1336 }
1337 }
1338
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001339 public void initializeMulticastFiltering() {
1340 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001341
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001342 synchronized (mMulticasters) {
1343 // if anybody had requested filters be off, leave off
1344 if (mMulticasters.size() != 0) {
1345 return;
1346 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001347 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001348 }
1349 }
1350 }
1351
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001352 public void acquireMulticastLock(IBinder binder, String tag) {
1353 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001354
1355 synchronized (mMulticasters) {
1356 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001357 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001358 // Note that we could call stopPacketFiltering only when
1359 // our new size == 1 (first call), but this function won't
1360 // be called often and by making the stopPacket call each
1361 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001362 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001363 }
1364
1365 int uid = Binder.getCallingUid();
1366 Long ident = Binder.clearCallingIdentity();
1367 try {
1368 mBatteryStats.noteWifiMulticastEnabled(uid);
1369 } catch (RemoteException e) {
1370 } finally {
1371 Binder.restoreCallingIdentity(ident);
1372 }
1373 }
1374
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001375 public void releaseMulticastLock() {
1376 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001377
1378 int uid = Binder.getCallingUid();
1379 synchronized (mMulticasters) {
1380 mMulticastDisabled++;
1381 int size = mMulticasters.size();
1382 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001383 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001384 if ((m != null) && (m.getUid() == uid)) {
1385 removeMulticasterLocked(i, uid);
1386 }
1387 }
1388 }
1389 }
1390
1391 private void removeMulticasterLocked(int i, int uid)
1392 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001393 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001394
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001395 if (removed != null) {
1396 removed.unlinkDeathRecipient();
1397 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001398 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001399 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001400 }
1401
1402 Long ident = Binder.clearCallingIdentity();
1403 try {
1404 mBatteryStats.noteWifiMulticastDisabled(uid);
1405 } catch (RemoteException e) {
1406 } finally {
1407 Binder.restoreCallingIdentity(ident);
1408 }
1409 }
1410
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001411 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001412 enforceAccessPermission();
1413
1414 synchronized (mMulticasters) {
1415 return (mMulticasters.size() > 0);
1416 }
1417 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001418
1419 private void checkAndSetNotification() {
1420 // If we shouldn't place a notification on available networks, then
1421 // don't bother doing any of the following
1422 if (!mNotificationEnabled) return;
1423
1424 State state = mNetworkInfo.getState();
1425 if ((state == NetworkInfo.State.DISCONNECTED)
1426 || (state == NetworkInfo.State.UNKNOWN)) {
1427 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001428 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001429 if (scanResults != null) {
1430 int numOpenNetworks = 0;
1431 for (int i = scanResults.size() - 1; i >= 0; i--) {
1432 ScanResult scanResult = scanResults.get(i);
1433
1434 if (TextUtils.isEmpty(scanResult.capabilities)) {
1435 numOpenNetworks++;
1436 }
1437 }
1438
1439 if (numOpenNetworks > 0) {
1440 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1441 /*
1442 * We've scanned continuously at least
1443 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1444 * probably does not have a remembered network in range,
1445 * since otherwise supplicant would have tried to
1446 * associate and thus resetting this counter.
1447 */
1448 setNotificationVisible(true, numOpenNetworks, false, 0);
1449 }
1450 return;
1451 }
1452 }
1453 }
1454
1455 // No open networks in range, remove the notification
1456 setNotificationVisible(false, 0, false, 0);
1457 }
1458
1459 /**
1460 * Clears variables related to tracking whether a notification has been
1461 * shown recently and clears the current notification.
1462 */
1463 private void resetNotification() {
1464 mNotificationRepeatTime = 0;
1465 mNumScansSinceNetworkStateChange = 0;
1466 setNotificationVisible(false, 0, false, 0);
1467 }
1468
1469 /**
1470 * Display or don't display a notification that there are open Wi-Fi networks.
1471 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1472 * @param numNetworks the number networks seen
1473 * @param force {@code true} to force notification to be shown/not-shown,
1474 * even if it is already shown/not-shown.
1475 * @param delay time in milliseconds after which the notification should be made
1476 * visible or invisible.
1477 */
1478 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1479 int delay) {
1480
1481 // Since we use auto cancel on the notification, when the
1482 // mNetworksAvailableNotificationShown is true, the notification may
1483 // have actually been canceled. However, when it is false we know
1484 // for sure that it is not being shown (it will not be shown any other
1485 // place than here)
1486
1487 // If it should be hidden and it is already hidden, then noop
1488 if (!visible && !mNotificationShown && !force) {
1489 return;
1490 }
1491
1492 NotificationManager notificationManager = (NotificationManager) mContext
1493 .getSystemService(Context.NOTIFICATION_SERVICE);
1494
1495 Message message;
1496 if (visible) {
1497
1498 // Not enough time has passed to show the notification again
1499 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1500 return;
1501 }
1502
1503 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001504 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001505 mNotification = new Notification();
1506 mNotification.when = 0;
1507 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1508 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1509 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1510 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1511 }
1512
1513 CharSequence title = mContext.getResources().getQuantityText(
1514 com.android.internal.R.plurals.wifi_available, numNetworks);
1515 CharSequence details = mContext.getResources().getQuantityText(
1516 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1517 mNotification.tickerText = title;
1518 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1519
1520 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1521
1522 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001523 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001524 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001525 }
1526
Irfan Sheriff0d255342010-07-28 09:35:20 -07001527 mNotificationShown = visible;
1528 }
1529
1530 private class NotificationEnabledSettingObserver extends ContentObserver {
1531
1532 public NotificationEnabledSettingObserver(Handler handler) {
1533 super(handler);
1534 }
1535
1536 public void register() {
1537 ContentResolver cr = mContext.getContentResolver();
1538 cr.registerContentObserver(Settings.Secure.getUriFor(
1539 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1540 mNotificationEnabled = getValue();
1541 }
1542
1543 @Override
1544 public void onChange(boolean selfChange) {
1545 super.onChange(selfChange);
1546
1547 mNotificationEnabled = getValue();
1548 resetNotification();
1549 }
1550
1551 private boolean getValue() {
1552 return Settings.Secure.getInt(mContext.getContentResolver(),
1553 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1554 }
1555 }
1556
1557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558}