1、权限
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 获取WIFI信息状态的权限 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
2、注册广播
/**
* Wifi 状态监听注册
*/
private void registerWifiReceiver() {
if (mWifiReceiver == null) return;
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mWifiReceiver, filter);
}
3、广播监听
private class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
Constant.wifiInfo = null;
ToastUtil.show("断开wifi");
} else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Constant.wifiInfo = wifiManager.getConnectionInfo();
ToastUtil.show("连接wifi");
}
}
}
}
}
4、注销广播
@Override
protected void onDestroy() {
super.onDestroy();
if (mWifiReceiver != null) {
unregisterReceiver(mWifiReceiver);
}
}
|