blob: e8502fa9ff89395232b9ac3dbf36456aebec5e82 [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;
185
186
187 WifiService(Context context) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 mContext = context;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700189 mWifiStateMachine = new WifiStateMachine(mContext);
190 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project10592532009-03-18 17:39:46 -0700191 mBatteryStats = BatteryStatsService.getService();
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
194 Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
195 mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
196
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700197 HandlerThread wifiThread = new HandlerThread("WifiService");
198 wifiThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 mContext.registerReceiver(
201 new BroadcastReceiver() {
202 @Override
203 public void onReceive(Context context, Intent intent) {
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700204 // clear our flag indicating the user has overwridden airplane mode
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700205 mAirplaneModeOverwridden.set(false);
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700206 // on airplane disable, restore Wifi if the saved state indicates so
207 if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
208 persistWifiEnabled(true);
209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 updateWifiState();
211 }
212 },
213 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
214
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800215 mContext.registerReceiver(
216 new BroadcastReceiver() {
217 @Override
218 public void onReceive(Context context, Intent intent) {
219
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700220 ArrayList<String> available = intent.getStringArrayListExtra(
221 ConnectivityManager.EXTRA_AVAILABLE_TETHER);
222 ArrayList<String> active = intent.getStringArrayListExtra(
223 ConnectivityManager.EXTRA_ACTIVE_TETHER);
224 updateTetherState(available, active);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800225
226 }
227 },new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
Irfan Sheriff0d255342010-07-28 09:35:20 -0700228
229 IntentFilter filter = new IntentFilter();
230 filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
231 filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
232 filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
233
234 mContext.registerReceiver(
235 new BroadcastReceiver() {
236 @Override
237 public void onReceive(Context context, Intent intent) {
238 if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
239 // reset & clear notification on any wifi state change
240 resetNotification();
241 } else if (intent.getAction().equals(
242 WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
243 mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
244 WifiManager.EXTRA_NETWORK_INFO);
245 // reset & clear notification on a network connect & disconnect
246 switch(mNetworkInfo.getDetailedState()) {
247 case CONNECTED:
248 case DISCONNECTED:
249 resetNotification();
250 break;
251 }
252 } else if (intent.getAction().equals(
253 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
254 checkAndSetNotification();
255 }
256 }
257 }, filter);
258
259 // Setting is in seconds
260 NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
261 Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
262 mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
263 mNotificationEnabledSettingObserver.register();
Irfan Sheriff7b009782010-03-11 16:37:45 -0800264 }
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800265
Irfan Sheriff7b009782010-03-11 16:37:45 -0800266 /**
267 * Check if Wi-Fi needs to be enabled and start
268 * if needed
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700269 *
270 * This function is used only at boot time
Irfan Sheriff7b009782010-03-11 16:37:45 -0800271 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700272 public void checkAndStartWifi() {
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700273 /* Start if Wi-Fi is enabled or the saved state indicates Wi-Fi was on */
Irfan Sheriff60e3ba02010-04-02 12:18:45 -0700274 boolean wifiEnabled = !isAirplaneModeOn()
275 && (getPersistedWifiEnabled() || testAndClearWifiSavedState());
Irfan Sheriff7b009782010-03-11 16:37:45 -0800276 Slog.i(TAG, "WifiService starting up with Wi-Fi " +
277 (wifiEnabled ? "enabled" : "disabled"));
Irfan Sheriffb99fe5e2010-03-26 14:56:07 -0700278 setWifiEnabled(wifiEnabled);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800279 }
280
281 private void updateTetherState(ArrayList<String> available, ArrayList<String> tethered) {
282
283 boolean wifiTethered = false;
284 boolean wifiAvailable = false;
285
286 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
287 INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
288
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700289 if (mCm == null) {
290 mCm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
291 }
292
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800293 mWifiRegexs = mCm.getTetherableWifiRegexs();
294
295 for (String intf : available) {
296 for (String regex : mWifiRegexs) {
297 if (intf.matches(regex)) {
298
299 InterfaceConfiguration ifcg = null;
300 try {
301 ifcg = service.getInterfaceConfig(intf);
302 if (ifcg != null) {
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -0700303 /* IP/netmask: 192.168.43.1/255.255.255.0 */
304 ifcg.ipAddr = (192 << 24) + (168 << 16) + (43 << 8) + 1;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800305 ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
306 ifcg.interfaceFlags = "up";
307
308 service.setInterfaceConfig(intf, ifcg);
309 }
310 } catch (Exception e) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800311 Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700312 setWifiApEnabled(null, false);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800313 return;
314 }
315
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800316 if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700317 Slog.e(TAG, "Error tethering on " + intf);
318 setWifiApEnabled(null, false);
319 return;
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800320 }
321 break;
322 }
323 }
324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 }
326
Irfan Sheriffa3bd4092010-03-24 17:58:59 -0700327 private boolean testAndClearWifiSavedState() {
328 final ContentResolver cr = mContext.getContentResolver();
329 int wifiSavedState = 0;
330 try {
331 wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
332 if(wifiSavedState == 1)
333 Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
334 } catch (Settings.SettingNotFoundException e) {
335 ;
336 }
337 return (wifiSavedState == 1);
338 }
339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 private boolean getPersistedWifiEnabled() {
341 final ContentResolver cr = mContext.getContentResolver();
342 try {
343 return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON) == 1;
344 } catch (Settings.SettingNotFoundException e) {
345 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, 0);
346 return false;
347 }
348 }
349
350 private void persistWifiEnabled(boolean enabled) {
351 final ContentResolver cr = mContext.getContentResolver();
352 Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, enabled ? 1 : 0);
353 }
354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 /**
356 * see {@link android.net.wifi.WifiManager#pingSupplicant()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700357 * @return {@code true} if the operation succeeds, {@code false} otherwise
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 */
359 public boolean pingSupplicant() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700360 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700361 return mWifiStateMachine.syncPingSupplicant();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 }
363
364 /**
365 * see {@link android.net.wifi.WifiManager#startScan()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700367 public void startScan(boolean forceActive) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700369 mWifiStateMachine.startScan(forceActive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 }
371
372 private void enforceAccessPermission() {
373 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
374 "WifiService");
375 }
376
377 private void enforceChangePermission() {
378 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
379 "WifiService");
380
381 }
382
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -0700383 private void enforceMulticastChangePermission() {
384 mContext.enforceCallingOrSelfPermission(
385 android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
386 "WifiService");
387 }
388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700390 * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
391 * @param enable {@code true} to enable, {@code false} to disable.
392 * @return {@code true} if the enable/disable operation was
393 * started or is already in the queue.
394 */
395 public synchronized boolean setWifiEnabled(boolean enable) {
396 enforceChangePermission();
397
398 if (DBG) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700399 Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700400 }
401
402 // set a flag if the user is enabling Wifi while in airplane mode
403 if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
404 mAirplaneModeOverwridden.set(true);
405 }
406
Irfan Sheriff0d255342010-07-28 09:35:20 -0700407 mWifiStateMachine.setWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700408
409 /*
410 * Caller might not have WRITE_SECURE_SETTINGS,
411 * only CHANGE_WIFI_STATE is enforced
412 */
413 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700414 persistWifiEnabled(enable);
Irfan Sheriff61180692010-08-18 16:07:39 -0700415 Binder.restoreCallingIdentity(ident);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700416
417 if (enable) {
418 if (!mIsReceiverRegistered) {
419 registerForBroadcasts();
420 mIsReceiverRegistered = true;
421 }
422 } else if (mIsReceiverRegistered){
423 mContext.unregisterReceiver(mReceiver);
424 mIsReceiverRegistered = false;
425 }
426
427 return true;
428 }
429
430 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 * see {@link WifiManager#getWifiState()}
432 * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
433 * {@link WifiManager#WIFI_STATE_DISABLING},
434 * {@link WifiManager#WIFI_STATE_ENABLED},
435 * {@link WifiManager#WIFI_STATE_ENABLING},
436 * {@link WifiManager#WIFI_STATE_UNKNOWN}
437 */
438 public int getWifiEnabledState() {
439 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700440 return mWifiStateMachine.syncGetWifiState();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 }
442
443 /**
Irfan Sheriffc2f54c22010-03-18 14:02:22 -0700444 * see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800445 * @param wifiConfig SSID, security and channel details as
446 * part of WifiConfiguration
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700447 * @param enabled true to enable and false to disable
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800448 * @return {@code true} if the start operation was
449 * started or is already in the queue.
450 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700451 public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800452 enforceChangePermission();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800453
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700454 if (enabled) {
455 /* Use default config if there is no existing config */
456 if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
457 wifiConfig = new WifiConfiguration();
458 wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
459 wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
460 }
Irfan Sheriff61180692010-08-18 16:07:39 -0700461 /*
462 * Caller might not have WRITE_SECURE_SETTINGS,
463 * only CHANGE_WIFI_STATE is enforced
464 */
465 long ident = Binder.clearCallingIdentity();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700466 setWifiApConfiguration(wifiConfig);
Irfan Sheriff61180692010-08-18 16:07:39 -0700467 Binder.restoreCallingIdentity(ident);
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800468 }
469
Irfan Sheriff0d255342010-07-28 09:35:20 -0700470 mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700471
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800472 return true;
473 }
474
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700475 /**
476 * see {@link WifiManager#getWifiApState()}
477 * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
478 * {@link WifiManager#WIFI_AP_STATE_DISABLING},
479 * {@link WifiManager#WIFI_AP_STATE_ENABLED},
480 * {@link WifiManager#WIFI_AP_STATE_ENABLING},
481 * {@link WifiManager#WIFI_AP_STATE_FAILED}
482 */
483 public int getWifiApEnabledState() {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700484 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700485 return mWifiStateMachine.syncGetWifiApState();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700486 }
487
488 /**
489 * see {@link WifiManager#getWifiApConfiguration()}
490 * @return soft access point configuration
491 */
492 public synchronized WifiConfiguration getWifiApConfiguration() {
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800493 final ContentResolver cr = mContext.getContentResolver();
494 WifiConfiguration wifiConfig = new WifiConfiguration();
495 int authType;
496 try {
497 wifiConfig.SSID = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_SSID);
498 if (wifiConfig.SSID == null)
499 return null;
500 authType = Settings.Secure.getInt(cr, Settings.Secure.WIFI_AP_SECURITY);
501 wifiConfig.allowedKeyManagement.set(authType);
502 wifiConfig.preSharedKey = Settings.Secure.getString(cr, Settings.Secure.WIFI_AP_PASSWD);
503 return wifiConfig;
504 } catch (Settings.SettingNotFoundException e) {
505 Slog.e(TAG,"AP settings not found, returning");
506 return null;
507 }
508 }
509
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700510 /**
511 * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
512 * @param wifiConfig WifiConfiguration details for soft access point
513 */
514 public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
Irfan Sheriff17b232b2010-06-24 11:32:26 -0700515 enforceChangePermission();
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800516 final ContentResolver cr = mContext.getContentResolver();
517 boolean isWpa;
518 if (wifiConfig == null)
519 return;
520 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_SSID, wifiConfig.SSID);
521 isWpa = wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_PSK);
522 Settings.Secure.putInt(cr,
523 Settings.Secure.WIFI_AP_SECURITY,
524 isWpa ? KeyMgmt.WPA_PSK : KeyMgmt.NONE);
525 if (isWpa)
526 Settings.Secure.putString(cr, Settings.Secure.WIFI_AP_PASSWD, wifiConfig.preSharedKey);
527 }
528
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800529 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700530 * see {@link android.net.wifi.WifiManager#disconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800531 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700532 public void disconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700533 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700534 mWifiStateMachine.disconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800535 }
536
537 /**
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700538 * see {@link android.net.wifi.WifiManager#reconnect()}
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800539 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700540 public void reconnect() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700541 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700542 mWifiStateMachine.reconnectCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800543 }
544
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700545 /**
546 * see {@link android.net.wifi.WifiManager#reassociate()}
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700547 */
Irfan Sheriffe4984752010-08-19 11:29:22 -0700548 public void reassociate() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700549 enforceChangePermission();
Irfan Sheriffe4984752010-08-19 11:29:22 -0700550 mWifiStateMachine.reassociateCommand();
Irfan Sheriff5321aef2010-02-12 12:35:59 -0800551 }
552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 /**
554 * see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
555 * @return the list of configured networks
556 */
557 public List<WifiConfiguration> getConfiguredNetworks() {
558 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700559 return mWifiStateMachine.syncGetConfiguredNetworks();
Chung-yih Wanga8d15942009-10-09 11:01:49 +0800560 }
561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 /**
563 * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
564 * @return the supplicant-assigned identifier for the new or updated
565 * network if the operation succeeds, or {@code -1} if it fails
566 */
Irfan Sheriff7aac5542009-12-22 21:42:17 -0800567 public int addOrUpdateNetwork(WifiConfiguration config) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700569 return mWifiStateMachine.syncAddOrUpdateNetwork(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 }
571
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700572 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 * See {@link android.net.wifi.WifiManager#removeNetwork(int)}
574 * @param netId the integer that identifies the network configuration
575 * to the supplicant
576 * @return {@code true} if the operation succeeded
577 */
578 public boolean removeNetwork(int netId) {
579 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700580 return mWifiStateMachine.syncRemoveNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 }
582
583 /**
584 * See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
585 * @param netId the integer that identifies the network configuration
586 * to the supplicant
587 * @param disableOthers if true, disable all other networks.
588 * @return {@code true} if the operation succeeded
589 */
590 public boolean enableNetwork(int netId, boolean disableOthers) {
591 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700592 return mWifiStateMachine.syncEnableNetwork(netId, disableOthers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 }
594
595 /**
596 * See {@link android.net.wifi.WifiManager#disableNetwork(int)}
597 * @param netId the integer that identifies the network configuration
598 * to the supplicant
599 * @return {@code true} if the operation succeeded
600 */
601 public boolean disableNetwork(int netId) {
602 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700603 return mWifiStateMachine.syncDisableNetwork(netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 }
605
606 /**
607 * See {@link android.net.wifi.WifiManager#getConnectionInfo()}
608 * @return the Wi-Fi information, contained in {@link WifiInfo}.
609 */
610 public WifiInfo getConnectionInfo() {
611 enforceAccessPermission();
612 /*
613 * Make sure we have the latest information, by sending
614 * a status request to the supplicant.
615 */
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700616 return mWifiStateMachine.syncRequestConnectionInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 }
618
619 /**
620 * Return the results of the most recent access point scan, in the form of
621 * a list of {@link ScanResult} objects.
622 * @return the list of results
623 */
624 public List<ScanResult> getScanResults() {
625 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700626 return mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 }
628
629 /**
630 * Tell the supplicant to persist the current list of configured networks.
631 * @return {@code true} if the operation succeeded
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700632 *
633 * TODO: deprecate this
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 */
635 public boolean saveConfiguration() {
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700636 boolean result = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 enforceChangePermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700638 return mWifiStateMachine.syncSaveConfig();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 }
640
641 /**
642 * Set the number of radio frequency channels that are allowed to be used
643 * in the current regulatory domain. This method should be used only
644 * if the correct number of channels cannot be determined automatically
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700645 * for some reason. If the operation is successful, the new value may be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 * persisted as a Secure setting.
647 * @param numChannels the number of allowed channels. Must be greater than 0
648 * and less than or equal to 16.
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700649 * @param persist {@code true} if the setting should be remembered.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
651 * {@code numChannels} is outside the valid range.
652 */
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700653 public synchronized boolean setNumAllowedChannels(int numChannels, boolean persist) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800654 Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700655 " with persist set to "+persist);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 enforceChangePermission();
Irfan Sheriff59610c02010-03-30 11:00:41 -0700657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 /*
659 * Validate the argument. We'd like to let the Wi-Fi driver do this,
660 * but if Wi-Fi isn't currently enabled, that's not possible, and
661 * we want to persist the setting anyway,so that it will take
662 * effect when Wi-Fi does become enabled.
663 */
664 boolean found = false;
665 for (int validChan : sValidRegulatoryChannelCounts) {
666 if (validChan == numChannels) {
667 found = true;
668 break;
669 }
670 }
671 if (!found) {
672 return false;
673 }
674
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700675 if (persist) {
676 Settings.Secure.putInt(mContext.getContentResolver(),
Irfan Sheriff59610c02010-03-30 11:00:41 -0700677 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
678 numChannels);
Robert Greenwaltb5010cc2009-05-21 15:11:40 -0700679 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700680
Irfan Sheriff0d255342010-07-28 09:35:20 -0700681 mWifiStateMachine.setNumAllowedChannels(numChannels);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700682
683 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 }
685
686 /**
687 * Return the number of frequency channels that are allowed
688 * to be used in the current regulatory domain.
689 * @return the number of allowed channels, or {@code -1} if an error occurs
690 */
691 public int getNumAllowedChannels() {
692 int numChannels;
693
694 enforceAccessPermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800695
696 /*
697 * If we can't get the value from the driver (e.g., because
698 * Wi-Fi is not currently enabled), get the value from
699 * Settings.
700 */
Irfan Sheriff0d255342010-07-28 09:35:20 -0700701 numChannels = mWifiStateMachine.getNumAllowedChannels();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -0800702 if (numChannels < 0) {
703 numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
704 Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
705 -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 }
707 return numChannels;
708 }
709
710 /**
711 * Return the list of valid values for the number of allowed radio channels
712 * for various regulatory domains.
713 * @return the list of channel counts
714 */
715 public int[] getValidChannelCounts() {
716 enforceAccessPermission();
717 return sValidRegulatoryChannelCounts;
718 }
719
720 /**
721 * Return the DHCP-assigned addresses from the last successful DHCP request,
722 * if any.
723 * @return the DHCP information
724 */
725 public DhcpInfo getDhcpInfo() {
726 enforceAccessPermission();
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700727 return mWifiStateMachine.syncGetDhcpInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 }
729
Irfan Sheriff0d255342010-07-28 09:35:20 -0700730 /**
731 * see {@link android.net.wifi.WifiManager#startWifi}
732 *
733 */
734 public void startWifi() {
735 enforceChangePermission();
736 /* TODO: may be add permissions for access only to connectivity service
737 * TODO: if a start issued, keep wifi alive until a stop issued irrespective
738 * of WifiLock & device idle status unless wifi enabled status is toggled
739 */
740
741 mWifiStateMachine.setDriverStart(true);
742 mWifiStateMachine.reconnectCommand();
743 }
744
745 /**
746 * see {@link android.net.wifi.WifiManager#stopWifi}
747 *
748 */
749 public void stopWifi() {
750 enforceChangePermission();
751 /* TODO: may be add permissions for access only to connectivity service
752 * TODO: if a stop is issued, wifi is brought up only by startWifi
753 * unless wifi enabled status is toggled
754 */
755 mWifiStateMachine.setDriverStart(false);
756 }
757
758
759 /**
760 * see {@link android.net.wifi.WifiManager#addToBlacklist}
761 *
762 */
763 public void addToBlacklist(String bssid) {
764 enforceChangePermission();
765
766 mWifiStateMachine.addToBlacklist(bssid);
767 }
768
769 /**
770 * see {@link android.net.wifi.WifiManager#clearBlacklist}
771 *
772 */
773 public void clearBlacklist() {
774 enforceChangePermission();
775
776 mWifiStateMachine.clearBlacklist();
777 }
778
Irfan Sheriffe04653c2010-08-09 09:09:59 -0700779 public void connectNetworkWithId(int networkId) {
780 enforceChangePermission();
781 mWifiStateMachine.connectNetwork(networkId);
782 }
783
784 public void connectNetworkWithConfig(WifiConfiguration config) {
785 enforceChangePermission();
786 mWifiStateMachine.connectNetwork(config);
787 }
788
789 public void saveNetwork(WifiConfiguration config) {
790 enforceChangePermission();
791 mWifiStateMachine.saveNetwork(config);
792 }
793
794 public void forgetNetwork(int netId) {
795 enforceChangePermission();
796 mWifiStateMachine.forgetNetwork(netId);
797 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
800 @Override
801 public void onReceive(Context context, Intent intent) {
802 String action = intent.getAction();
803
Doug Zongker43866e02010-01-07 12:09:54 -0800804 long idleMillis =
805 Settings.Secure.getLong(mContext.getContentResolver(),
806 Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MILLIS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 int stayAwakeConditions =
Doug Zongker43866e02010-01-07 12:09:54 -0800808 Settings.System.getInt(mContext.getContentResolver(),
809 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 if (action.equals(Intent.ACTION_SCREEN_ON)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800811 Slog.d(TAG, "ACTION_SCREEN_ON");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 mAlarmManager.cancel(mIdleIntent);
813 mDeviceIdle = false;
814 mScreenOff = false;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700815 mWifiStateMachine.enableRssiPolling(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800817 Slog.d(TAG, "ACTION_SCREEN_OFF");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 mScreenOff = true;
Irfan Sheriff0d255342010-07-28 09:35:20 -0700819 mWifiStateMachine.enableRssiPolling(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 /*
821 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
822 * AND the "stay on while plugged in" setting doesn't match the
823 * current power conditions (i.e, not plugged in, plugged in to USB,
824 * or plugged in to AC).
825 */
826 if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
Irfan Sheriffd8134ff2010-08-22 17:06:34 -0700827 WifiInfo info = mWifiStateMachine.syncRequestConnectionInfo();
San Mehatfa6c7112009-07-07 09:34:44 -0700828 if (info.getSupplicantState() != SupplicantState.COMPLETED) {
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700829 // we used to go to sleep immediately, but this caused some race conditions
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700830 // we don't have time to track down for this release. Delay instead,
831 // but not as long as we would if connected (below)
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700832 // TODO - fix the race conditions and switch back to the immediate turn-off
833 long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Joe Onorato8a9b2202010-02-26 18:56:32 -0800834 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
Robert Greenwalt84612ea62009-09-30 09:04:22 -0700835 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
836 // // do not keep Wifi awake when screen is off if Wifi is not associated
837 // mDeviceIdle = true;
838 // updateWifiState();
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400839 } else {
840 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800841 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
Mike Lockwoodd9c32bc2009-05-18 14:14:15 -0400842 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845 /* we can return now -- there's nothing to do until we get the idle intent back */
846 return;
847 } else if (action.equals(ACTION_DEVICE_IDLE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800848 Slog.d(TAG, "got ACTION_DEVICE_IDLE");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 mDeviceIdle = true;
850 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
851 /*
852 * Set a timer to put Wi-Fi to sleep, but only if the screen is off
853 * AND we are transitioning from a state in which the device was supposed
854 * to stay awake to a state in which it is not supposed to stay awake.
855 * If "stay awake" state is not changing, we do nothing, to avoid resetting
856 * the already-set timer.
857 */
858 int pluggedType = intent.getIntExtra("plugged", 0);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800859 Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
861 !shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
862 long triggerTime = System.currentTimeMillis() + idleMillis;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800863 Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
865 mPluggedType = pluggedType;
866 return;
867 }
868 mPluggedType = pluggedType;
Nick Pelly005b2282009-09-10 10:21:56 -0700869 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800870 BluetoothA2dp a2dp = new BluetoothA2dp(mContext);
871 Set<BluetoothDevice> sinks = a2dp.getConnectedSinks();
872 boolean isBluetoothPlaying = false;
873 for (BluetoothDevice sink : sinks) {
874 if (a2dp.getSinkState(sink) == BluetoothA2dp.STATE_PLAYING) {
875 isBluetoothPlaying = true;
876 }
877 }
Irfan Sheriff0d255342010-07-28 09:35:20 -0700878 mWifiStateMachine.setBluetoothScanMode(isBluetoothPlaying);
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 } else {
881 return;
882 }
883
884 updateWifiState();
885 }
886
887 /**
888 * Determines whether the Wi-Fi chipset should stay awake or be put to
889 * sleep. Looks at the setting for the sleep policy and the current
890 * conditions.
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800891 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 * @see #shouldDeviceStayAwake(int, int)
893 */
894 private boolean shouldWifiStayAwake(int stayAwakeConditions, int pluggedType) {
895 int wifiSleepPolicy = Settings.System.getInt(mContext.getContentResolver(),
896 Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
897
898 if (wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER) {
899 // Never sleep
900 return true;
901 } else if ((wifiSleepPolicy == Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED) &&
902 (pluggedType != 0)) {
903 // Never sleep while plugged, and we're plugged
904 return true;
905 } else {
906 // Default
907 return shouldDeviceStayAwake(stayAwakeConditions, pluggedType);
908 }
909 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 /**
912 * Determine whether the bit value corresponding to {@code pluggedType} is set in
913 * the bit string {@code stayAwakeConditions}. Because a {@code pluggedType} value
914 * of {@code 0} isn't really a plugged type, but rather an indication that the
915 * device isn't plugged in at all, there is no bit value corresponding to a
916 * {@code pluggedType} value of {@code 0}. That is why we shift by
Ben Dodson4e8620f2010-08-25 10:55:47 -0700917 * {@code pluggedType - 1} instead of by {@code pluggedType}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 * @param stayAwakeConditions a bit string specifying which "plugged types" should
919 * keep the device (and hence Wi-Fi) awake.
920 * @param pluggedType the type of plug (USB, AC, or none) for which the check is
921 * being made
922 * @return {@code true} if {@code pluggedType} indicates that the device is
923 * supposed to stay awake, {@code false} otherwise.
924 */
925 private boolean shouldDeviceStayAwake(int stayAwakeConditions, int pluggedType) {
926 return (stayAwakeConditions & pluggedType) != 0;
927 }
928 };
929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 private void updateWifiState() {
931 boolean wifiEnabled = getPersistedWifiEnabled();
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700932 boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 boolean lockHeld = mLocks.hasLocks();
934 int strongestLockMode;
935 boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
936 boolean wifiShouldBeStarted = !mDeviceIdle || lockHeld;
937 if (mDeviceIdle && lockHeld) {
938 strongestLockMode = mLocks.getStrongestLockMode();
939 } else {
940 strongestLockMode = WifiManager.WIFI_MODE_FULL;
941 }
942
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700943 /* Disable tethering when airplane mode is enabled */
944 if (airplaneMode) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700945 mWifiStateMachine.setWifiApEnabled(null, false);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700946 }
Irfan Sheriffb2e6c012010-04-05 11:57:56 -0700947
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700948 if (wifiShouldBeEnabled) {
949 if (wifiShouldBeStarted) {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700950 mWifiStateMachine.setWifiEnabled(true);
951 mWifiStateMachine.setScanOnlyMode(
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700952 strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700953 mWifiStateMachine.setDriverStart(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700955 mWifiStateMachine.requestCmWakeLock();
956 mWifiStateMachine.setDriverStart(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700958 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -0700959 mWifiStateMachine.setWifiEnabled(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 }
961 }
962
963 private void registerForBroadcasts() {
964 IntentFilter intentFilter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
966 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
967 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
968 intentFilter.addAction(ACTION_DEVICE_IDLE);
Nick Pelly005b2282009-09-10 10:21:56 -0700969 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 mContext.registerReceiver(mReceiver, intentFilter);
971 }
Jaikumar Ganesh084c6652009-12-07 10:58:18 -0800972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 private boolean isAirplaneSensitive() {
974 String airplaneModeRadios = Settings.System.getString(mContext.getContentResolver(),
975 Settings.System.AIRPLANE_MODE_RADIOS);
976 return airplaneModeRadios == null
977 || airplaneModeRadios.contains(Settings.System.RADIO_WIFI);
978 }
979
Mike Lockwoodbd5ddf02009-07-29 21:37:14 -0700980 private boolean isAirplaneToggleable() {
981 String toggleableRadios = Settings.System.getString(mContext.getContentResolver(),
982 Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
983 return toggleableRadios != null
984 && toggleableRadios.contains(Settings.System.RADIO_WIFI);
985 }
986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 /**
988 * Returns true if Wi-Fi is sensitive to airplane mode, and airplane mode is
989 * currently on.
990 * @return {@code true} if airplane mode is on.
991 */
992 private boolean isAirplaneModeOn() {
993 return isAirplaneSensitive() && Settings.System.getInt(mContext.getContentResolver(),
994 Settings.System.AIRPLANE_MODE_ON, 0) == 1;
995 }
996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 @Override
998 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
999 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1000 != PackageManager.PERMISSION_GRANTED) {
1001 pw.println("Permission Denial: can't dump WifiService from from pid="
1002 + Binder.getCallingPid()
1003 + ", uid=" + Binder.getCallingUid());
1004 return;
1005 }
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001006 pw.println("Wi-Fi is " + mWifiStateMachine.syncGetWifiStateByName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 pw.println("Stay-awake conditions: " +
1008 Settings.System.getInt(mContext.getContentResolver(),
1009 Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
1010 pw.println();
1011
1012 pw.println("Internal state:");
Irfan Sheriff0d255342010-07-28 09:35:20 -07001013 pw.println(mWifiStateMachine);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 pw.println();
1015 pw.println("Latest scan results:");
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001016 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 if (scanResults != null && scanResults.size() != 0) {
1018 pw.println(" BSSID Frequency RSSI Flags SSID");
1019 for (ScanResult r : scanResults) {
1020 pw.printf(" %17s %9d %5d %-16s %s%n",
1021 r.BSSID,
1022 r.frequency,
1023 r.level,
1024 r.capabilities,
1025 r.SSID == null ? "" : r.SSID);
1026 }
1027 }
1028 pw.println();
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001029 pw.println("Locks acquired: " + mFullLocksAcquired + " full, " +
1030 mScanLocksAcquired + " scan");
1031 pw.println("Locks released: " + mFullLocksReleased + " full, " +
1032 mScanLocksReleased + " scan");
1033 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 pw.println("Locks held:");
1035 mLocks.dump(pw);
1036 }
1037
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001038 private class WifiLock extends DeathRecipient {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001039 WifiLock(int lockMode, String tag, IBinder binder, WorkSource ws) {
1040 super(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
1042
1043 public void binderDied() {
1044 synchronized (mLocks) {
1045 releaseWifiLockLocked(mBinder);
1046 }
1047 }
1048
1049 public String toString() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001050 return "WifiLock{" + mTag + " type=" + mMode + " binder=" + mBinder + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
1052 }
1053
1054 private class LockList {
1055 private List<WifiLock> mList;
1056
1057 private LockList() {
1058 mList = new ArrayList<WifiLock>();
1059 }
1060
1061 private synchronized boolean hasLocks() {
1062 return !mList.isEmpty();
1063 }
1064
1065 private synchronized int getStrongestLockMode() {
1066 if (mList.isEmpty()) {
1067 return WifiManager.WIFI_MODE_FULL;
1068 }
1069 for (WifiLock l : mList) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001070 if (l.mMode == WifiManager.WIFI_MODE_FULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 return WifiManager.WIFI_MODE_FULL;
1072 }
1073 }
1074 return WifiManager.WIFI_MODE_SCAN_ONLY;
1075 }
1076
1077 private void addLock(WifiLock lock) {
1078 if (findLockByBinder(lock.mBinder) < 0) {
1079 mList.add(lock);
1080 }
1081 }
1082
1083 private WifiLock removeLock(IBinder binder) {
1084 int index = findLockByBinder(binder);
1085 if (index >= 0) {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001086 WifiLock ret = mList.remove(index);
1087 ret.unlinkDeathRecipient();
1088 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 } else {
1090 return null;
1091 }
1092 }
1093
1094 private int findLockByBinder(IBinder binder) {
1095 int size = mList.size();
1096 for (int i = size - 1; i >= 0; i--)
1097 if (mList.get(i).mBinder == binder)
1098 return i;
1099 return -1;
1100 }
1101
1102 private void dump(PrintWriter pw) {
1103 for (WifiLock l : mList) {
1104 pw.print(" ");
1105 pw.println(l);
1106 }
1107 }
1108 }
1109
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001110 void enforceWakeSourcePermission(int uid, int pid) {
Dianne Hackborne746f032010-09-13 16:02:57 -07001111 if (uid == android.os.Process.myUid()) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001112 return;
1113 }
1114 mContext.enforcePermission(android.Manifest.permission.UPDATE_DEVICE_STATS,
1115 pid, uid, null);
1116 }
1117
1118 public boolean acquireWifiLock(IBinder binder, int lockMode, String tag, WorkSource ws) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1120 if (lockMode != WifiManager.WIFI_MODE_FULL && lockMode != WifiManager.WIFI_MODE_SCAN_ONLY) {
1121 return false;
1122 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001123 if (ws != null) {
1124 enforceWakeSourcePermission(Binder.getCallingUid(), Binder.getCallingPid());
1125 }
1126 if (ws != null && ws.size() == 0) {
1127 ws = null;
1128 }
1129 if (ws == null) {
1130 ws = new WorkSource(Binder.getCallingUid());
1131 }
1132 WifiLock wifiLock = new WifiLock(lockMode, tag, binder, ws);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 synchronized (mLocks) {
1134 return acquireWifiLockLocked(wifiLock);
1135 }
1136 }
1137
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001138 private void noteAcquireWifiLock(WifiLock wifiLock) throws RemoteException {
1139 switch(wifiLock.mMode) {
1140 case WifiManager.WIFI_MODE_FULL:
1141 mBatteryStats.noteFullWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1142 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001143 case WifiManager.WIFI_MODE_SCAN_ONLY:
1144 mBatteryStats.noteScanWifiLockAcquiredFromSource(wifiLock.mWorkSource);
1145 break;
1146 }
1147 }
1148
1149 private void noteReleaseWifiLock(WifiLock wifiLock) throws RemoteException {
1150 switch(wifiLock.mMode) {
1151 case WifiManager.WIFI_MODE_FULL:
1152 mBatteryStats.noteFullWifiLockReleasedFromSource(wifiLock.mWorkSource);
1153 break;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001154 case WifiManager.WIFI_MODE_SCAN_ONLY:
1155 mBatteryStats.noteScanWifiLockReleasedFromSource(wifiLock.mWorkSource);
1156 break;
1157 }
1158 }
1159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 private boolean acquireWifiLockLocked(WifiLock wifiLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001161 Slog.d(TAG, "acquireWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 mLocks.addLock(wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001164
The Android Open Source Project10592532009-03-18 17:39:46 -07001165 long ident = Binder.clearCallingIdentity();
1166 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001167 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001168 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001169 case WifiManager.WIFI_MODE_FULL:
1170 ++mFullLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001171 break;
1172 case WifiManager.WIFI_MODE_SCAN_ONLY:
1173 ++mScanLocksAcquired;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001174 break;
The Android Open Source Project10592532009-03-18 17:39:46 -07001175 }
1176 } catch (RemoteException e) {
1177 } finally {
1178 Binder.restoreCallingIdentity(ident);
1179 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 updateWifiState();
1182 return true;
1183 }
1184
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001185 public void updateWifiLockWorkSource(IBinder lock, WorkSource ws) {
1186 int uid = Binder.getCallingUid();
1187 int pid = Binder.getCallingPid();
1188 if (ws != null && ws.size() == 0) {
1189 ws = null;
1190 }
1191 if (ws != null) {
1192 enforceWakeSourcePermission(uid, pid);
1193 }
1194 long ident = Binder.clearCallingIdentity();
1195 try {
1196 synchronized (mLocks) {
1197 int index = mLocks.findLockByBinder(lock);
1198 if (index < 0) {
1199 throw new IllegalArgumentException("Wifi lock not active");
1200 }
1201 WifiLock wl = mLocks.mList.get(index);
1202 noteReleaseWifiLock(wl);
1203 wl.mWorkSource = ws != null ? new WorkSource(ws) : new WorkSource(uid);
1204 noteAcquireWifiLock(wl);
1205 }
1206 } catch (RemoteException e) {
1207 } finally {
1208 Binder.restoreCallingIdentity(ident);
1209 }
1210 }
1211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 public boolean releaseWifiLock(IBinder lock) {
1213 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
1214 synchronized (mLocks) {
1215 return releaseWifiLockLocked(lock);
1216 }
1217 }
1218
1219 private boolean releaseWifiLockLocked(IBinder lock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001220 boolean hadLock;
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001221
The Android Open Source Project10592532009-03-18 17:39:46 -07001222 WifiLock wifiLock = mLocks.removeLock(lock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001223
Joe Onorato8a9b2202010-02-26 18:56:32 -08001224 Slog.d(TAG, "releaseWifiLockLocked: " + wifiLock);
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001225
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001226 hadLock = (wifiLock != null);
1227
1228 if (hadLock) {
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001229 long ident = Binder.clearCallingIdentity();
1230 try {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001231 noteAcquireWifiLock(wifiLock);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001232 switch(wifiLock.mMode) {
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001233 case WifiManager.WIFI_MODE_FULL:
1234 ++mFullLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001235 break;
1236 case WifiManager.WIFI_MODE_SCAN_ONLY:
1237 ++mScanLocksReleased;
Eric Shienbrood5711fad2009-03-27 20:25:31 -07001238 break;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001239 }
1240 } catch (RemoteException e) {
1241 } finally {
1242 Binder.restoreCallingIdentity(ident);
The Android Open Source Project10592532009-03-18 17:39:46 -07001243 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001244 }
Robert Greenwaltf1acb2d2009-10-13 08:20:55 -07001245 // TODO - should this only happen if you hadLock?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 updateWifiState();
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07001247 return hadLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001249
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001250 private abstract class DeathRecipient
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001251 implements IBinder.DeathRecipient {
1252 String mTag;
1253 int mMode;
1254 IBinder mBinder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001255 WorkSource mWorkSource;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001256
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001257 DeathRecipient(int mode, String tag, IBinder binder, WorkSource ws) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001258 super();
1259 mTag = tag;
1260 mMode = mode;
1261 mBinder = binder;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001262 mWorkSource = ws;
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001263 try {
1264 mBinder.linkToDeath(this, 0);
1265 } catch (RemoteException e) {
1266 binderDied();
1267 }
1268 }
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001269
1270 void unlinkDeathRecipient() {
1271 mBinder.unlinkToDeath(this, 0);
1272 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001273 }
1274
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001275 private class Multicaster extends DeathRecipient {
1276 Multicaster(String tag, IBinder binder) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001277 super(Binder.getCallingUid(), tag, binder, null);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001278 }
1279
1280 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001281 Slog.e(TAG, "Multicaster binderDied");
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001282 synchronized (mMulticasters) {
1283 int i = mMulticasters.indexOf(this);
1284 if (i != -1) {
1285 removeMulticasterLocked(i, mMode);
1286 }
1287 }
1288 }
1289
1290 public String toString() {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001291 return "Multicaster{" + mTag + " binder=" + mBinder + "}";
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001292 }
1293
1294 public int getUid() {
1295 return mMode;
1296 }
1297 }
1298
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001299 public void initializeMulticastFiltering() {
1300 enforceMulticastChangePermission();
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001301
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001302 synchronized (mMulticasters) {
1303 // if anybody had requested filters be off, leave off
1304 if (mMulticasters.size() != 0) {
1305 return;
1306 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001307 mWifiStateMachine.startPacketFiltering();
Robert Greenwalte2d155a2009-10-21 14:58:34 -07001308 }
1309 }
1310 }
1311
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001312 public void acquireMulticastLock(IBinder binder, String tag) {
1313 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001314
1315 synchronized (mMulticasters) {
1316 mMulticastEnabled++;
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001317 mMulticasters.add(new Multicaster(tag, binder));
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001318 // Note that we could call stopPacketFiltering only when
1319 // our new size == 1 (first call), but this function won't
1320 // be called often and by making the stopPacket call each
1321 // time we're less fragile and self-healing.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001322 mWifiStateMachine.stopPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001323 }
1324
1325 int uid = Binder.getCallingUid();
1326 Long ident = Binder.clearCallingIdentity();
1327 try {
1328 mBatteryStats.noteWifiMulticastEnabled(uid);
1329 } catch (RemoteException e) {
1330 } finally {
1331 Binder.restoreCallingIdentity(ident);
1332 }
1333 }
1334
Robert Greenwaltfc1b15c2009-05-22 15:09:51 -07001335 public void releaseMulticastLock() {
1336 enforceMulticastChangePermission();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001337
1338 int uid = Binder.getCallingUid();
1339 synchronized (mMulticasters) {
1340 mMulticastDisabled++;
1341 int size = mMulticasters.size();
1342 for (int i = size - 1; i >= 0; i--) {
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001343 Multicaster m = mMulticasters.get(i);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001344 if ((m != null) && (m.getUid() == uid)) {
1345 removeMulticasterLocked(i, uid);
1346 }
1347 }
1348 }
1349 }
1350
1351 private void removeMulticasterLocked(int i, int uid)
1352 {
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001353 Multicaster removed = mMulticasters.remove(i);
Irfan Sheriffa8fbe1f2010-03-09 09:13:58 -08001354
Suchi Amalapurapufff2fda2009-06-30 21:36:16 -07001355 if (removed != null) {
1356 removed.unlinkDeathRecipient();
1357 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001358 if (mMulticasters.size() == 0) {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001359 mWifiStateMachine.startPacketFiltering();
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001360 }
1361
1362 Long ident = Binder.clearCallingIdentity();
1363 try {
1364 mBatteryStats.noteWifiMulticastDisabled(uid);
1365 } catch (RemoteException e) {
1366 } finally {
1367 Binder.restoreCallingIdentity(ident);
1368 }
1369 }
1370
Robert Greenwalt58ff0212009-05-19 15:53:54 -07001371 public boolean isMulticastEnabled() {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07001372 enforceAccessPermission();
1373
1374 synchronized (mMulticasters) {
1375 return (mMulticasters.size() > 0);
1376 }
1377 }
Irfan Sheriff0d255342010-07-28 09:35:20 -07001378
1379 private void checkAndSetNotification() {
1380 // If we shouldn't place a notification on available networks, then
1381 // don't bother doing any of the following
1382 if (!mNotificationEnabled) return;
1383
1384 State state = mNetworkInfo.getState();
1385 if ((state == NetworkInfo.State.DISCONNECTED)
1386 || (state == NetworkInfo.State.UNKNOWN)) {
1387 // Look for an open network
Irfan Sheriffd8134ff2010-08-22 17:06:34 -07001388 List<ScanResult> scanResults = mWifiStateMachine.syncGetScanResultsList();
Irfan Sheriff0d255342010-07-28 09:35:20 -07001389 if (scanResults != null) {
1390 int numOpenNetworks = 0;
1391 for (int i = scanResults.size() - 1; i >= 0; i--) {
1392 ScanResult scanResult = scanResults.get(i);
1393
1394 if (TextUtils.isEmpty(scanResult.capabilities)) {
1395 numOpenNetworks++;
1396 }
1397 }
1398
1399 if (numOpenNetworks > 0) {
1400 if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
1401 /*
1402 * We've scanned continuously at least
1403 * NUM_SCANS_BEFORE_NOTIFICATION times. The user
1404 * probably does not have a remembered network in range,
1405 * since otherwise supplicant would have tried to
1406 * associate and thus resetting this counter.
1407 */
1408 setNotificationVisible(true, numOpenNetworks, false, 0);
1409 }
1410 return;
1411 }
1412 }
1413 }
1414
1415 // No open networks in range, remove the notification
1416 setNotificationVisible(false, 0, false, 0);
1417 }
1418
1419 /**
1420 * Clears variables related to tracking whether a notification has been
1421 * shown recently and clears the current notification.
1422 */
1423 private void resetNotification() {
1424 mNotificationRepeatTime = 0;
1425 mNumScansSinceNetworkStateChange = 0;
1426 setNotificationVisible(false, 0, false, 0);
1427 }
1428
1429 /**
1430 * Display or don't display a notification that there are open Wi-Fi networks.
1431 * @param visible {@code true} if notification should be visible, {@code false} otherwise
1432 * @param numNetworks the number networks seen
1433 * @param force {@code true} to force notification to be shown/not-shown,
1434 * even if it is already shown/not-shown.
1435 * @param delay time in milliseconds after which the notification should be made
1436 * visible or invisible.
1437 */
1438 private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
1439 int delay) {
1440
1441 // Since we use auto cancel on the notification, when the
1442 // mNetworksAvailableNotificationShown is true, the notification may
1443 // have actually been canceled. However, when it is false we know
1444 // for sure that it is not being shown (it will not be shown any other
1445 // place than here)
1446
1447 // If it should be hidden and it is already hidden, then noop
1448 if (!visible && !mNotificationShown && !force) {
1449 return;
1450 }
1451
1452 NotificationManager notificationManager = (NotificationManager) mContext
1453 .getSystemService(Context.NOTIFICATION_SERVICE);
1454
1455 Message message;
1456 if (visible) {
1457
1458 // Not enough time has passed to show the notification again
1459 if (System.currentTimeMillis() < mNotificationRepeatTime) {
1460 return;
1461 }
1462
1463 if (mNotification == null) {
Wink Savillec7a98342010-08-13 16:11:42 -07001464 // Cache the Notification object.
Irfan Sheriff0d255342010-07-28 09:35:20 -07001465 mNotification = new Notification();
1466 mNotification.when = 0;
1467 mNotification.icon = ICON_NETWORKS_AVAILABLE;
1468 mNotification.flags = Notification.FLAG_AUTO_CANCEL;
1469 mNotification.contentIntent = PendingIntent.getActivity(mContext, 0,
1470 new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK), 0);
1471 }
1472
1473 CharSequence title = mContext.getResources().getQuantityText(
1474 com.android.internal.R.plurals.wifi_available, numNetworks);
1475 CharSequence details = mContext.getResources().getQuantityText(
1476 com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
1477 mNotification.tickerText = title;
1478 mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
1479
1480 mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
1481
1482 notificationManager.notify(ICON_NETWORKS_AVAILABLE, mNotification);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001483 } else {
Irfan Sheriff0d255342010-07-28 09:35:20 -07001484 notificationManager.cancel(ICON_NETWORKS_AVAILABLE);
Irfan Sheriff0d255342010-07-28 09:35:20 -07001485 }
1486
Irfan Sheriff0d255342010-07-28 09:35:20 -07001487 mNotificationShown = visible;
1488 }
1489
1490 private class NotificationEnabledSettingObserver extends ContentObserver {
1491
1492 public NotificationEnabledSettingObserver(Handler handler) {
1493 super(handler);
1494 }
1495
1496 public void register() {
1497 ContentResolver cr = mContext.getContentResolver();
1498 cr.registerContentObserver(Settings.Secure.getUriFor(
1499 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
1500 mNotificationEnabled = getValue();
1501 }
1502
1503 @Override
1504 public void onChange(boolean selfChange) {
1505 super.onChange(selfChange);
1506
1507 mNotificationEnabled = getValue();
1508 resetNotification();
1509 }
1510
1511 private boolean getValue() {
1512 return Settings.Secure.getInt(mContext.getContentResolver(),
1513 Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
1514 }
1515 }
1516
1517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518}