blob: 6ecc5115f8da65b21f2de4c5ee808ea771b655a4 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.provider.Settings;
Irfan Sheriff0d255342010-07-28 09:35:20 -070054import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080055import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
57import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.List;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -080059import java.util.Set;
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070060import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.io.FileDescriptor;
62import java.io.PrintWriter;
63
The Android Open Source Project10592532009-03-18 17:39:46 -070064import com.android.internal.app.IBatteryStats;
The Android Open Source Project10592532009-03-18 17:39:46 -070065import com.android.server.am.BatteryStatsService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080066import com.android.internal.R;
The Android Open Source Project10592532009-03-18 17:39:46 -070067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068/**
69 * WifiService handles remote WiFi operation requests by implementing
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070070 * the IWifiManager interface.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 *
72 * @hide
73 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070074//TODO: Clean up multiple locks and implement WifiService
75// as a SM to track soft AP/client/adhoc bring up based
76// on device idle state, airplane mode and boot.
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078public class WifiService extends IWifiManager.Stub {
79 private static final String TAG = "WifiService";
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070080 private static final boolean DBG = true;
81
Irfan Sheriff0d255342010-07-28 09:35:20 -070082 private final WifiStateMachine mWifiStateMachine;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
84 private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
86 private AlarmManager mAlarmManager;
87 private PendingIntent mIdleIntent;
88 private static final int IDLE_REQUEST = 0;
89 private boolean mScreenOff;
90 private boolean mDeviceIdle;
91 private int mPluggedType;
92
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070093 // true if the user enabled Wifi while in airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070094 private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -070095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private final LockList mLocks = new LockList();
Eric Shienbrood5711fad2009-03-27 20:25:31 -070097 // some wifi lock statistics
98 private int mFullLocksAcquired;
99 private int mFullLocksReleased;
100 private int mScanLocksAcquired;
101 private int mScanLocksReleased;
The Android Open Source Project10592532009-03-18 17:39:46 -0700102
Robert Greenwalt58ff0212009-05-19 15:53:54 -0700103 private final List<Multicaster> mMulticasters =
104 new ArrayList<Multicaster>();
Robert Greenwalt5347bd42009-05-13 15:10:16 -0700105 private int mMulticastEnabled;
106 private int mMulticastDisabled;
107
The Android Open Source Project10592532009-03-18 17:39:46 -0700108 private final IBatteryStats mBatteryStats;
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800109
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800110 ConnectivityManager mCm;
111 private String[] mWifiRegexs;
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 /**
Doug Zongker43866e02010-01-07 12:09:54 -0800114 * See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
115 * Settings.Secure value is not present. This timeout value is chosen as
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 * the approximate point at which the battery drain caused by Wi-Fi
117 * being enabled but not active exceeds the battery drain caused by
118 * re-establishing a connection to the mobile data network.
119 */
120 private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 /**
123 * Number of allowed radio frequency channels in various regulatory domains.
124 * This list is sufficient for 802.11b/g networks (2.4GHz range).
125 */
126 private static int[] sValidRegulatoryChannelCounts = new int[] {11, 13, 14};
127
128 private static final String ACTION_DEVICE_IDLE =
129 "com.android.server.WifiManager.action.DEVICE_IDLE";
130
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700131 private boolean mIsReceiverRegistered = false;
132
Irfan Sheriff0d255342010-07-28 09:35:20 -0700133
134 NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
135
136 // Variables relating to the 'available networks' notification
137 /**
138 * The icon to show in the 'available networks' notification. This will also
139 * be the ID of the Notification given to the NotificationManager.
140 */
141 private static final int ICON_NETWORKS_AVAILABLE =
142 com.android.internal.R.drawable.stat_notify_wifi_in_range;
143 /**
144 * When a notification is shown, we wait this amount before possibly showing it again.
145 */
146 private final long NOTIFICATION_REPEAT_DELAY_MS;
147 /**
148 * Whether the user has set the setting to show the 'available networks' notification.
149 */
150 private boolean mNotificationEnabled;
151 /**
152 * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
153 */
154 private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
155 /**
156 * The {@link System#currentTimeMillis()} must be at least this value for us
157 * to show the notification again.
158 */
159 private long mNotificationRepeatTime;
160 /**
161 * The Notification object given to the NotificationManager.
162 */
163 private Notification mNotification;
164 /**
165 * Whether the notification is being shown, as set by us. That is, if the
166 * user cancels the notification, we will not receive the callback so this
167 * will still be true. We only guarantee if this is false, then the
168 * notification is not showing.
169 */
170 private boolean mNotificationShown;
171 /**
172 * The number of continuous scans that must occur before consider the
173 * supplicant in a scanning state. This allows supplicant to associate with
174 * remembered networks that are in the scan results.
175 */
176 private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
177 /**
178 * The number of scans since the last network state change. When this
179 * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
180 * supplicant to actually be scanning. When the network state changes to
181 * something other than scanning, we reset this to 0.
182 */
183 private int mNumScansSinceNetworkStateChange;
184
185
186 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700188 mWifiStateMachine = new WifiStateMachine(mContext);
189 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700190 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
193 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
194 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
195
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700196 HandlerThread wifiThread = new HandlerThread("WifiService");
197 wifiThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 mContext.registerReceiver(
200 new BroadcastReceiver() {
201 @Override
202 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700203 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700204 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700205 // on airplane disable, restore Wifi if the saved state indicates so
206 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
207 persistWifiEnabled(true);
208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 updateWifiState();
210 }
211 },
212 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
213
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800214 mContext.registerReceiver(
215 new BroadcastReceiver() {
216 @Override
217 public void onReceive(Context context, Intent intent) {
218
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700219 ArrayList<String> available = intent.getStringArrayListExtra(
220 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
221 ArrayList<String> active = intent.getStringArrayListExtra(
222 ConnectivityManager.EXTRA_ACTIVE_TETHER);
223 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800224
225 }
226 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700227
228 IntentFilter filter = new IntentFilter();
229 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
230 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
231 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
232
233 mContext.registerReceiver(
234 new BroadcastReceiver() {
235 @Override
236 public void onReceive(Context context, Intent intent) {
237 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
238 // reset & clear notification on any wifi state change
239 resetNotification();
240 } else if (intent.getAction().equals(
241 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
242 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
243 WifiManager.EXTRA_NETWORK_INFO);
244 // reset & clear notification on a network connect & disconnect
245 switch(mNetworkInfo.getDetailedState()) {
246 case CONNECTED:
247 case DISCONNECTED:
248 resetNotification();
249 break;
250 }
251 } else if (intent.getAction().equals(
252 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
253 checkAndSetNotification();
254 }
255 }
256 }, filter);
257
258 // Setting is in seconds
259 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
260 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
261 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
262 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800263 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800264
Irfan Sheriff7b009782010-03-11 16:37:45 -0800265 /**
266 * Check if Wi-Fi needs to be enabled and start
267 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700268 *
269 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800270 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700271 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700272 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700273 boolean wifiEnabled = !isAirplaneModeOn()
274 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800275 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
276 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700277 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800278 }
279
280 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
281
282 boolean wifiTethered = false;
283 boolean wifiAvailable = false;
284
285 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
286 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
287
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700288 if (mCm == null) {
289 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
290 }
291
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800292 mWifiRegexs = mCm.getTetherableWifiRegexs();
293
294 for (String intf : available) {
295 for (String regex : mWifiRegexs) {
296 if (intf.matches(regex)) {
297
298 InterfaceConfiguration ifcg = null;
299 try {
300 ifcg = service.getInterfaceConfig(intf);
301 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700302 /* IP/netmask: 192.168.43.1/255.255.255.0 */
303 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800304 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
305 ifcg.interfaceFlags = "up";
306
307 service.setInterfaceConfig(intf, ifcg);
308 }
309 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800310 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700311 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800312 return;
313 }
314
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800315 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700316 Slog.e(TAG, "Error tethering on " + intf);
317 setWifiApEnabled(null, false);
318 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800319 }
320 break;
321 }
322 }
323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 }
325
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700326 private boolean testAndClearWifiSavedState() {
327 final ContentResolver cr = mContext.getContentResolver();
328 int wifiSavedState = 0;
329 try {
330 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
331 if(wifiSavedState == 1)
332 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
333 } catch (Settings.SettingNotFoundException e) {
334 ;
335 }
336 return (wifiSavedState == 1);
337 }
338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 private boolean getPersistedWifiEnabled() {
340 final ContentResolver cr = mContext.getContentResolver();
341 try {
342 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
343 } catch (Settings.SettingNotFoundException e) {
344 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
345 return false;
346 }
347 }
348
349 private void persistWifiEnabled(boolean enabled) {
350 final ContentResolver cr = mContext.getContentResolver();
351 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
352 }
353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 /**
355 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700356 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 */
358 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700359 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700360 return mWifiStateMachine.syncPingSupplicant();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 }
362
363 /**
364 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700366 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700368 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 }
370
371 private void enforceAccessPermission() {
372 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
373 "WifiService");
374 }
375
376 private void enforceChangePermission() {
377 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
378 "WifiService");
379
380 }
381
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700382 private void enforceMulticastChangePermission() {
383 mContext.enforceCallingOrSelfPermission(
384 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
385 "WifiService");
386 }
387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700389 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
390 * @param enable {@code true} to enable, {@code false} to disable.
391 * @return {@code true} if the enable/disable operation was
392 * started or is already in the queue.
393 */
394 public synchronized boolean setWifiEnabled(boolean enable) {
395 enforceChangePermission();
396
397 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700398 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700399 }
400
401 // set a flag if the user is enabling Wifi while in airplane mode
402 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
403 mAirplaneModeOverwridden.set(true);
404 }
405
Irfan Sheriff0d255342010-07-28 09:35:20 -0700406 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700407
408 /*
409 * Caller might not have WRITE_SECURE_SETTINGS,
410 * only CHANGE_WIFI_STATE is enforced
411 */
412 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700413 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700414 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700415
416 if (enable) {
417 if (!mIsReceiverRegistered) {
418 registerForBroadcasts();
419 mIsReceiverRegistered = true;
420 }
421 } else if (mIsReceiverRegistered){
422 mContext.unregisterReceiver(mReceiver);
423 mIsReceiverRegistered = false;
424 }
425
426 return true;
427 }
428
429 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 * see {@link WifiManager#getWifiState()}
431 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
432 * {@link WifiManager#WIFI_STATE_DISABLING},
433 * {@link WifiManager#WIFI_STATE_ENABLED},
434 * {@link WifiManager#WIFI_STATE_ENABLING},
435 * {@link WifiManager#WIFI_STATE_UNKNOWN}
436 */
437 public int getWifiEnabledState() {
438 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700439 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 }
441
442 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700443 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800444 * @param wifiConfig SSID, security and channel details as
445 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700446 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800447 * @return {@code true} if the start operation was
448 * started or is already in the queue.
449 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700450 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800451 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800452
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700453 if (enabled) {
454 /* Use default config if there is no existing config */
455 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
456 wifiConfig = new WifiConfiguration();
457 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
458 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
459 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700460 /*
461 * Caller might not have WRITE_SECURE_SETTINGS,
462 * only CHANGE_WIFI_STATE is enforced
463 */
464 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700465 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700466 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800467 }
468
Irfan Sheriff0d255342010-07-28 09:35:20 -0700469 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700470
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800471 return true;
472 }
473
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700474 /**
475 * see {@link WifiManager#getWifiApState()}
476 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
477 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
478 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
479 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
480 * {@link WifiManager#WIFI_AP_STATE_FAILED}
481 */
482 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700483 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700484 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700485 }
486
487 /**
488 * see {@link WifiManager#getWifiApConfiguration()}
489 * @return soft access point configuration
490 */
491 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800492 final ContentResolver cr = mContext.getContentResolver();
493 WifiConfiguration wifiConfig = new WifiConfiguration();
494 int authType;
495 try {
496 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
497 if (wifiConfig.SSID == null)
498 return null;
499 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
500 wifiConfig.allowedKeyManagement.set(authType);
501 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
502 return wifiConfig;
503 } catch (Settings.SettingNotFoundException e) {
504 Slog.e(TAG,"AP settings not found, returning");
505 return null;
506 }
507 }
508
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700509 /**
510 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
511 * @param wifiConfig WifiConfiguration details for soft access point
512 */
513 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700514 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800515 final ContentResolver cr = mContext.getContentResolver();
516 boolean isWpa;
517 if (wifiConfig == null)
518 return;
519 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
520 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
521 Settings.Secure.putInt(cr,
522 Settings.Secure.WIFI_AP_SECURITY,
523 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
524 if (isWpa)
525 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
526 }
527
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800528 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700529 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800530 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700531 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700532 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700533 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800534 }
535
536 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700537 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800538 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700539 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700540 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700541 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800542 }
543
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700544 /**
545 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700546 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700547 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700548 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700549 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800550 }
551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 /**
553 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
554 * @return the list of configured networks
555 */
556 public List<WifiConfiguration> getConfiguredNetworks() {
557 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700558 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800559 }
560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 /**
562 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
563 * @return the supplicant-assigned identifier for the new or updated
564 * network if the operation succeeds, or {@code -1} if it fails
565 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800566 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700568 return mWifiStateMachine.syncAddOrUpdateNetwork(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 }
570
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700571 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
573 * @param netId the integer that identifies the network configuration
574 * to the supplicant
575 * @return {@code true} if the operation succeeded
576 */
577 public boolean removeNetwork(int netId) {
578 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700579 return mWifiStateMachine.syncRemoveNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 }
581
582 /**
583 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
584 * @param netId the integer that identifies the network configuration
585 * to the supplicant
586 * @param disableOthers if true, disable all other networks.
587 * @return {@code true} if the operation succeeded
588 */
589 public boolean enableNetwork(int netId, boolean disableOthers) {
590 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700591 return mWifiStateMachine.syncEnableNetwork(netId, disableOthers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 }
593
594 /**
595 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
596 * @param netId the integer that identifies the network configuration
597 * to the supplicant
598 * @return {@code true} if the operation succeeded
599 */
600 public boolean disableNetwork(int netId) {
601 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700602 return mWifiStateMachine.syncDisableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 }
604
605 /**
606 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
607 * @return the Wi-Fi information, contained in {@link WifiInfo}.
608 */
609 public WifiInfo getConnectionInfo() {
610 enforceAccessPermission();
611 /*
612 * Make sure we have the latest information, by sending
613 * a status request to the supplicant.
614 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700615 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 }
617
618 /**
619 * Return the results of the most recent access point scan, in the form of
620 * a list of {@link ScanResult} objects.
621 * @return the list of results
622 */
623 public List<ScanResult> getScanResults() {
624 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700625 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 }
627
628 /**
629 * Tell the supplicant to persist the current list of configured networks.
630 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700631 *
632 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 */
634 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700635 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700637 return mWifiStateMachine.syncSaveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 }
639
640 /**
641 * Set the number of radio frequency channels that are allowed to be used
642 * in the current regulatory domain. This method should be used only
643 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700644 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 * persisted as a Secure setting.
646 * @param numChannels the number of allowed channels. Must be greater than 0
647 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700648 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
650 * {@code numChannels} is outside the valid range.
651 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700652 public synchronized boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800653 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700654 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -0700656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 /*
658 * Validate the argument. We'd like to let the Wi-Fi driver do this,
659 * but if Wi-Fi isn't currently enabled, that's not possible, and
660 * we want to persist the setting anyway,so that it will take
661 * effect when Wi-Fi does become enabled.
662 */
663 boolean found = false;
664 for (int validChan : sValidRegulatoryChannelCounts) {
665 if (validChan == numChannels) {
666 found = true;
667 break;
668 }
669 }
670 if (!found) {
671 return false;
672 }
673
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700674 if (persist) {
675 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -0700676 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
677 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700678 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700679
Irfan Sheriff0d255342010-07-28 09:35:20 -0700680 mWifiStateMachine.setNumAllowedChannels(numChannels);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700681
682 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 }
684
685 /**
686 * Return the number of frequency channels that are allowed
687 * to be used in the current regulatory domain.
688 * @return the number of allowed channels, or {@code -1} if an error occurs
689 */
690 public int getNumAllowedChannels() {
691 int numChannels;
692
693 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800694
695 /*
696 * If we can't get the value from the driver (e.g., because
697 * Wi-Fi is not currently enabled), get the value from
698 * Settings.
699 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700700 numChannels = mWifiStateMachine.getNumAllowedChannels();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800701 if (numChannels < 0) {
702 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
703 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
704 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 }
706 return numChannels;
707 }
708
709 /**
710 * Return the list of valid values for the number of allowed radio channels
711 * for various regulatory domains.
712 * @return the list of channel counts
713 */
714 public int[] getValidChannelCounts() {
715 enforceAccessPermission();
716 return sValidRegulatoryChannelCounts;
717 }
718
719 /**
720 * Return the DHCP-assigned addresses from the last successful DHCP request,
721 * if any.
722 * @return the DHCP information
723 */
724 public DhcpInfo getDhcpInfo() {
725 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700726 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 }
728
Irfan Sheriff0d255342010-07-28 09:35:20 -0700729 /**
730 * see {@link android.net.wifi.WifiManager#startWifi}
731 *
732 */
733 public void startWifi() {
734 enforceChangePermission();
735 /* TODO: may be add permissions for access only to connectivity service
736 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
737 * of WifiLock & device idle status unless wifi enabled status is toggled
738 */
739
740 mWifiStateMachine.setDriverStart(true);
741 mWifiStateMachine.reconnectCommand();
742 }
743
744 /**
745 * see {@link android.net.wifi.WifiManager#stopWifi}
746 *
747 */
748 public void stopWifi() {
749 enforceChangePermission();
750 /* TODO: may be add permissions for access only to connectivity service
751 * TODO: if a stop is issued, wifi is brought up only by startWifi
752 * unless wifi enabled status is toggled
753 */
754 mWifiStateMachine.setDriverStart(false);
755 }
756
757
758 /**
759 * see {@link android.net.wifi.WifiManager#addToBlacklist}
760 *
761 */
762 public void addToBlacklist(String bssid) {
763 enforceChangePermission();
764
765 mWifiStateMachine.addToBlacklist(bssid);
766 }
767
768 /**
769 * see {@link android.net.wifi.WifiManager#clearBlacklist}
770 *
771 */
772 public void clearBlacklist() {
773 enforceChangePermission();
774
775 mWifiStateMachine.clearBlacklist();
776 }
777
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700778 public void connectNetworkWithId(int networkId) {
779 enforceChangePermission();
780 mWifiStateMachine.connectNetwork(networkId);
781 }
782
783 public void connectNetworkWithConfig(WifiConfiguration config) {
784 enforceChangePermission();
785 mWifiStateMachine.connectNetwork(config);
786 }
787
788 public void saveNetwork(WifiConfiguration config) {
789 enforceChangePermission();
790 mWifiStateMachine.saveNetwork(config);
791 }
792
793 public void forgetNetwork(int netId) {
794 enforceChangePermission();
795 mWifiStateMachine.forgetNetwork(netId);
796 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
799 @Override
800 public void onReceive(Context context, Intent intent) {
801 String action = intent.getAction();
802
Doug Zongker43866e02010-01-07 12:09:54 -0800803 long idleMillis =
804 Settings.Secure.getLong(mContext.getContentResolver(),
805 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800807 Settings.System.getInt(mContext.getContentResolver(),
808 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800810 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 mAlarmManager.cancel(mIdleIntent);
812 mDeviceIdle = false;
813 mScreenOff = false;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700814 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800816 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700818 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 /*
820 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
821 * AND the "stay on while plugged in" setting doesn't match the
822 * current power conditions (i.e, not plugged in, plugged in to USB,
823 * or plugged in to AC).
824 */
825 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700826 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700827 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700828 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700829 // we don't have time to track down for this release. Delay instead,
830 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700831 // TODO - fix the race conditions and switch back to the immediate turn-off
832 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -0800833 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700834 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
835 // // do not keep Wifi awake when screen is off if Wifi is not associated
836 // mDeviceIdle = true;
837 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400838 } else {
839 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800840 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400841 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
844 /* we can return now -- there's nothing to do until we get the idle intent back */
845 return;
846 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800847 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 mDeviceIdle = true;
849 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
850 /*
851 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
852 * AND we are transitioning from a state in which the device was supposed
853 * to stay awake to a state in which it is not supposed to stay awake.
854 * If "stay awake" state is not changing, we do nothing, to avoid resetting
855 * the already-set timer.
856 */
857 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800858 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
860 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
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");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
864 mPluggedType = pluggedType;
865 return;
866 }
867 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -0700868 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800869 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
870 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
871 boolean isBluetoothPlaying = false;
872 for (BluetoothDevice sink : sinks) {
873 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
874 isBluetoothPlaying = true;
875 }
876 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700877 mWifiStateMachine.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 } else {
880 return;
881 }
882
883 updateWifiState();
884 }
885
886 /**
887 * Determines whether the Wi-Fi chipset should stay awake or be put to
888 * sleep. Looks at the setting for the sleep policy and the current
889 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800890 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 * @see #shouldDeviceStayAwake(int, int)
892 */
893 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
894 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
895 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
896
897 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
898 // Never sleep
899 return true;
900 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
901 (pluggedType != 0)) {
902 // Never sleep while plugged, and we're plugged
903 return true;
904 } else {
905 // Default
906 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
907 }
908 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 /**
911 * Determine whether the bit value corresponding to {@code pluggedType} is set in
912 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
913 * of {@code 0} isn't really a plugged type, but rather an indication that the
914 * device isn't plugged in at all, there is no bit value corresponding to a
915 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700916 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 * @param stayAwakeConditions a bit string specifying which "plugged types" should
918 * keep the device (and hence Wi-Fi) awake.
919 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
920 * being made
921 * @return {@code true} if {@code pluggedType} indicates that the device is
922 * supposed to stay awake, {@code false} otherwise.
923 */
924 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
925 return (stayAwakeConditions & pluggedType) != 0;
926 }
927 };
928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 private void updateWifiState() {
930 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700931 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 boolean lockHeld = mLocks.hasLocks();
933 int strongestLockMode;
934 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
935 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
936 if (mDeviceIdle && lockHeld) {
937 strongestLockMode = mLocks.getStrongestLockMode();
938 } else {
939 strongestLockMode = WifiManager.WIFI_MODE_FULL;
940 }
941
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700942 /* Disable tethering when airplane mode is enabled */
943 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700944 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700945 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700946
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700947 if (wifiShouldBeEnabled) {
948 if (wifiShouldBeStarted) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700949 mWifiStateMachine.setWifiEnabled(true);
950 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700951 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700952 mWifiStateMachine.setDriverStart(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700954 mWifiStateMachine.requestCmWakeLock();
955 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700957 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700958 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 }
960 }
961
962 private void registerForBroadcasts() {
963 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
965 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
966 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
967 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -0700968 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 mContext.registerReceiver(mReceiver, intentFilter);
970 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 private boolean isAirplaneSensitive() {
973 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
974 Settings.System.AIRPLANE_MODE_RADIOS);
975 return airplaneModeRadios == null
976 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
977 }
978
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700979 private boolean isAirplaneToggleable() {
980 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
981 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
982 return toggleableRadios != null
983 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
984 }
985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 /**
987 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
988 * currently on.
989 * @return {@code true} if airplane mode is on.
990 */
991 private boolean isAirplaneModeOn() {
992 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
993 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
994 }
995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 @Override
997 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
998 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
999 != PackageManager.PERMISSION_GRANTED) {
1000 pw.println("Permission Denial: can't dump WifiService from from pid="
1001 + Binder.getCallingPid()
1002 + ", uid=" + Binder.getCallingUid());
1003 return;
1004 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001005 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 pw.println("Stay-awake conditions: " +
1007 Settings.System.getInt(mContext.getContentResolver(),
1008 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1009 pw.println();
1010
1011 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001012 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 pw.println();
1014 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001015 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 if (scanResults != null && scanResults.size() != 0) {
1017 pw.println(" BSSID Frequency RSSI Flags SSID");
1018 for (ScanResult r : scanResults) {
1019 pw.printf(" %17s %9d %5d %-16s %s%n",
1020 r.BSSID,
1021 r.frequency,
1022 r.level,
1023 r.capabilities,
1024 r.SSID == null ? "" : r.SSID);
1025 }
1026 }
1027 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001028 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1029 mScanLocksAcquired + " scan");
1030 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1031 mScanLocksReleased + " scan");
1032 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 pw.println("Locks held:");
1034 mLocks.dump(pw);
1035 }
1036
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001037 private class WifiLock extends DeathRecipient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 WifiLock(int lockMode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001039 super(lockMode, tag, binder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
1041
1042 public void binderDied() {
1043 synchronized (mLocks) {
1044 releaseWifiLockLocked(mBinder);
1045 }
1046 }
1047
1048 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001049 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051 }
1052
1053 private class LockList {
1054 private List<WifiLock> mList;
1055
1056 private LockList() {
1057 mList = new ArrayList<WifiLock>();
1058 }
1059
1060 private synchronized boolean hasLocks() {
1061 return !mList.isEmpty();
1062 }
1063
1064 private synchronized int getStrongestLockMode() {
1065 if (mList.isEmpty()) {
1066 return WifiManager.WIFI_MODE_FULL;
1067 }
1068 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001069 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 return WifiManager.WIFI_MODE_FULL;
1071 }
1072 }
1073 return WifiManager.WIFI_MODE_SCAN_ONLY;
1074 }
1075
1076 private void addLock(WifiLock lock) {
1077 if (findLockByBinder(lock.mBinder) < 0) {
1078 mList.add(lock);
1079 }
1080 }
1081
1082 private WifiLock removeLock(IBinder binder) {
1083 int index = findLockByBinder(binder);
1084 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001085 WifiLock ret = mList.remove(index);
1086 ret.unlinkDeathRecipient();
1087 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 } else {
1089 return null;
1090 }
1091 }
1092
1093 private int findLockByBinder(IBinder binder) {
1094 int size = mList.size();
1095 for (int i = size - 1; i >= 0; i--)
1096 if (mList.get(i).mBinder == binder)
1097 return i;
1098 return -1;
1099 }
1100
1101 private void dump(PrintWriter pw) {
1102 for (WifiLock l : mList) {
1103 pw.print(" ");
1104 pw.println(l);
1105 }
1106 }
1107 }
1108
1109 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag) {
1110 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1111 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1112 return false;
1113 }
1114 WifiLock wifiLock = new WifiLock(lockMode, tag, binder);
1115 synchronized (mLocks) {
1116 return acquireWifiLockLocked(wifiLock);
1117 }
1118 }
1119
1120 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001121 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001124
The Android Open Source Project10592532009-03-18 17:39:46 -07001125 int uid = Binder.getCallingUid();
1126 long ident = Binder.clearCallingIdentity();
1127 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001128 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001129 case WifiManager.WIFI_MODE_FULL:
1130 ++mFullLocksAcquired;
1131 mBatteryStats.noteFullWifiLockAcquired(uid);
1132 break;
1133 case WifiManager.WIFI_MODE_SCAN_ONLY:
1134 ++mScanLocksAcquired;
1135 mBatteryStats.noteScanWifiLockAcquired(uid);
1136 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001137 }
1138 } catch (RemoteException e) {
1139 } finally {
1140 Binder.restoreCallingIdentity(ident);
1141 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 updateWifiState();
1144 return true;
1145 }
1146
1147 public boolean releaseWifiLock(IBinder lock) {
1148 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1149 synchronized (mLocks) {
1150 return releaseWifiLockLocked(lock);
1151 }
1152 }
1153
1154 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001155 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001156
The Android Open Source Project10592532009-03-18 17:39:46 -07001157 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001158
Joe Onorato8a9b2202010-02-26 18:56:32 -08001159 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001160
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001161 hadLock = (wifiLock != null);
1162
1163 if (hadLock) {
1164 int uid = Binder.getCallingUid();
1165 long ident = Binder.clearCallingIdentity();
1166 try {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001167 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001168 case WifiManager.WIFI_MODE_FULL:
1169 ++mFullLocksReleased;
1170 mBatteryStats.noteFullWifiLockReleased(uid);
1171 break;
1172 case WifiManager.WIFI_MODE_SCAN_ONLY:
1173 ++mScanLocksReleased;
1174 mBatteryStats.noteScanWifiLockReleased(uid);
1175 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001176 }
1177 } catch (RemoteException e) {
1178 } finally {
1179 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001180 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001181 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001182 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001184 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001186
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001187 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001188 implements IBinder.DeathRecipient {
1189 String mTag;
1190 int mMode;
1191 IBinder mBinder;
1192
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001193 DeathRecipient(int mode, String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001194 super();
1195 mTag = tag;
1196 mMode = mode;
1197 mBinder = binder;
1198 try {
1199 mBinder.linkToDeath(this, 0);
1200 } catch (RemoteException e) {
1201 binderDied();
1202 }
1203 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001204
1205 void unlinkDeathRecipient() {
1206 mBinder.unlinkToDeath(this, 0);
1207 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001208 }
1209
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001210 private class Multicaster extends DeathRecipient {
1211 Multicaster(String tag, IBinder binder) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001212 super(Binder.getCallingUid(), tag, binder);
1213 }
1214
1215 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001216 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001217 synchronized (mMulticasters) {
1218 int i = mMulticasters.indexOf(this);
1219 if (i != -1) {
1220 removeMulticasterLocked(i, mMode);
1221 }
1222 }
1223 }
1224
1225 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001226 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001227 }
1228
1229 public int getUid() {
1230 return mMode;
1231 }
1232 }
1233
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001234 public void initializeMulticastFiltering() {
1235 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001236
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001237 synchronized (mMulticasters) {
1238 // if anybody had requested filters be off, leave off
1239 if (mMulticasters.size() != 0) {
1240 return;
1241 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001242 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001243 }
1244 }
1245 }
1246
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001247 public void acquireMulticastLock(IBinder binder, String tag) {
1248 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001249
1250 synchronized (mMulticasters) {
1251 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001252 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001253 // Note that we could call stopPacketFiltering only when
1254 // our new size == 1 (first call), but this function won't
1255 // be called often and by making the stopPacket call each
1256 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001257 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001258 }
1259
1260 int uid = Binder.getCallingUid();
1261 Long ident = Binder.clearCallingIdentity();
1262 try {
1263 mBatteryStats.noteWifiMulticastEnabled(uid);
1264 } catch (RemoteException e) {
1265 } finally {
1266 Binder.restoreCallingIdentity(ident);
1267 }
1268 }
1269
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001270 public void releaseMulticastLock() {
1271 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001272
1273 int uid = Binder.getCallingUid();
1274 synchronized (mMulticasters) {
1275 mMulticastDisabled++;
1276 int size = mMulticasters.size();
1277 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001278 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001279 if ((m != null) && (m.getUid() == uid)) {
1280 removeMulticasterLocked(i, uid);
1281 }
1282 }
1283 }
1284 }
1285
1286 private void removeMulticasterLocked(int i, int uid)
1287 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001288 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001289
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001290 if (removed != null) {
1291 removed.unlinkDeathRecipient();
1292 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001293 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001294 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001295 }
1296
1297 Long ident = Binder.clearCallingIdentity();
1298 try {
1299 mBatteryStats.noteWifiMulticastDisabled(uid);
1300 } catch (RemoteException e) {
1301 } finally {
1302 Binder.restoreCallingIdentity(ident);
1303 }
1304 }
1305
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001306 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001307 enforceAccessPermission();
1308
1309 synchronized (mMulticasters) {
1310 return (mMulticasters.size() > 0);
1311 }
1312 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001313
1314 private void checkAndSetNotification() {
1315 // If we shouldn't place a notification on available networks, then
1316 // don't bother doing any of the following
1317 if (!mNotificationEnabled) return;
1318
1319 State state = mNetworkInfo.getState();
1320 if ((state == NetworkInfo.State.DISCONNECTED)
1321 || (state == NetworkInfo.State.UNKNOWN)) {
1322 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001323 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001324 if (scanResults != null) {
1325 int numOpenNetworks = 0;
1326 for (int i = scanResults.size() - 1; i >= 0; i--) {
1327 ScanResult scanResult = scanResults.get(i);
1328
1329 if (TextUtils.isEmpty(scanResult.capabilities)) {
1330 numOpenNetworks++;
1331 }
1332 }
1333
1334 if (numOpenNetworks > 0) {
1335 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1336 /*
1337 * We've scanned continuously at least
1338 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1339 * probably does not have a remembered network in range,
1340 * since otherwise supplicant would have tried to
1341 * associate and thus resetting this counter.
1342 */
1343 setNotificationVisible(true, numOpenNetworks, false, 0);
1344 }
1345 return;
1346 }
1347 }
1348 }
1349
1350 // No open networks in range, remove the notification
1351 setNotificationVisible(false, 0, false, 0);
1352 }
1353
1354 /**
1355 * Clears variables related to tracking whether a notification has been
1356 * shown recently and clears the current notification.
1357 */
1358 private void resetNotification() {
1359 mNotificationRepeatTime = 0;
1360 mNumScansSinceNetworkStateChange = 0;
1361 setNotificationVisible(false, 0, false, 0);
1362 }
1363
1364 /**
1365 * Display or don't display a notification that there are open Wi-Fi networks.
1366 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1367 * @param numNetworks the number networks seen
1368 * @param force {@code true} to force notification to be shown/not-shown,
1369 * even if it is already shown/not-shown.
1370 * @param delay time in milliseconds after which the notification should be made
1371 * visible or invisible.
1372 */
1373 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1374 int delay) {
1375
1376 // Since we use auto cancel on the notification, when the
1377 // mNetworksAvailableNotificationShown is true, the notification may
1378 // have actually been canceled. However, when it is false we know
1379 // for sure that it is not being shown (it will not be shown any other
1380 // place than here)
1381
1382 // If it should be hidden and it is already hidden, then noop
1383 if (!visible && !mNotificationShown && !force) {
1384 return;
1385 }
1386
1387 NotificationManager notificationManager = (NotificationManager) mContext
1388 .getSystemService(Context.NOTIFICATION_SERVICE);
1389
1390 Message message;
1391 if (visible) {
1392
1393 // Not enough time has passed to show the notification again
1394 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1395 return;
1396 }
1397
1398 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001399 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001400 mNotification = new Notification();
1401 mNotification.when = 0;
1402 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1403 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1404 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1405 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1406 }
1407
1408 CharSequence title = mContext.getResources().getQuantityText(
1409 com.android.internal.R.plurals.wifi_available, numNetworks);
1410 CharSequence details = mContext.getResources().getQuantityText(
1411 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1412 mNotification.tickerText = title;
1413 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1414
1415 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1416
1417 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001418 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001419 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001420 }
1421
Irfan Sheriff0d255342010-07-28 09:35:20 -07001422 mNotificationShown = visible;
1423 }
1424
1425 private class NotificationEnabledSettingObserver extends ContentObserver {
1426
1427 public NotificationEnabledSettingObserver(Handler handler) {
1428 super(handler);
1429 }
1430
1431 public void register() {
1432 ContentResolver cr = mContext.getContentResolver();
1433 cr.registerContentObserver(Settings.Secure.getUriFor(
1434 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1435 mNotificationEnabled = getValue();
1436 }
1437
1438 @Override
1439 public void onChange(boolean selfChange) {
1440 super.onChange(selfChange);
1441
1442 mNotificationEnabled = getValue();
1443 resetNotification();
1444 }
1445
1446 private boolean getValue() {
1447 return Settings.Secure.getInt(mContext.getContentResolver(),
1448 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1449 }
1450 }
1451
1452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453}