blob: c52567a268d254678b5f185c654b67b3e5653d79 [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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
808 @Override
809 public void onReceive(Context context, Intent intent) {
810 String action = intent.getAction();
811
Doug Zongker43866e02010-01-07 12:09:54 -0800812 long idleMillis =
813 Settings.Secure.getLong(mContext.getContentResolver(),
814 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800816 Settings.System.getInt(mContext.getContentResolver(),
817 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800819 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 mAlarmManager.cancel(mIdleIntent);
821 mDeviceIdle = false;
822 mScreenOff = false;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700823 // Once the screen is on, we are not keeping WIFI running
824 // because of any locks so clear that tracking immediately.
825 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700826 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800828 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700830 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 /*
832 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
833 * AND the "stay on while plugged in" setting doesn't match the
834 * current power conditions (i.e, not plugged in, plugged in to USB,
835 * or plugged in to AC).
836 */
837 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700838 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700839 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700840 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700841 // we don't have time to track down for this release. Delay instead,
842 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700843 // TODO - fix the race conditions and switch back to the immediate turn-off
844 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -0800845 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700846 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
847 // // do not keep Wifi awake when screen is off if Wifi is not associated
848 // mDeviceIdle = true;
849 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400850 } else {
851 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800852 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400853 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 /* we can return now -- there's nothing to do until we get the idle intent back */
857 return;
858 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800859 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 mDeviceIdle = true;
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700861 reportStartWorkSource();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
863 /*
864 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
865 * AND we are transitioning from a state in which the device was supposed
866 * to stay awake to a state in which it is not supposed to stay awake.
867 * If "stay awake" state is not changing, we do nothing, to avoid resetting
868 * the already-set timer.
869 */
870 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
873 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
874 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800875 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
877 mPluggedType = pluggedType;
878 return;
879 }
880 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -0700881 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800882 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
883 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
884 boolean isBluetoothPlaying = false;
885 for (BluetoothDevice sink : sinks) {
886 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
887 isBluetoothPlaying = true;
888 }
889 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700890 mWifiStateMachine.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 } else {
893 return;
894 }
895
896 updateWifiState();
897 }
898
899 /**
900 * Determines whether the Wi-Fi chipset should stay awake or be put to
901 * sleep. Looks at the setting for the sleep policy and the current
902 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800903 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 * @see #shouldDeviceStayAwake(int, int)
905 */
906 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
907 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
908 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
909
910 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
911 // Never sleep
912 return true;
913 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
914 (pluggedType != 0)) {
915 // Never sleep while plugged, and we're plugged
916 return true;
917 } else {
918 // Default
919 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
920 }
921 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 /**
924 * Determine whether the bit value corresponding to {@code pluggedType} is set in
925 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
926 * of {@code 0} isn't really a plugged type, but rather an indication that the
927 * device isn't plugged in at all, there is no bit value corresponding to a
928 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700929 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 * @param stayAwakeConditions a bit string specifying which "plugged types" should
931 * keep the device (and hence Wi-Fi) awake.
932 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
933 * being made
934 * @return {@code true} if {@code pluggedType} indicates that the device is
935 * supposed to stay awake, {@code false} otherwise.
936 */
937 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
938 return (stayAwakeConditions & pluggedType) != 0;
939 }
940 };
941
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700942 private synchronized void reportStartWorkSource() {
943 mTmpWorkSource.clear();
944 if (mDeviceIdle) {
945 for (int i=0; i<mLocks.mList.size(); i++) {
946 mTmpWorkSource.add(mLocks.mList.get(i).mWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700947 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700948 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700949 mWifiStateMachine.updateBatteryWorkSource(mTmpWorkSource);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700950 }
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 private void updateWifiState() {
953 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700954 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 boolean lockHeld = mLocks.hasLocks();
956 int strongestLockMode;
957 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
958 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
959 if (mDeviceIdle && lockHeld) {
960 strongestLockMode = mLocks.getStrongestLockMode();
961 } else {
962 strongestLockMode = WifiManager.WIFI_MODE_FULL;
963 }
964
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700965 /* Disable tethering when airplane mode is enabled */
966 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700967 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700968 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700969
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700970 if (wifiShouldBeEnabled) {
971 if (wifiShouldBeStarted) {
Dianne Hackborn03f3cb02010-09-17 23:12:26 -0700972 reportStartWorkSource();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700973 mWifiStateMachine.setWifiEnabled(true);
974 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700975 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700976 mWifiStateMachine.setDriverStart(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700978 mWifiStateMachine.requestCmWakeLock();
979 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700981 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700982 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 }
984 }
985
986 private void registerForBroadcasts() {
987 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
989 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
990 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
991 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -0700992 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 mContext.registerReceiver(mReceiver, intentFilter);
994 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 private boolean isAirplaneSensitive() {
997 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
998 Settings.System.AIRPLANE_MODE_RADIOS);
999 return airplaneModeRadios == null
1000 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
1001 }
1002
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -07001003 private boolean isAirplaneToggleable() {
1004 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
1005 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
1006 return toggleableRadios != null
1007 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
1008 }
1009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 /**
1011 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
1012 * currently on.
1013 * @return {@code true} if airplane mode is on.
1014 */
1015 private boolean isAirplaneModeOn() {
1016 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
1017 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
1018 }
1019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 @Override
1021 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1022 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1023 != PackageManager.PERMISSION_GRANTED) {
1024 pw.println("Permission Denial: can't dump WifiService from from pid="
1025 + Binder.getCallingPid()
1026 + ", uid=" + Binder.getCallingUid());
1027 return;
1028 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001029 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 pw.println("Stay-awake conditions: " +
1031 Settings.System.getInt(mContext.getContentResolver(),
1032 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1033 pw.println();
1034
1035 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001036 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 pw.println();
1038 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001039 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 if (scanResults != null && scanResults.size() != 0) {
1041 pw.println(" BSSID Frequency RSSI Flags SSID");
1042 for (ScanResult r : scanResults) {
1043 pw.printf(" %17s %9d %5d %-16s %s%n",
1044 r.BSSID,
1045 r.frequency,
1046 r.level,
1047 r.capabilities,
1048 r.SSID == null ? "" : r.SSID);
1049 }
1050 }
1051 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001052 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1053 mScanLocksAcquired + " scan");
1054 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1055 mScanLocksReleased + " scan");
1056 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 pw.println("Locks held:");
1058 mLocks.dump(pw);
1059 }
1060
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001061 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001062 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1063 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065
1066 public void binderDied() {
1067 synchronized (mLocks) {
1068 releaseWifiLockLocked(mBinder);
1069 }
1070 }
1071
1072 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001073 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
1075 }
1076
1077 private class LockList {
1078 private List<WifiLock> mList;
1079
1080 private LockList() {
1081 mList = new ArrayList<WifiLock>();
1082 }
1083
1084 private synchronized boolean hasLocks() {
1085 return !mList.isEmpty();
1086 }
1087
1088 private synchronized int getStrongestLockMode() {
1089 if (mList.isEmpty()) {
1090 return WifiManager.WIFI_MODE_FULL;
1091 }
1092 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001093 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 return WifiManager.WIFI_MODE_FULL;
1095 }
1096 }
1097 return WifiManager.WIFI_MODE_SCAN_ONLY;
1098 }
1099
1100 private void addLock(WifiLock lock) {
1101 if (findLockByBinder(lock.mBinder) < 0) {
1102 mList.add(lock);
1103 }
1104 }
1105
1106 private WifiLock removeLock(IBinder binder) {
1107 int index = findLockByBinder(binder);
1108 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001109 WifiLock ret = mList.remove(index);
1110 ret.unlinkDeathRecipient();
1111 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 } else {
1113 return null;
1114 }
1115 }
1116
1117 private int findLockByBinder(IBinder binder) {
1118 int size = mList.size();
1119 for (int i = size - 1; i >= 0; i--)
1120 if (mList.get(i).mBinder == binder)
1121 return i;
1122 return -1;
1123 }
1124
1125 private void dump(PrintWriter pw) {
1126 for (WifiLock l : mList) {
1127 pw.print(" ");
1128 pw.println(l);
1129 }
1130 }
1131 }
1132
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001133 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001134 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001135 return;
1136 }
1137 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1138 pid, uid, null);
1139 }
1140
1141 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1143 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1144 return false;
1145 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001146 if (ws != null) {
1147 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1148 }
1149 if (ws != null && ws.size() == 0) {
1150 ws = null;
1151 }
1152 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:
1164 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1165 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001166 case WifiManager.WIFI_MODE_SCAN_ONLY:
1167 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1168 break;
1169 }
1170 }
1171
1172 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1173 switch(wifiLock.mMode) {
1174 case WifiManager.WIFI_MODE_FULL:
1175 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1176 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001177 case WifiManager.WIFI_MODE_SCAN_ONLY:
1178 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1179 break;
1180 }
1181 }
1182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001184 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001187
The Android Open Source Project10592532009-03-18 17:39:46 -07001188 long ident = Binder.clearCallingIdentity();
1189 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001190 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001191 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001192 case WifiManager.WIFI_MODE_FULL:
1193 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001194 break;
1195 case WifiManager.WIFI_MODE_SCAN_ONLY:
1196 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001197 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001198 }
1199 } catch (RemoteException e) {
1200 } finally {
1201 Binder.restoreCallingIdentity(ident);
1202 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001203
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07001204 // Be aggressive about adding new locks into the accounted state...
1205 // we want to over-report rather than under-report.
1206 reportStartWorkSource();
Dianne Hackborn03f3cb02010-09-17 23:12:26 -07001207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 updateWifiState();
1209 return true;
1210 }
1211
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001212 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1213 int uid = Binder.getCallingUid();
1214 int pid = Binder.getCallingPid();
1215 if (ws != null && ws.size() == 0) {
1216 ws = null;
1217 }
1218 if (ws != null) {
1219 enforceWakeSourcePermission(uid, pid);
1220 }
1221 long ident = Binder.clearCallingIdentity();
1222 try {
1223 synchronized (mLocks) {
1224 int index = mLocks.findLockByBinder(lock);
1225 if (index < 0) {
1226 throw new IllegalArgumentException("Wifi lock not active");
1227 }
1228 WifiLock wl = mLocks.mList.get(index);
1229 noteReleaseWifiLock(wl);
1230 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1231 noteAcquireWifiLock(wl);
1232 }
1233 } catch (RemoteException e) {
1234 } finally {
1235 Binder.restoreCallingIdentity(ident);
1236 }
1237 }
1238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 public boolean releaseWifiLock(IBinder lock) {
1240 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1241 synchronized (mLocks) {
1242 return releaseWifiLockLocked(lock);
1243 }
1244 }
1245
1246 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001247 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001248
The Android Open Source Project10592532009-03-18 17:39:46 -07001249 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001250
Joe Onorato8a9b2202010-02-26 18:56:32 -08001251 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001252
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001253 hadLock = (wifiLock != null);
1254
1255 if (hadLock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001256 long ident = Binder.clearCallingIdentity();
1257 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001258 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001259 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001260 case WifiManager.WIFI_MODE_FULL:
1261 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001262 break;
1263 case WifiManager.WIFI_MODE_SCAN_ONLY:
1264 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001265 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001266 }
1267 } catch (RemoteException e) {
1268 } finally {
1269 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001270 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001271 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001272 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001274 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001276
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001277 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001278 implements IBinder.DeathRecipient {
1279 String mTag;
1280 int mMode;
1281 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001282 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001283
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001284 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001285 super();
1286 mTag = tag;
1287 mMode = mode;
1288 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001289 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001290 try {
1291 mBinder.linkToDeath(this, 0);
1292 } catch (RemoteException e) {
1293 binderDied();
1294 }
1295 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001296
1297 void unlinkDeathRecipient() {
1298 mBinder.unlinkToDeath(this, 0);
1299 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001300 }
1301
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001302 private class Multicaster extends DeathRecipient {
1303 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001304 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001305 }
1306
1307 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001308 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001309 synchronized (mMulticasters) {
1310 int i = mMulticasters.indexOf(this);
1311 if (i != -1) {
1312 removeMulticasterLocked(i, mMode);
1313 }
1314 }
1315 }
1316
1317 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001318 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001319 }
1320
1321 public int getUid() {
1322 return mMode;
1323 }
1324 }
1325
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001326 public void initializeMulticastFiltering() {
1327 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001328
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001329 synchronized (mMulticasters) {
1330 // if anybody had requested filters be off, leave off
1331 if (mMulticasters.size() != 0) {
1332 return;
1333 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001334 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001335 }
1336 }
1337 }
1338
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001339 public void acquireMulticastLock(IBinder binder, String tag) {
1340 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001341
1342 synchronized (mMulticasters) {
1343 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001344 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001345 // Note that we could call stopPacketFiltering only when
1346 // our new size == 1 (first call), but this function won't
1347 // be called often and by making the stopPacket call each
1348 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001349 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001350 }
1351
1352 int uid = Binder.getCallingUid();
1353 Long ident = Binder.clearCallingIdentity();
1354 try {
1355 mBatteryStats.noteWifiMulticastEnabled(uid);
1356 } catch (RemoteException e) {
1357 } finally {
1358 Binder.restoreCallingIdentity(ident);
1359 }
1360 }
1361
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001362 public void releaseMulticastLock() {
1363 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001364
1365 int uid = Binder.getCallingUid();
1366 synchronized (mMulticasters) {
1367 mMulticastDisabled++;
1368 int size = mMulticasters.size();
1369 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001370 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001371 if ((m != null) && (m.getUid() == uid)) {
1372 removeMulticasterLocked(i, uid);
1373 }
1374 }
1375 }
1376 }
1377
1378 private void removeMulticasterLocked(int i, int uid)
1379 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001380 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001381
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001382 if (removed != null) {
1383 removed.unlinkDeathRecipient();
1384 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001385 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001386 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001387 }
1388
1389 Long ident = Binder.clearCallingIdentity();
1390 try {
1391 mBatteryStats.noteWifiMulticastDisabled(uid);
1392 } catch (RemoteException e) {
1393 } finally {
1394 Binder.restoreCallingIdentity(ident);
1395 }
1396 }
1397
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001398 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001399 enforceAccessPermission();
1400
1401 synchronized (mMulticasters) {
1402 return (mMulticasters.size() > 0);
1403 }
1404 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001405
1406 private void checkAndSetNotification() {
1407 // If we shouldn't place a notification on available networks, then
1408 // don't bother doing any of the following
1409 if (!mNotificationEnabled) return;
1410
1411 State state = mNetworkInfo.getState();
1412 if ((state == NetworkInfo.State.DISCONNECTED)
1413 || (state == NetworkInfo.State.UNKNOWN)) {
1414 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001415 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001416 if (scanResults != null) {
1417 int numOpenNetworks = 0;
1418 for (int i = scanResults.size() - 1; i >= 0; i--) {
1419 ScanResult scanResult = scanResults.get(i);
1420
1421 if (TextUtils.isEmpty(scanResult.capabilities)) {
1422 numOpenNetworks++;
1423 }
1424 }
1425
1426 if (numOpenNetworks > 0) {
1427 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1428 /*
1429 * We've scanned continuously at least
1430 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1431 * probably does not have a remembered network in range,
1432 * since otherwise supplicant would have tried to
1433 * associate and thus resetting this counter.
1434 */
1435 setNotificationVisible(true, numOpenNetworks, false, 0);
1436 }
1437 return;
1438 }
1439 }
1440 }
1441
1442 // No open networks in range, remove the notification
1443 setNotificationVisible(false, 0, false, 0);
1444 }
1445
1446 /**
1447 * Clears variables related to tracking whether a notification has been
1448 * shown recently and clears the current notification.
1449 */
1450 private void resetNotification() {
1451 mNotificationRepeatTime = 0;
1452 mNumScansSinceNetworkStateChange = 0;
1453 setNotificationVisible(false, 0, false, 0);
1454 }
1455
1456 /**
1457 * Display or don't display a notification that there are open Wi-Fi networks.
1458 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1459 * @param numNetworks the number networks seen
1460 * @param force {@code true} to force notification to be shown/not-shown,
1461 * even if it is already shown/not-shown.
1462 * @param delay time in milliseconds after which the notification should be made
1463 * visible or invisible.
1464 */
1465 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1466 int delay) {
1467
1468 // Since we use auto cancel on the notification, when the
1469 // mNetworksAvailableNotificationShown is true, the notification may
1470 // have actually been canceled. However, when it is false we know
1471 // for sure that it is not being shown (it will not be shown any other
1472 // place than here)
1473
1474 // If it should be hidden and it is already hidden, then noop
1475 if (!visible && !mNotificationShown && !force) {
1476 return;
1477 }
1478
1479 NotificationManager notificationManager = (NotificationManager) mContext
1480 .getSystemService(Context.NOTIFICATION_SERVICE);
1481
1482 Message message;
1483 if (visible) {
1484
1485 // Not enough time has passed to show the notification again
1486 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1487 return;
1488 }
1489
1490 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001491 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001492 mNotification = new Notification();
1493 mNotification.when = 0;
1494 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1495 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1496 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1497 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1498 }
1499
1500 CharSequence title = mContext.getResources().getQuantityText(
1501 com.android.internal.R.plurals.wifi_available, numNetworks);
1502 CharSequence details = mContext.getResources().getQuantityText(
1503 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1504 mNotification.tickerText = title;
1505 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1506
1507 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1508
1509 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001510 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001511 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001512 }
1513
Irfan Sheriff0d255342010-07-28 09:35:20 -07001514 mNotificationShown = visible;
1515 }
1516
1517 private class NotificationEnabledSettingObserver extends ContentObserver {
1518
1519 public NotificationEnabledSettingObserver(Handler handler) {
1520 super(handler);
1521 }
1522
1523 public void register() {
1524 ContentResolver cr = mContext.getContentResolver();
1525 cr.registerContentObserver(Settings.Secure.getUriFor(
1526 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1527 mNotificationEnabled = getValue();
1528 }
1529
1530 @Override
1531 public void onChange(boolean selfChange) {
1532 super.onChange(selfChange);
1533
1534 mNotificationEnabled = getValue();
1535 resetNotification();
1536 }
1537
1538 private boolean getValue() {
1539 return Settings.Secure.getInt(mContext.getContentResolver(),
1540 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1541 }
1542 }
1543
1544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545}