1、基础准备工作
先进行WiFi权限的声明
<!-- 获取WiFi状态 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- api <= Android29调用setWifiEnabled -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 定位权限(api >= 23 用于 WIFI扫描)-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
注意:ACCESS_FINE_LOCATION和ACCESS_COARSE_LOCATION是危险级权限需要使用中还需要动态申请,申请其中一个即可。
2、WiFi打开关闭 (注意Android10之后不支持setWifiEnabled打开关闭 详情)
WifiManager mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.R) {
Intent panelIntent =new Intent(Settings.Panel.ACTION_WIFI);
startActivityForResult(panelIntent,null);
}else{ mWifiManager.setWifiEnabled(!isEnable);}
3、WiFi状态监听
可以通过监听系统广播来了解WiFi状态。
WIFI_STATE_CHANGED_ACTION:WiFi开关状态;
SCAN_RESULTS_AVAILABLE_ACTION:WiFi列表变化;
RSSI_CHANGED_ACTION:WiFi信号强度变化。
IntentFilter mFilter =new IntentFilter();
mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
mReceiver =new BroadcastReceiver() {
@Override
public void onReceive(Context context,Intent intent) {
handleEvent(intent);
}
};
registerReceiver(mReceiver, mFilter);
private void handleEvent(Intent intent) {
String action = intent.getAction();
if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
final int wifiState =mWifiManager.getWifiState();
if(wifiState ==WifiManager.WIFI_STATE_ENABLED){
postDelayed(()->{mRefreshLayout.autoRefresh();},1000);
}
}else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
}else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
if(System.currentTimeMillis() -mLastUpateWifiRssiTime <1000){//刷新太快
return;
}
}
updateWifiChange();
}
切记:wifistate切换到WifiManager.WIFI_STATE_ENABLED,mWifiManager.isWifiEnabled()需要有个等待时间切换。
4、WiFi扫描
3的基础上解析广播应答
private void updateWifiChange() {
final int wifiState =mWifiManager.getWifiState();
switch (wifiState) {
case WifiManager.WIFI_STATE_ENABLED:
ArrayListresults = (ArrayList)mWifiManager.getScanResults();
updateApListView(results);
mWlanSb.setChecked(mWifiManager.isWifiEnabled() );
break;
case WifiManager.WIFI_STATE_ENABLING:
break;
case WifiManager.WIFI_STATE_DISABLING:
mAdapter.clearData();
mWlanSb.setChecked(mWifiManager.isWifiEnabled() );
break;
case WifiManager.WIFI_STATE_DISABLED:
break;
}
}