blob: 7b2a57037e97ccd5711ee8a92416ed28bef02efd [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;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070023import android.bluetooth.BluetoothA2dp;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080024import android.bluetooth.BluetoothDevice;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.BroadcastReceiver;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070031import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.net.wifi.IWifiManager;
33import android.net.wifi.WifiInfo;
34import android.net.wifi.WifiManager;
Irfan Sheriff0d255342010-07-28 09:35:20 -070035import android.net.wifi.WifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.wifi.ScanResult;
37import android.net.wifi.WifiConfiguration;
San Mehat0310f9a2009-07-07 10:49:47 -070038import android.net.wifi.SupplicantState;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080039import android.net.wifi.WifiConfiguration.KeyMgmt;
Irfan Sheriff5321aef2010-02-12 12:35:59 -080040import android.net.ConnectivityManager;
41import android.net.InterfaceConfiguration;
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;
The Android Open Source Project10592532009-03-18 17:39:46 -070066import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080067import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069/**
70 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070071 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 *
73 * @hide
74 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070075//TODO: Clean up multiple locks and implement WifiService
76// as a SM to track soft AP/client/adhoc bring up based
77// on device idle state, airplane mode and boot.
78
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079public class WifiService extends IWifiManager.Stub {
80 private static final String TAG = "WifiService";
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070081 private static final boolean DBG = true;
82
Irfan Sheriff0d255342010-07-28 09:35:20 -070083 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084
85 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
87 private AlarmManager mAlarmManager;
88 private PendingIntent mIdleIntent;
89 private static final int IDLE_REQUEST = 0;
90 private boolean mScreenOff;
91 private boolean mDeviceIdle;
92 private int mPluggedType;
93
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070094 // true if the user enabled Wifi while in airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070095 private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -070098 // some wifi lock statistics
99 private int mFullLocksAcquired;
100 private int mFullLocksReleased;
101 private int mScanLocksAcquired;
102 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700103
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700104 private final List<Multicaster> mMulticasters =
105 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700106 private int mMulticastEnabled;
107 private int mMulticastDisabled;
108
The Android Open Source Project10592532009-03-18 17:39:46 -0700109 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800110
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800111 ConnectivityManager mCm;
112 private String[] mWifiRegexs;
113
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 */
121 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 /**
124 * Number of allowed radio frequency channels in various regulatory domains.
125 * This list is sufficient for 802.11b/g networks (2.4GHz range).
126 */
127 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
128
129 private static final String ACTION_DEVICE_IDLE =
130 "com.android.server.WifiManager.action.DEVICE_IDLE";
131
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700132 private boolean mIsReceiverRegistered = false;
133
Irfan Sheriff0d255342010-07-28 09:35:20 -0700134
135 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
136
137 // Variables relating to the 'available networks' notification
138 /**
139 * The icon to show in the 'available networks' notification. This will also
140 * be the ID of the Notification given to the NotificationManager.
141 */
142 private static final int ICON_NETWORKS_AVAILABLE =
143 com.android.internal.R.drawable.stat_notify_wifi_in_range;
144 /**
145 * When a notification is shown, we wait this amount before possibly showing it again.
146 */
147 private final long NOTIFICATION_REPEAT_DELAY_MS;
148 /**
149 * Whether the user has set the setting to show the 'available networks' notification.
150 */
151 private boolean mNotificationEnabled;
152 /**
153 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
154 */
155 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
156 /**
157 * The {@link System#currentTimeMillis()} must be at least this value for us
158 * to show the notification again.
159 */
160 private long mNotificationRepeatTime;
161 /**
162 * The Notification object given to the NotificationManager.
163 */
164 private Notification mNotification;
165 /**
166 * Whether the notification is being shown, as set by us. That is, if the
167 * user cancels the notification, we will not receive the callback so this
168 * will still be true. We only guarantee if this is false, then the
169 * notification is not showing.
170 */
171 private boolean mNotificationShown;
172 /**
173 * The number of continuous scans that must occur before consider the
174 * supplicant in a scanning state. This allows supplicant to associate with
175 * remembered networks that are in the scan results.
176 */
177 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
178 /**
179 * The number of scans since the last network state change. When this
180 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
181 * supplicant to actually be scanning. When the network state changes to
182 * something other than scanning, we reset this to 0.
183 */
184 private int mNumScansSinceNetworkStateChange;
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700185
186 /**
187 * Temporary for computing UIDS that are responsible for starting WIFI.
188 * Protected by mWifiStateTracker lock.
189 */
190 private final WorkSource mTmpWorkSource = new WorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700191
192 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700194 mWifiStateMachine = new WifiStateMachine(mContext);
195 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700196 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
199 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
200 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
201
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700202 HandlerThread wifiThread = new HandlerThread("WifiService");
203 wifiThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 mContext.registerReceiver(
206 new BroadcastReceiver() {
207 @Override
208 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700209 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700210 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700211 // on airplane disable, restore Wifi if the saved state indicates so
212 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
213 persistWifiEnabled(true);
214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 updateWifiState();
216 }
217 },
218 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
219
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800220 mContext.registerReceiver(
221 new BroadcastReceiver() {
222 @Override
223 public void onReceive(Context context, Intent intent) {
224
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700225 ArrayList<String> available = intent.getStringArrayListExtra(
226 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
227 ArrayList<String> active = intent.getStringArrayListExtra(
228 ConnectivityManager.EXTRA_ACTIVE_TETHER);
229 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800230
231 }
232 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700233
234 IntentFilter filter = new IntentFilter();
235 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
236 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
237 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
238
239 mContext.registerReceiver(
240 new BroadcastReceiver() {
241 @Override
242 public void onReceive(Context context, Intent intent) {
243 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
244 // reset & clear notification on any wifi state change
245 resetNotification();
246 } else if (intent.getAction().equals(
247 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
248 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
249 WifiManager.EXTRA_NETWORK_INFO);
250 // reset & clear notification on a network connect & disconnect
251 switch(mNetworkInfo.getDetailedState()) {
252 case CONNECTED:
253 case DISCONNECTED:
254 resetNotification();
255 break;
256 }
257 } else if (intent.getAction().equals(
258 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
259 checkAndSetNotification();
260 }
261 }
262 }, filter);
263
264 // Setting is in seconds
265 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
266 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
267 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
268 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800269 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800270
Irfan Sheriff7b009782010-03-11 16:37:45 -0800271 /**
272 * Check if Wi-Fi needs to be enabled and start
273 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700274 *
275 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800276 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700277 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700278 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700279 boolean wifiEnabled = !isAirplaneModeOn()
280 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800281 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
282 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700283 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800284 }
285
286 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
287
288 boolean wifiTethered = false;
289 boolean wifiAvailable = false;
290
291 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
292 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
293
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700294 if (mCm == null) {
295 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
296 }
297
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800298 mWifiRegexs = mCm.getTetherableWifiRegexs();
299
300 for (String intf : available) {
301 for (String regex : mWifiRegexs) {
302 if (intf.matches(regex)) {
303
304 InterfaceConfiguration ifcg = null;
305 try {
306 ifcg = service.getInterfaceConfig(intf);
307 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700308 /* IP/netmask: 192.168.43.1/255.255.255.0 */
309 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800310 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
311 ifcg.interfaceFlags = "up";
312
313 service.setInterfaceConfig(intf, ifcg);
314 }
315 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800316 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700317 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800318 return;
319 }
320
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800321 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700322 Slog.e(TAG, "Error tethering on " + intf);
323 setWifiApEnabled(null, false);
324 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800325 }
326 break;
327 }
328 }
329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 }
331
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700332 private boolean testAndClearWifiSavedState() {
333 final ContentResolver cr = mContext.getContentResolver();
334 int wifiSavedState = 0;
335 try {
336 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
337 if(wifiSavedState == 1)
338 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
339 } catch (Settings.SettingNotFoundException e) {
340 ;
341 }
342 return (wifiSavedState == 1);
343 }
344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 private boolean getPersistedWifiEnabled() {
346 final ContentResolver cr = mContext.getContentResolver();
347 try {
348 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
349 } catch (Settings.SettingNotFoundException e) {
350 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
351 return false;
352 }
353 }
354
355 private void persistWifiEnabled(boolean enabled) {
356 final ContentResolver cr = mContext.getContentResolver();
357 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
358 }
359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 /**
361 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700362 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 */
364 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700365 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700366 return mWifiStateMachine.syncPingSupplicant();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 }
368
369 /**
370 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700372 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700374 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 }
376
377 private void enforceAccessPermission() {
378 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
379 "WifiService");
380 }
381
382 private void enforceChangePermission() {
383 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
384 "WifiService");
385
386 }
387
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700388 private void enforceMulticastChangePermission() {
389 mContext.enforceCallingOrSelfPermission(
390 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
391 "WifiService");
392 }
393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700395 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
396 * @param enable {@code true} to enable, {@code false} to disable.
397 * @return {@code true} if the enable/disable operation was
398 * started or is already in the queue.
399 */
400 public synchronized boolean setWifiEnabled(boolean enable) {
401 enforceChangePermission();
402
403 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700404 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700405 }
406
407 // set a flag if the user is enabling Wifi while in airplane mode
408 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
409 mAirplaneModeOverwridden.set(true);
410 }
411
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700412 if (enable) {
413 reportStartWorkSource();
414 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700415 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700416
417 /*
418 * Caller might not have WRITE_SECURE_SETTINGS,
419 * only CHANGE_WIFI_STATE is enforced
420 */
421 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700422 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700423 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700424
425 if (enable) {
426 if (!mIsReceiverRegistered) {
427 registerForBroadcasts();
428 mIsReceiverRegistered = true;
429 }
430 } else if (mIsReceiverRegistered){
431 mContext.unregisterReceiver(mReceiver);
432 mIsReceiverRegistered = false;
433 }
434
435 return true;
436 }
437
438 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 * see {@link WifiManager#getWifiState()}
440 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
441 * {@link WifiManager#WIFI_STATE_DISABLING},
442 * {@link WifiManager#WIFI_STATE_ENABLED},
443 * {@link WifiManager#WIFI_STATE_ENABLING},
444 * {@link WifiManager#WIFI_STATE_UNKNOWN}
445 */
446 public int getWifiEnabledState() {
447 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700448 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 }
450
451 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700452 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800453 * @param wifiConfig SSID, security and channel details as
454 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700455 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800456 * @return {@code true} if the start operation was
457 * started or is already in the queue.
458 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700459 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800460 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800461
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700462 if (enabled) {
463 /* Use default config if there is no existing config */
464 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
465 wifiConfig = new WifiConfiguration();
466 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
467 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
468 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700469 /*
470 * Caller might not have WRITE_SECURE_SETTINGS,
471 * only CHANGE_WIFI_STATE is enforced
472 */
473 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700474 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700475 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800476 }
477
Irfan Sheriff0d255342010-07-28 09:35:20 -0700478 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700479
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800480 return true;
481 }
482
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700483 /**
484 * see {@link WifiManager#getWifiApState()}
485 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
486 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
487 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
488 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
489 * {@link WifiManager#WIFI_AP_STATE_FAILED}
490 */
491 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700492 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700493 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700494 }
495
496 /**
497 * see {@link WifiManager#getWifiApConfiguration()}
498 * @return soft access point configuration
499 */
500 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800501 final ContentResolver cr = mContext.getContentResolver();
502 WifiConfiguration wifiConfig = new WifiConfiguration();
503 int authType;
504 try {
505 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
506 if (wifiConfig.SSID == null)
507 return null;
508 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
509 wifiConfig.allowedKeyManagement.set(authType);
510 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
511 return wifiConfig;
512 } catch (Settings.SettingNotFoundException e) {
513 Slog.e(TAG,"AP settings not found, returning");
514 return null;
515 }
516 }
517
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700518 /**
519 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
520 * @param wifiConfig WifiConfiguration details for soft access point
521 */
522 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700523 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800524 final ContentResolver cr = mContext.getContentResolver();
525 boolean isWpa;
526 if (wifiConfig == null)
527 return;
528 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
529 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
530 Settings.Secure.putInt(cr,
531 Settings.Secure.WIFI_AP_SECURITY,
532 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
533 if (isWpa)
534 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
535 }
536
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800537 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700538 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800539 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700540 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700541 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700542 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800543 }
544
545 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700546 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800547 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700548 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700549 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700550 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800551 }
552
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700553 /**
554 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700555 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700556 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700557 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700558 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800559 }
560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 /**
562 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
563 * @return the list of configured networks
564 */
565 public List<WifiConfiguration> getConfiguredNetworks() {
566 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700567 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800568 }
569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 /**
571 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
572 * @return the supplicant-assigned identifier for the new or updated
573 * network if the operation succeeds, or {@code -1} if it fails
574 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800575 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700577 return mWifiStateMachine.syncAddOrUpdateNetwork(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 }
579
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700580 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
582 * @param netId the integer that identifies the network configuration
583 * to the supplicant
584 * @return {@code true} if the operation succeeded
585 */
586 public boolean removeNetwork(int netId) {
587 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700588 return mWifiStateMachine.syncRemoveNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 }
590
591 /**
592 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
593 * @param netId the integer that identifies the network configuration
594 * to the supplicant
595 * @param disableOthers if true, disable all other networks.
596 * @return {@code true} if the operation succeeded
597 */
598 public boolean enableNetwork(int netId, boolean disableOthers) {
599 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700600 return mWifiStateMachine.syncEnableNetwork(netId, disableOthers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
602
603 /**
604 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
605 * @param netId the integer that identifies the network configuration
606 * to the supplicant
607 * @return {@code true} if the operation succeeded
608 */
609 public boolean disableNetwork(int netId) {
610 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700611 return mWifiStateMachine.syncDisableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 }
613
614 /**
615 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
616 * @return the Wi-Fi information, contained in {@link WifiInfo}.
617 */
618 public WifiInfo getConnectionInfo() {
619 enforceAccessPermission();
620 /*
621 * Make sure we have the latest information, by sending
622 * a status request to the supplicant.
623 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700624 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 }
626
627 /**
628 * Return the results of the most recent access point scan, in the form of
629 * a list of {@link ScanResult} objects.
630 * @return the list of results
631 */
632 public List<ScanResult> getScanResults() {
633 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700634 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 }
636
637 /**
638 * Tell the supplicant to persist the current list of configured networks.
639 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700640 *
641 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 */
643 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700644 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700646 return mWifiStateMachine.syncSaveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 }
648
649 /**
650 * Set the number of radio frequency channels that are allowed to be used
651 * in the current regulatory domain. This method should be used only
652 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700653 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 * persisted as a Secure setting.
655 * @param numChannels the number of allowed channels. Must be greater than 0
656 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700657 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
659 * {@code numChannels} is outside the valid range.
660 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700661 public synchronized boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800662 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700663 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -0700665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 /*
667 * Validate the argument. We'd like to let the Wi-Fi driver do this,
668 * but if Wi-Fi isn't currently enabled, that's not possible, and
669 * we want to persist the setting anyway,so that it will take
670 * effect when Wi-Fi does become enabled.
671 */
672 boolean found = false;
673 for (int validChan : sValidRegulatoryChannelCounts) {
674 if (validChan == numChannels) {
675 found = true;
676 break;
677 }
678 }
679 if (!found) {
680 return false;
681 }
682
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700683 if (persist) {
684 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -0700685 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
686 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700687 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700688
Irfan Sheriff0d255342010-07-28 09:35:20 -0700689 mWifiStateMachine.setNumAllowedChannels(numChannels);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700690
691 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 }
693
694 /**
695 * Return the number of frequency channels that are allowed
696 * to be used in the current regulatory domain.
697 * @return the number of allowed channels, or {@code -1} if an error occurs
698 */
699 public int getNumAllowedChannels() {
700 int numChannels;
701
702 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800703
704 /*
705 * If we can't get the value from the driver (e.g., because
706 * Wi-Fi is not currently enabled), get the value from
707 * Settings.
708 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700709 numChannels = mWifiStateMachine.getNumAllowedChannels();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800710 if (numChannels < 0) {
711 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
712 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
713 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 }
715 return numChannels;
716 }
717
718 /**
719 * Return the list of valid values for the number of allowed radio channels
720 * for various regulatory domains.
721 * @return the list of channel counts
722 */
723 public int[] getValidChannelCounts() {
724 enforceAccessPermission();
725 return sValidRegulatoryChannelCounts;
726 }
727
728 /**
729 * Return the DHCP-assigned addresses from the last successful DHCP request,
730 * if any.
731 * @return the DHCP information
732 */
733 public DhcpInfo getDhcpInfo() {
734 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700735 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 }
737
Irfan Sheriff0d255342010-07-28 09:35:20 -0700738 /**
739 * see {@link android.net.wifi.WifiManager#startWifi}
740 *
741 */
742 public void startWifi() {
743 enforceChangePermission();
744 /* TODO: may be add permissions for access only to connectivity service
745 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
746 * of WifiLock & device idle status unless wifi enabled status is toggled
747 */
748
749 mWifiStateMachine.setDriverStart(true);
750 mWifiStateMachine.reconnectCommand();
751 }
752
753 /**
754 * see {@link android.net.wifi.WifiManager#stopWifi}
755 *
756 */
757 public void stopWifi() {
758 enforceChangePermission();
759 /* TODO: may be add permissions for access only to connectivity service
760 * TODO: if a stop is issued, wifi is brought up only by startWifi
761 * unless wifi enabled status is toggled
762 */
763 mWifiStateMachine.setDriverStart(false);
764 }
765
766
767 /**
768 * see {@link android.net.wifi.WifiManager#addToBlacklist}
769 *
770 */
771 public void addToBlacklist(String bssid) {
772 enforceChangePermission();
773
774 mWifiStateMachine.addToBlacklist(bssid);
775 }
776
777 /**
778 * see {@link android.net.wifi.WifiManager#clearBlacklist}
779 *
780 */
781 public void clearBlacklist() {
782 enforceChangePermission();
783
784 mWifiStateMachine.clearBlacklist();
785 }
786
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700787 public void connectNetworkWithId(int networkId) {
788 enforceChangePermission();
789 mWifiStateMachine.connectNetwork(networkId);
790 }
791
792 public void connectNetworkWithConfig(WifiConfiguration config) {
793 enforceChangePermission();
794 mWifiStateMachine.connectNetwork(config);
795 }
796
797 public void saveNetwork(WifiConfiguration config) {
798 enforceChangePermission();
799 mWifiStateMachine.saveNetwork(config);
800 }
801
802 public void forgetNetwork(int netId) {
803 enforceChangePermission();
804 mWifiStateMachine.forgetNetwork(netId);
805 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700806
Irfan Sheriff5ee89802010-09-16 17:53:34 -0700807 public void startWpsPbc(String bssid) {
808 enforceChangePermission();
809 mWifiStateMachine.startWpsPbc(bssid);
810 }
811
812 public void startWpsPin(String bssid, int apPin) {
813 enforceChangePermission();
814 mWifiStateMachine.startWpsPin(bssid, apPin);
815 }
816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
818 @Override
819 public void onReceive(Context context, Intent intent) {
820 String action = intent.getAction();
821
Doug Zongker43866e02010-01-07 12:09:54 -0800822 long idleMillis =
823 Settings.Secure.getLong(mContext.getContentResolver(),
824 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800826 Settings.System.getInt(mContext.getContentResolver(),
827 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800829 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 mAlarmManager.cancel(mIdleIntent);
831 mDeviceIdle = false;
832 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700833 // Once the screen is on, we are not keeping WIFI running
834 // because of any locks so clear that tracking immediately.
835 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700836 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800838 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700840 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 /*
842 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
843 * AND the "stay on while plugged in" setting doesn't match the
844 * current power conditions (i.e, not plugged in, plugged in to USB,
845 * or plugged in to AC).
846 */
847 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700848 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700849 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700850 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700851 // we don't have time to track down for this release. Delay instead,
852 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700853 // TODO - fix the race conditions and switch back to the immediate turn-off
854 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -0800855 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700856 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
857 // // do not keep Wifi awake when screen is off if Wifi is not associated
858 // mDeviceIdle = true;
859 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400860 } else {
861 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800862 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400863 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 }
866 /* we can return now -- there's nothing to do until we get the idle intent back */
867 return;
868 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800869 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700871 reportStartWorkSource();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
873 /*
874 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
875 * AND we are transitioning from a state in which the device was supposed
876 * to stay awake to a state in which it is not supposed to stay awake.
877 * If "stay awake" state is not changing, we do nothing, to avoid resetting
878 * the already-set timer.
879 */
880 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800881 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
883 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
884 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800885 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
887 mPluggedType = pluggedType;
888 return;
889 }
890 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -0700891 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800892 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
893 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
894 boolean isBluetoothPlaying = false;
895 for (BluetoothDevice sink : sinks) {
896 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
897 isBluetoothPlaying = true;
898 }
899 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700900 mWifiStateMachine.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 } else {
903 return;
904 }
905
906 updateWifiState();
907 }
908
909 /**
910 * Determines whether the Wi-Fi chipset should stay awake or be put to
911 * sleep. Looks at the setting for the sleep policy and the current
912 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800913 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 * @see #shouldDeviceStayAwake(int, int)
915 */
916 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
917 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
918 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
919
920 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
921 // Never sleep
922 return true;
923 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
924 (pluggedType != 0)) {
925 // Never sleep while plugged, and we're plugged
926 return true;
927 } else {
928 // Default
929 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
930 }
931 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 /**
934 * Determine whether the bit value corresponding to {@code pluggedType} is set in
935 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
936 * of {@code 0} isn't really a plugged type, but rather an indication that the
937 * device isn't plugged in at all, there is no bit value corresponding to a
938 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700939 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 * @param stayAwakeConditions a bit string specifying which "plugged types" should
941 * keep the device (and hence Wi-Fi) awake.
942 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
943 * being made
944 * @return {@code true} if {@code pluggedType} indicates that the device is
945 * supposed to stay awake, {@code false} otherwise.
946 */
947 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
948 return (stayAwakeConditions & pluggedType) != 0;
949 }
950 };
951
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700952 private synchronized void reportStartWorkSource() {
953 mTmpWorkSource.clear();
954 if (mDeviceIdle) {
955 for (int i=0; i<mLocks.mList.size(); i++) {
956 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700957 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700958 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700959 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700960 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 private void updateWifiState() {
963 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700964 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 boolean lockHeld = mLocks.hasLocks();
966 int strongestLockMode;
967 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
968 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
969 if (mDeviceIdle && lockHeld) {
970 strongestLockMode = mLocks.getStrongestLockMode();
971 } else {
972 strongestLockMode = WifiManager.WIFI_MODE_FULL;
973 }
974
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700975 /* Disable tethering when airplane mode is enabled */
976 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700977 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700978 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700979
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700980 if (wifiShouldBeEnabled) {
981 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700982 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700983 mWifiStateMachine.setWifiEnabled(true);
984 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700985 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700986 mWifiStateMachine.setDriverStart(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700988 mWifiStateMachine.requestCmWakeLock();
989 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700991 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700992 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
994 }
995
996 private void registerForBroadcasts() {
997 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
999 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
1000 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
1001 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -07001002 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 mContext.registerReceiver(mReceiver, intentFilter);
1004 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -08001005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 private boolean isAirplaneSensitive() {
1007 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
1008 Settings.System.AIRPLANE_MODE_RADIOS);
1009 return airplaneModeRadios == null
1010 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1011 }
1012
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001013 private boolean isAirplaneToggleable() {
1014 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1015 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1016 return toggleableRadios != null
1017 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1018 }
1019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 /**
1021 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1022 * currently on.
1023 * @return {@code true} if airplane mode is on.
1024 */
1025 private boolean isAirplaneModeOn() {
1026 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1027 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1028 }
1029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 @Override
1031 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1032 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1033 != PackageManager.PERMISSION_GRANTED) {
1034 pw.println("Permission Denial: can't dump WifiService from from pid="
1035 + Binder.getCallingPid()
1036 + ", uid=" + Binder.getCallingUid());
1037 return;
1038 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001039 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 pw.println("Stay-awake conditions: " +
1041 Settings.System.getInt(mContext.getContentResolver(),
1042 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1043 pw.println();
1044
1045 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001046 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 pw.println();
1048 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001049 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 if (scanResults != null && scanResults.size() != 0) {
1051 pw.println(" BSSID Frequency RSSI Flags SSID");
1052 for (ScanResult r : scanResults) {
1053 pw.printf(" %17s %9d %5d %-16s %s%n",
1054 r.BSSID,
1055 r.frequency,
1056 r.level,
1057 r.capabilities,
1058 r.SSID == null ? "" : r.SSID);
1059 }
1060 }
1061 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001062 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1063 mScanLocksAcquired + " scan");
1064 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1065 mScanLocksReleased + " scan");
1066 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 pw.println("Locks held:");
1068 mLocks.dump(pw);
1069 }
1070
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001071 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001072 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1073 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
1075
1076 public void binderDied() {
1077 synchronized (mLocks) {
1078 releaseWifiLockLocked(mBinder);
1079 }
1080 }
1081
1082 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001083 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 }
1085 }
1086
1087 private class LockList {
1088 private List<WifiLock> mList;
1089
1090 private LockList() {
1091 mList = new ArrayList<WifiLock>();
1092 }
1093
1094 private synchronized boolean hasLocks() {
1095 return !mList.isEmpty();
1096 }
1097
1098 private synchronized int getStrongestLockMode() {
1099 if (mList.isEmpty()) {
1100 return WifiManager.WIFI_MODE_FULL;
1101 }
1102 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001103 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 return WifiManager.WIFI_MODE_FULL;
1105 }
1106 }
1107 return WifiManager.WIFI_MODE_SCAN_ONLY;
1108 }
1109
1110 private void addLock(WifiLock lock) {
1111 if (findLockByBinder(lock.mBinder) < 0) {
1112 mList.add(lock);
1113 }
1114 }
1115
1116 private WifiLock removeLock(IBinder binder) {
1117 int index = findLockByBinder(binder);
1118 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001119 WifiLock ret = mList.remove(index);
1120 ret.unlinkDeathRecipient();
1121 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 } else {
1123 return null;
1124 }
1125 }
1126
1127 private int findLockByBinder(IBinder binder) {
1128 int size = mList.size();
1129 for (int i = size - 1; i >= 0; i--)
1130 if (mList.get(i).mBinder == binder)
1131 return i;
1132 return -1;
1133 }
1134
1135 private void dump(PrintWriter pw) {
1136 for (WifiLock l : mList) {
1137 pw.print(" ");
1138 pw.println(l);
1139 }
1140 }
1141 }
1142
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001143 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001144 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001145 return;
1146 }
1147 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1148 pid, uid, null);
1149 }
1150
1151 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1153 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1154 return false;
1155 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001156 if (ws != null) {
1157 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1158 }
1159 if (ws != null && ws.size() == 0) {
1160 ws = null;
1161 }
1162 if (ws == null) {
1163 ws = new WorkSource(Binder.getCallingUid());
1164 }
1165 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 synchronized (mLocks) {
1167 return acquireWifiLockLocked(wifiLock);
1168 }
1169 }
1170
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001171 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1172 switch(wifiLock.mMode) {
1173 case WifiManager.WIFI_MODE_FULL:
1174 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1175 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001176 case WifiManager.WIFI_MODE_SCAN_ONLY:
1177 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1178 break;
1179 }
1180 }
1181
1182 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1183 switch(wifiLock.mMode) {
1184 case WifiManager.WIFI_MODE_FULL:
1185 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1186 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001187 case WifiManager.WIFI_MODE_SCAN_ONLY:
1188 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1189 break;
1190 }
1191 }
1192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001194 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001197
The Android Open Source Project10592532009-03-18 17:39:46 -07001198 long ident = Binder.clearCallingIdentity();
1199 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001200 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001201 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001202 case WifiManager.WIFI_MODE_FULL:
1203 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001204 break;
1205 case WifiManager.WIFI_MODE_SCAN_ONLY:
1206 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001207 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001208 }
1209 } catch (RemoteException e) {
1210 } finally {
1211 Binder.restoreCallingIdentity(ident);
1212 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001213
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001214 // Be aggressive about adding new locks into the accounted state...
1215 // we want to over-report rather than under-report.
1216 reportStartWorkSource();
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 updateWifiState();
1219 return true;
1220 }
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
Joe Onorato8a9b2202010-02-26 18:56:32 -08001261 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
1265 if (hadLock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001266 long ident = Binder.clearCallingIdentity();
1267 try {
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;
1273 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 }
1277 } catch (RemoteException e) {
1278 } finally {
1279 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001280 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001281 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001282 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001284 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001286
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001287 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001288 implements IBinder.DeathRecipient {
1289 String mTag;
1290 int mMode;
1291 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001292 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001293
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001294 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001295 super();
1296 mTag = tag;
1297 mMode = mode;
1298 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001299 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001300 try {
1301 mBinder.linkToDeath(this, 0);
1302 } catch (RemoteException e) {
1303 binderDied();
1304 }
1305 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001306
1307 void unlinkDeathRecipient() {
1308 mBinder.unlinkToDeath(this, 0);
1309 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001310 }
1311
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001312 private class Multicaster extends DeathRecipient {
1313 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001314 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001315 }
1316
1317 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001318 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001319 synchronized (mMulticasters) {
1320 int i = mMulticasters.indexOf(this);
1321 if (i != -1) {
1322 removeMulticasterLocked(i, mMode);
1323 }
1324 }
1325 }
1326
1327 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001328 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001329 }
1330
1331 public int getUid() {
1332 return mMode;
1333 }
1334 }
1335
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001336 public void initializeMulticastFiltering() {
1337 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001338
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001339 synchronized (mMulticasters) {
1340 // if anybody had requested filters be off, leave off
1341 if (mMulticasters.size() != 0) {
1342 return;
1343 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001344 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001345 }
1346 }
1347 }
1348
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001349 public void acquireMulticastLock(IBinder binder, String tag) {
1350 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001351
1352 synchronized (mMulticasters) {
1353 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001354 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001355 // Note that we could call stopPacketFiltering only when
1356 // our new size == 1 (first call), but this function won't
1357 // be called often and by making the stopPacket call each
1358 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001359 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001360 }
1361
1362 int uid = Binder.getCallingUid();
1363 Long ident = Binder.clearCallingIdentity();
1364 try {
1365 mBatteryStats.noteWifiMulticastEnabled(uid);
1366 } catch (RemoteException e) {
1367 } finally {
1368 Binder.restoreCallingIdentity(ident);
1369 }
1370 }
1371
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001372 public void releaseMulticastLock() {
1373 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001374
1375 int uid = Binder.getCallingUid();
1376 synchronized (mMulticasters) {
1377 mMulticastDisabled++;
1378 int size = mMulticasters.size();
1379 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001380 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001381 if ((m != null) && (m.getUid() == uid)) {
1382 removeMulticasterLocked(i, uid);
1383 }
1384 }
1385 }
1386 }
1387
1388 private void removeMulticasterLocked(int i, int uid)
1389 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001390 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001391
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001392 if (removed != null) {
1393 removed.unlinkDeathRecipient();
1394 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001395 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001396 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001397 }
1398
1399 Long ident = Binder.clearCallingIdentity();
1400 try {
1401 mBatteryStats.noteWifiMulticastDisabled(uid);
1402 } catch (RemoteException e) {
1403 } finally {
1404 Binder.restoreCallingIdentity(ident);
1405 }
1406 }
1407
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001408 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001409 enforceAccessPermission();
1410
1411 synchronized (mMulticasters) {
1412 return (mMulticasters.size() > 0);
1413 }
1414 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001415
1416 private void checkAndSetNotification() {
1417 // If we shouldn't place a notification on available networks, then
1418 // don't bother doing any of the following
1419 if (!mNotificationEnabled) return;
1420
1421 State state = mNetworkInfo.getState();
1422 if ((state == NetworkInfo.State.DISCONNECTED)
1423 || (state == NetworkInfo.State.UNKNOWN)) {
1424 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001425 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001426 if (scanResults != null) {
1427 int numOpenNetworks = 0;
1428 for (int i = scanResults.size() - 1; i >= 0; i--) {
1429 ScanResult scanResult = scanResults.get(i);
1430
1431 if (TextUtils.isEmpty(scanResult.capabilities)) {
1432 numOpenNetworks++;
1433 }
1434 }
1435
1436 if (numOpenNetworks > 0) {
1437 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1438 /*
1439 * We've scanned continuously at least
1440 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1441 * probably does not have a remembered network in range,
1442 * since otherwise supplicant would have tried to
1443 * associate and thus resetting this counter.
1444 */
1445 setNotificationVisible(true, numOpenNetworks, false, 0);
1446 }
1447 return;
1448 }
1449 }
1450 }
1451
1452 // No open networks in range, remove the notification
1453 setNotificationVisible(false, 0, false, 0);
1454 }
1455
1456 /**
1457 * Clears variables related to tracking whether a notification has been
1458 * shown recently and clears the current notification.
1459 */
1460 private void resetNotification() {
1461 mNotificationRepeatTime = 0;
1462 mNumScansSinceNetworkStateChange = 0;
1463 setNotificationVisible(false, 0, false, 0);
1464 }
1465
1466 /**
1467 * Display or don't display a notification that there are open Wi-Fi networks.
1468 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1469 * @param numNetworks the number networks seen
1470 * @param force {@code true} to force notification to be shown/not-shown,
1471 * even if it is already shown/not-shown.
1472 * @param delay time in milliseconds after which the notification should be made
1473 * visible or invisible.
1474 */
1475 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1476 int delay) {
1477
1478 // Since we use auto cancel on the notification, when the
1479 // mNetworksAvailableNotificationShown is true, the notification may
1480 // have actually been canceled. However, when it is false we know
1481 // for sure that it is not being shown (it will not be shown any other
1482 // place than here)
1483
1484 // If it should be hidden and it is already hidden, then noop
1485 if (!visible && !mNotificationShown && !force) {
1486 return;
1487 }
1488
1489 NotificationManager notificationManager = (NotificationManager) mContext
1490 .getSystemService(Context.NOTIFICATION_SERVICE);
1491
1492 Message message;
1493 if (visible) {
1494
1495 // Not enough time has passed to show the notification again
1496 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1497 return;
1498 }
1499
1500 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001501 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001502 mNotification = new Notification();
1503 mNotification.when = 0;
1504 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1505 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1506 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1507 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1508 }
1509
1510 CharSequence title = mContext.getResources().getQuantityText(
1511 com.android.internal.R.plurals.wifi_available, numNetworks);
1512 CharSequence details = mContext.getResources().getQuantityText(
1513 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1514 mNotification.tickerText = title;
1515 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1516
1517 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1518
1519 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001520 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001521 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001522 }
1523
Irfan Sheriff0d255342010-07-28 09:35:20 -07001524 mNotificationShown = visible;
1525 }
1526
1527 private class NotificationEnabledSettingObserver extends ContentObserver {
1528
1529 public NotificationEnabledSettingObserver(Handler handler) {
1530 super(handler);
1531 }
1532
1533 public void register() {
1534 ContentResolver cr = mContext.getContentResolver();
1535 cr.registerContentObserver(Settings.Secure.getUriFor(
1536 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1537 mNotificationEnabled = getValue();
1538 }
1539
1540 @Override
1541 public void onChange(boolean selfChange) {
1542 super.onChange(selfChange);
1543
1544 mNotificationEnabled = getValue();
1545 resetNotification();
1546 }
1547
1548 private boolean getValue() {
1549 return Settings.Secure.getInt(mContext.getContentResolver(),
1550 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1551 }
1552 }
1553
1554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555}