-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWifiService.java
More file actions
1735 lines (1535 loc) · 64.5 KB
/
WifiService.java
File metadata and controls
1735 lines (1535 loc) · 64.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.net.wifi.IWifiManager;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiStateMachine;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiWatchdogStateMachine;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WpsInfo;
import android.net.wifi.WpsResult;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.NetworkInfo.DetailedState;
import android.net.TrafficStats;
import android.os.Binder;
import android.os.Handler;
import android.os.Messenger;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.INetworkManagementService;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.os.WorkSource;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Slog;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicBoolean;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import com.android.internal.app.IBatteryStats;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.util.AsyncChannel;
import com.android.server.am.BatteryStatsService;
import com.android.internal.R;
/**
* WifiService handles remote WiFi operation requests by implementing
* the IWifiManager interface.
*
* @hide
*/
//TODO: Clean up multiple locks and implement WifiService
// as a SM to track soft AP/client/adhoc bring up based
// on device idle state, airplane mode and boot.
public class WifiService extends IWifiManager.Stub {
private static final String TAG = "WifiService";
private static final boolean DBG = false;
private final WifiStateMachine mWifiStateMachine;
private Context mContext;
private AlarmManager mAlarmManager;
private PendingIntent mIdleIntent;
private static final int IDLE_REQUEST = 0;
private boolean mScreenOff;
private boolean mDeviceIdle;
private boolean mEmergencyCallbackMode = false;
private int mPluggedType;
/* Chipset supports background scan */
private final boolean mBackgroundScanSupported;
private final LockList mLocks = new LockList();
// some wifi lock statistics
private int mFullHighPerfLocksAcquired;
private int mFullHighPerfLocksReleased;
private int mFullLocksAcquired;
private int mFullLocksReleased;
private int mScanLocksAcquired;
private int mScanLocksReleased;
private final List<Multicaster> mMulticasters =
new ArrayList<Multicaster>();
private int mMulticastEnabled;
private int mMulticastDisabled;
private final IBatteryStats mBatteryStats;
private boolean mEnableTrafficStatsPoll = false;
private int mTrafficStatsPollToken = 0;
private long mTxPkts;
private long mRxPkts;
/* Tracks last reported data activity */
private int mDataActivity;
private String mInterfaceName;
/**
* Interval in milliseconds between polling for traffic
* statistics
*/
private static final int POLL_TRAFFIC_STATS_INTERVAL_MSECS = 1000;
/**
* See {@link Settings.Secure#WIFI_IDLE_MS}. This is the default value if a
* Settings.Secure value is not present. This timeout value is chosen as
* the approximate point at which the battery drain caused by Wi-Fi
* being enabled but not active exceeds the battery drain caused by
* re-establishing a connection to the mobile data network.
*/
private static final long DEFAULT_IDLE_MS = 15 * 60 * 1000; /* 15 minutes */
private static final String ACTION_DEVICE_IDLE =
"com.android.server.WifiManager.action.DEVICE_IDLE";
private static final int WIFI_DISABLED = 0;
private static final int WIFI_ENABLED = 1;
/* Wifi enabled while in airplane mode */
private static final int WIFI_ENABLED_AIRPLANE_OVERRIDE = 2;
/* Wifi disabled due to airplane mode on */
private static final int WIFI_DISABLED_AIRPLANE_ON = 3;
/* Persisted state that tracks the wifi & airplane interaction from settings */
private AtomicInteger mPersistWifiState = new AtomicInteger(WIFI_DISABLED);
/* Tracks current airplane mode state */
private AtomicBoolean mAirplaneModeOn = new AtomicBoolean(false);
/* Tracks whether wifi is enabled from WifiStateMachine's perspective */
private boolean mWifiEnabled;
private boolean mIsReceiverRegistered = false;
NetworkInfo mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
// Variables relating to the 'available networks' notification
/**
* The icon to show in the 'available networks' notification. This will also
* be the ID of the Notification given to the NotificationManager.
*/
private static final int ICON_NETWORKS_AVAILABLE =
com.android.internal.R.drawable.stat_notify_wifi_in_range;
/**
* When a notification is shown, we wait this amount before possibly showing it again.
*/
private final long NOTIFICATION_REPEAT_DELAY_MS;
/**
* Whether the user has set the setting to show the 'available networks' notification.
*/
private boolean mNotificationEnabled;
/**
* Observes the user setting to keep {@link #mNotificationEnabled} in sync.
*/
private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
/**
* The {@link System#currentTimeMillis()} must be at least this value for us
* to show the notification again.
*/
private long mNotificationRepeatTime;
/**
* The Notification object given to the NotificationManager.
*/
private Notification mNotification;
/**
* Whether the notification is being shown, as set by us. That is, if the
* user cancels the notification, we will not receive the callback so this
* will still be true. We only guarantee if this is false, then the
* notification is not showing.
*/
private boolean mNotificationShown;
/**
* The number of continuous scans that must occur before consider the
* supplicant in a scanning state. This allows supplicant to associate with
* remembered networks that are in the scan results.
*/
private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
/**
* The number of scans since the last network state change. When this
* exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
* supplicant to actually be scanning. When the network state changes to
* something other than scanning, we reset this to 0.
*/
private int mNumScansSinceNetworkStateChange;
/**
* Asynchronous channel to WifiStateMachine
*/
private AsyncChannel mWifiStateMachineChannel;
/**
* Clients receiving asynchronous messages
*/
private List<AsyncChannel> mClients = new ArrayList<AsyncChannel>();
/**
* Handles client connections
*/
private class AsyncServiceHandler extends Handler {
AsyncServiceHandler(android.os.Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
Slog.d(TAG, "New client listening to asynchronous messages");
mClients.add((AsyncChannel) msg.obj);
} else {
Slog.e(TAG, "Client connection failure, error=" + msg.arg1);
}
break;
}
case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
if (msg.arg1 == AsyncChannel.STATUS_SEND_UNSUCCESSFUL) {
Slog.d(TAG, "Send failed, client connection lost");
} else {
Slog.d(TAG, "Client connection lost with reason: " + msg.arg1);
}
mClients.remove((AsyncChannel) msg.obj);
break;
}
case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: {
AsyncChannel ac = new AsyncChannel();
ac.connect(mContext, this, msg.replyTo);
break;
}
case WifiManager.CMD_ENABLE_TRAFFIC_STATS_POLL: {
mEnableTrafficStatsPoll = (msg.arg1 == 1);
mTrafficStatsPollToken++;
if (mEnableTrafficStatsPoll) {
notifyOnDataActivity();
sendMessageDelayed(Message.obtain(this, WifiManager.CMD_TRAFFIC_STATS_POLL,
mTrafficStatsPollToken, 0), POLL_TRAFFIC_STATS_INTERVAL_MSECS);
}
break;
}
case WifiManager.CMD_TRAFFIC_STATS_POLL: {
if (msg.arg1 == mTrafficStatsPollToken) {
notifyOnDataActivity();
sendMessageDelayed(Message.obtain(this, WifiManager.CMD_TRAFFIC_STATS_POLL,
mTrafficStatsPollToken, 0), POLL_TRAFFIC_STATS_INTERVAL_MSECS);
}
break;
}
case WifiManager.CMD_CONNECT_NETWORK: {
if (msg.obj != null) {
mWifiStateMachine.connectNetwork((WifiConfiguration)msg.obj);
} else {
mWifiStateMachine.connectNetwork(msg.arg1);
}
break;
}
case WifiManager.CMD_SAVE_NETWORK: {
mWifiStateMachine.saveNetwork((WifiConfiguration)msg.obj);
break;
}
case WifiManager.CMD_FORGET_NETWORK: {
mWifiStateMachine.forgetNetwork(msg.arg1);
break;
}
case WifiManager.CMD_START_WPS: {
//replyTo has the original source
mWifiStateMachine.startWps(msg.replyTo, (WpsInfo)msg.obj);
break;
}
case WifiManager.CMD_DISABLE_NETWORK: {
mWifiStateMachine.disableNetwork(msg.replyTo, msg.arg1, msg.arg2);
break;
}
default: {
Slog.d(TAG, "WifiServicehandler.handleMessage ignoring msg=" + msg);
break;
}
}
}
}
private AsyncServiceHandler mAsyncServiceHandler;
/**
* Handles interaction with WifiStateMachine
*/
private class WifiStateMachineHandler extends Handler {
private AsyncChannel mWsmChannel;
WifiStateMachineHandler(android.os.Looper looper) {
super(looper);
mWsmChannel = new AsyncChannel();
mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
mWifiStateMachineChannel = mWsmChannel;
} else {
Slog.e(TAG, "WifiStateMachine connection failure, error=" + msg.arg1);
mWifiStateMachineChannel = null;
}
break;
}
case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
Slog.e(TAG, "WifiStateMachine channel lost, msg.arg1 =" + msg.arg1);
mWifiStateMachineChannel = null;
//Re-establish connection to state machine
mWsmChannel.connect(mContext, this, mWifiStateMachine.getHandler());
break;
}
default: {
Slog.d(TAG, "WifiStateMachineHandler.handleMessage ignoring msg=" + msg);
break;
}
}
}
}
WifiStateMachineHandler mWifiStateMachineHandler;
/**
* Temporary for computing UIDS that are responsible for starting WIFI.
* Protected by mWifiStateTracker lock.
*/
private final WorkSource mTmpWorkSource = new WorkSource();
private WifiWatchdogStateMachine mWifiWatchdogStateMachine;
WifiService(Context context) {
mContext = context;
mInterfaceName = SystemProperties.get("wifi.interface", "wlan0");
mWifiStateMachine = new WifiStateMachine(mContext, mInterfaceName);
mWifiStateMachine.enableRssiPolling(true);
mBatteryStats = BatteryStatsService.getService();
mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mAirplaneModeOn.set(isAirplaneModeOn());
/* On airplane mode disable, restore wifi state if necessary */
if (!mAirplaneModeOn.get() && (testAndClearWifiSavedState() ||
mPersistWifiState.get() == WIFI_ENABLED_AIRPLANE_OVERRIDE)) {
persistWifiState(true);
}
updateWifiState();
}
},
new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_DISABLED);
mWifiEnabled = (wifiState == WifiManager.WIFI_STATE_ENABLED);
// reset & clear notification on any wifi state change
resetNotification();
} else if (intent.getAction().equals(
WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
WifiManager.EXTRA_NETWORK_INFO);
// reset & clear notification on a network connect & disconnect
switch(mNetworkInfo.getDetailedState()) {
case CONNECTED:
case DISCONNECTED:
evaluateTrafficStatsPolling();
resetNotification();
break;
}
} else if (intent.getAction().equals(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
checkAndSetNotification();
}
}
}, filter);
HandlerThread wifiThread = new HandlerThread("WifiService");
wifiThread.start();
mAsyncServiceHandler = new AsyncServiceHandler(wifiThread.getLooper());
mWifiStateMachineHandler = new WifiStateMachineHandler(wifiThread.getLooper());
// Setting is in seconds
NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
mNotificationEnabledSettingObserver.register();
mBackgroundScanSupported = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_wifi_background_scan_support);
}
/**
* Check if Wi-Fi needs to be enabled and start
* if needed
*
* This function is used only at boot time
*/
public void checkAndStartWifi() {
mAirplaneModeOn.set(isAirplaneModeOn());
mPersistWifiState.set(getPersistedWifiState());
/* Start if Wi-Fi should be enabled or the saved state indicates Wi-Fi was on */
boolean wifiEnabled = shouldWifiBeEnabled() || testAndClearWifiSavedState();
Slog.i(TAG, "WifiService starting up with Wi-Fi " +
(wifiEnabled ? "enabled" : "disabled"));
setWifiEnabled(wifiEnabled);
mWifiWatchdogStateMachine = WifiWatchdogStateMachine.
makeWifiWatchdogStateMachine(mContext);
}
private boolean testAndClearWifiSavedState() {
final ContentResolver cr = mContext.getContentResolver();
int wifiSavedState = 0;
try {
wifiSavedState = Settings.Secure.getInt(cr, Settings.Secure.WIFI_SAVED_STATE);
if(wifiSavedState == 1)
Settings.Secure.putInt(cr, Settings.Secure.WIFI_SAVED_STATE, 0);
} catch (Settings.SettingNotFoundException e) {
;
}
return (wifiSavedState == 1);
}
private int getPersistedWifiState() {
final ContentResolver cr = mContext.getContentResolver();
try {
return Settings.Secure.getInt(cr, Settings.Secure.WIFI_ON);
} catch (Settings.SettingNotFoundException e) {
Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, WIFI_DISABLED);
return WIFI_DISABLED;
}
}
private boolean shouldWifiBeEnabled() {
if (mAirplaneModeOn.get()) {
return mPersistWifiState.get() == WIFI_ENABLED_AIRPLANE_OVERRIDE;
} else {
return mPersistWifiState.get() != WIFI_DISABLED;
}
}
private void persistWifiState(boolean enabled) {
final ContentResolver cr = mContext.getContentResolver();
boolean airplane = mAirplaneModeOn.get() && isAirplaneToggleable();
if (enabled) {
if (airplane) {
mPersistWifiState.set(WIFI_ENABLED_AIRPLANE_OVERRIDE);
} else {
mPersistWifiState.set(WIFI_ENABLED);
}
} else {
if (airplane) {
mPersistWifiState.set(WIFI_DISABLED_AIRPLANE_ON);
} else {
mPersistWifiState.set(WIFI_DISABLED);
}
}
Settings.Secure.putInt(cr, Settings.Secure.WIFI_ON, mPersistWifiState.get());
}
/**
* see {@link android.net.wifi.WifiManager#pingSupplicant()}
* @return {@code true} if the operation succeeds, {@code false} otherwise
*/
public boolean pingSupplicant() {
enforceAccessPermission();
if (mWifiStateMachineChannel != null) {
return mWifiStateMachine.syncPingSupplicant(mWifiStateMachineChannel);
} else {
Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
return false;
}
}
/**
* see {@link android.net.wifi.WifiManager#startScan()}
*/
public void startScan(boolean forceActive) {
enforceChangePermission();
mWifiStateMachine.startScan(forceActive);
}
private void enforceAccessPermission() {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
"WifiService");
}
private void enforceChangePermission() {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
"WifiService");
}
private void enforceMulticastChangePermission() {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
"WifiService");
}
/**
* see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
* @param enable {@code true} to enable, {@code false} to disable.
* @return {@code true} if the enable/disable operation was
* started or is already in the queue.
*/
public synchronized boolean setWifiEnabled(boolean enable) {
enforceChangePermission();
if (DBG) {
Slog.e(TAG, "Invoking mWifiStateMachine.setWifiEnabled\n");
}
if (enable) {
reportStartWorkSource();
}
mWifiStateMachine.setWifiEnabled(enable);
/*
* Caller might not have WRITE_SECURE_SETTINGS,
* only CHANGE_WIFI_STATE is enforced
*/
/* Avoids overriding of airplane state when wifi is already in the expected state */
if (enable != mWifiEnabled) {
long ident = Binder.clearCallingIdentity();
persistWifiState(enable);
Binder.restoreCallingIdentity(ident);
}
if (enable) {
if (!mIsReceiverRegistered) {
registerForBroadcasts();
mIsReceiverRegistered = true;
}
} else if (mIsReceiverRegistered) {
mContext.unregisterReceiver(mReceiver);
mIsReceiverRegistered = false;
}
return true;
}
/**
* see {@link WifiManager#getWifiState()}
* @return One of {@link WifiManager#WIFI_STATE_DISABLED},
* {@link WifiManager#WIFI_STATE_DISABLING},
* {@link WifiManager#WIFI_STATE_ENABLED},
* {@link WifiManager#WIFI_STATE_ENABLING},
* {@link WifiManager#WIFI_STATE_UNKNOWN}
*/
public int getWifiEnabledState() {
enforceAccessPermission();
return mWifiStateMachine.syncGetWifiState();
}
/**
* see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
* @param wifiConfig SSID, security and channel details as
* part of WifiConfiguration
* @param enabled true to enable and false to disable
*/
public void setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
enforceChangePermission();
mWifiStateMachine.setWifiApEnabled(wifiConfig, enabled);
}
/**
* see {@link WifiManager#getWifiApState()}
* @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
* {@link WifiManager#WIFI_AP_STATE_DISABLING},
* {@link WifiManager#WIFI_AP_STATE_ENABLED},
* {@link WifiManager#WIFI_AP_STATE_ENABLING},
* {@link WifiManager#WIFI_AP_STATE_FAILED}
*/
public int getWifiApEnabledState() {
enforceAccessPermission();
return mWifiStateMachine.syncGetWifiApState();
}
/**
* see {@link WifiManager#getWifiApConfiguration()}
* @return soft access point configuration
*/
public WifiConfiguration getWifiApConfiguration() {
enforceAccessPermission();
return mWifiStateMachine.syncGetWifiApConfiguration();
}
/**
* see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
* @param wifiConfig WifiConfiguration details for soft access point
*/
public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
enforceChangePermission();
if (wifiConfig == null)
return;
mWifiStateMachine.setWifiApConfiguration(wifiConfig);
}
/**
* see {@link android.net.wifi.WifiManager#disconnect()}
*/
public void disconnect() {
enforceChangePermission();
mWifiStateMachine.disconnectCommand();
}
/**
* see {@link android.net.wifi.WifiManager#reconnect()}
*/
public void reconnect() {
enforceChangePermission();
mWifiStateMachine.reconnectCommand();
}
/**
* see {@link android.net.wifi.WifiManager#reassociate()}
*/
public void reassociate() {
enforceChangePermission();
mWifiStateMachine.reassociateCommand();
}
/**
* see {@link android.net.wifi.WifiManager#getConfiguredNetworks()}
* @return the list of configured networks
*/
public List<WifiConfiguration> getConfiguredNetworks() {
enforceAccessPermission();
return mWifiStateMachine.syncGetConfiguredNetworks();
}
/**
* see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
* @return the supplicant-assigned identifier for the new or updated
* network if the operation succeeds, or {@code -1} if it fails
*/
public int addOrUpdateNetwork(WifiConfiguration config) {
enforceChangePermission();
if (mWifiStateMachineChannel != null) {
return mWifiStateMachine.syncAddOrUpdateNetwork(mWifiStateMachineChannel, config);
} else {
Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
return -1;
}
}
/**
* See {@link android.net.wifi.WifiManager#removeNetwork(int)}
* @param netId the integer that identifies the network configuration
* to the supplicant
* @return {@code true} if the operation succeeded
*/
public boolean removeNetwork(int netId) {
enforceChangePermission();
if (mWifiStateMachineChannel != null) {
return mWifiStateMachine.syncRemoveNetwork(mWifiStateMachineChannel, netId);
} else {
Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
return false;
}
}
/**
* See {@link android.net.wifi.WifiManager#enableNetwork(int, boolean)}
* @param netId the integer that identifies the network configuration
* to the supplicant
* @param disableOthers if true, disable all other networks.
* @return {@code true} if the operation succeeded
*/
public boolean enableNetwork(int netId, boolean disableOthers) {
enforceChangePermission();
if (mWifiStateMachineChannel != null) {
return mWifiStateMachine.syncEnableNetwork(mWifiStateMachineChannel, netId,
disableOthers);
} else {
Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
return false;
}
}
/**
* See {@link android.net.wifi.WifiManager#disableNetwork(int)}
* @param netId the integer that identifies the network configuration
* to the supplicant
* @return {@code true} if the operation succeeded
*/
public boolean disableNetwork(int netId) {
enforceChangePermission();
if (mWifiStateMachineChannel != null) {
return mWifiStateMachine.syncDisableNetwork(mWifiStateMachineChannel, netId);
} else {
Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
return false;
}
}
/**
* See {@link android.net.wifi.WifiManager#getConnectionInfo()}
* @return the Wi-Fi information, contained in {@link WifiInfo}.
*/
public WifiInfo getConnectionInfo() {
enforceAccessPermission();
/*
* Make sure we have the latest information, by sending
* a status request to the supplicant.
*/
return mWifiStateMachine.syncRequestConnectionInfo();
}
/**
* Return the results of the most recent access point scan, in the form of
* a list of {@link ScanResult} objects.
* @return the list of results
*/
public List<ScanResult> getScanResults() {
enforceAccessPermission();
return mWifiStateMachine.syncGetScanResultsList();
}
/**
* Tell the supplicant to persist the current list of configured networks.
* @return {@code true} if the operation succeeded
*
* TODO: deprecate this
*/
public boolean saveConfiguration() {
boolean result = true;
enforceChangePermission();
if (mWifiStateMachineChannel != null) {
return mWifiStateMachine.syncSaveConfig(mWifiStateMachineChannel);
} else {
Slog.e(TAG, "mWifiStateMachineChannel is not initialized");
return false;
}
}
/**
* Set the country code
* @param countryCode ISO 3166 country code.
* @param persist {@code true} if the setting should be remembered.
*
* The persist behavior exists so that wifi can fall back to the last
* persisted country code on a restart, when the locale information is
* not available from telephony.
*/
public void setCountryCode(String countryCode, boolean persist) {
Slog.i(TAG, "WifiService trying to set country code to " + countryCode +
" with persist set to " + persist);
enforceChangePermission();
mWifiStateMachine.setCountryCode(countryCode, persist);
}
/**
* Set the operational frequency band
* @param band One of
* {@link WifiManager#WIFI_FREQUENCY_BAND_AUTO},
* {@link WifiManager#WIFI_FREQUENCY_BAND_5GHZ},
* {@link WifiManager#WIFI_FREQUENCY_BAND_2GHZ},
* @param persist {@code true} if the setting should be remembered.
*
*/
public void setFrequencyBand(int band, boolean persist) {
enforceChangePermission();
if (!isDualBandSupported()) return;
Slog.i(TAG, "WifiService trying to set frequency band to " + band +
" with persist set to " + persist);
mWifiStateMachine.setFrequencyBand(band, persist);
}
/**
* Get the operational frequency band
*/
public int getFrequencyBand() {
enforceAccessPermission();
return mWifiStateMachine.getFrequencyBand();
}
public boolean isDualBandSupported() {
//TODO: Should move towards adding a driver API that checks at runtime
return mContext.getResources().getBoolean(
com.android.internal.R.bool.config_wifi_dual_band_support);
}
/**
* Return the DHCP-assigned addresses from the last successful DHCP request,
* if any.
* @return the DHCP information
*/
public DhcpInfo getDhcpInfo() {
enforceAccessPermission();
return mWifiStateMachine.syncGetDhcpInfo();
}
/**
* see {@link android.net.wifi.WifiManager#startWifi}
*
*/
public void startWifi() {
enforceChangePermission();
/* TODO: may be add permissions for access only to connectivity service
* TODO: if a start issued, keep wifi alive until a stop issued irrespective
* of WifiLock & device idle status unless wifi enabled status is toggled
*/
mWifiStateMachine.setDriverStart(true, mEmergencyCallbackMode);
mWifiStateMachine.reconnectCommand();
}
/**
* see {@link android.net.wifi.WifiManager#stopWifi}
*
*/
public void stopWifi() {
enforceChangePermission();
/* TODO: may be add permissions for access only to connectivity service
* TODO: if a stop is issued, wifi is brought up only by startWifi
* unless wifi enabled status is toggled
*/
mWifiStateMachine.setDriverStart(false, mEmergencyCallbackMode);
}
/**
* see {@link android.net.wifi.WifiManager#addToBlacklist}
*
*/
public void addToBlacklist(String bssid) {
enforceChangePermission();
mWifiStateMachine.addToBlacklist(bssid);
}
/**
* see {@link android.net.wifi.WifiManager#clearBlacklist}
*
*/
public void clearBlacklist() {
enforceChangePermission();
mWifiStateMachine.clearBlacklist();
}
/**
* Get a reference to handler. This is used by a client to establish
* an AsyncChannel communication with WifiService
*/
public Messenger getMessenger() {
/* Enforce the highest permissions
TODO: when we consider exposing the asynchronous API, think about
how to provide both access and change permissions seperately
*/
enforceAccessPermission();
enforceChangePermission();
return new Messenger(mAsyncServiceHandler);
}
/**
* Get the IP and proxy configuration file
*/
public String getConfigFile() {
enforceAccessPermission();
return mWifiStateMachine.getConfigFile();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
long idleMillis =
Settings.Secure.getLong(mContext.getContentResolver(),
Settings.Secure.WIFI_IDLE_MS, DEFAULT_IDLE_MS);
int stayAwakeConditions =
Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0);
if (action.equals(Intent.ACTION_SCREEN_ON)) {
if (DBG) {
Slog.d(TAG, "ACTION_SCREEN_ON");
}
mAlarmManager.cancel(mIdleIntent);
mScreenOff = false;
evaluateTrafficStatsPolling();
mWifiStateMachine.enableRssiPolling(true);
if (mBackgroundScanSupported) {
mWifiStateMachine.enableBackgroundScanCommand(false);
}
mWifiStateMachine.enableAllNetworks();
setDeviceIdleAndUpdateWifi(false);
} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
if (DBG) {
Slog.d(TAG, "ACTION_SCREEN_OFF");
}
mScreenOff = true;
evaluateTrafficStatsPolling();
mWifiStateMachine.enableRssiPolling(false);
if (mBackgroundScanSupported) {
mWifiStateMachine.enableBackgroundScanCommand(true);
}
/*
* Set a timer to put Wi-Fi to sleep, but only if the screen is off
* AND the "stay on while plugged in" setting doesn't match the
* current power conditions (i.e, not plugged in, plugged in to USB,
* or plugged in to AC).
*/
if (!shouldWifiStayAwake(stayAwakeConditions, mPluggedType)) {
//Delayed shutdown if wifi is connected
if (mNetworkInfo.getDetailedState() == DetailedState.CONNECTED) {
if (DBG) Slog.d(TAG, "setting ACTION_DEVICE_IDLE: " + idleMillis + " ms");
mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ idleMillis, mIdleIntent);
} else {
setDeviceIdleAndUpdateWifi(true);
}
}
} else if (action.equals(ACTION_DEVICE_IDLE)) {
setDeviceIdleAndUpdateWifi(true);
} else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
/*
* Set a timer to put Wi-Fi to sleep, but only if the screen is off
* AND we are transitioning from a state in which the device was supposed
* to stay awake to a state in which it is not supposed to stay awake.
* If "stay awake" state is not changing, we do nothing, to avoid resetting
* the already-set timer.
*/
int pluggedType = intent.getIntExtra("plugged", 0);
if (DBG) {
Slog.d(TAG, "ACTION_BATTERY_CHANGED pluggedType: " + pluggedType);
}
if (mScreenOff && shouldWifiStayAwake(stayAwakeConditions, mPluggedType) &&
!shouldWifiStayAwake(stayAwakeConditions, pluggedType)) {
long triggerTime = System.currentTimeMillis() + idleMillis;
if (DBG) {
Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for " + idleMillis + "ms");
}
mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
}
mPluggedType = pluggedType;
} else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
BluetoothAdapter.STATE_DISCONNECTED);
mWifiStateMachine.sendBluetoothAdapterStateChange(state);
} else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
mEmergencyCallbackMode = intent.getBooleanExtra("phoneinECMState", false);
updateWifiState();
}
}
/**
* Determines whether the Wi-Fi chipset should stay awake or be put to