启用/关闭Wifi,并显示当前Wifi的状态

wifi的状态总共有五种:

WIFI DISABLED,

WIFI DISABLING,

WIFI ENABLED,

WIFI ENABLEING,

WIFI UNKNOW

 

要设置 WIFI 的状态

//获得wifi的管理器 mWifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE); //设置wifi是否可用 mWifiManager.setWifiEnabled(true);

 

要获得wifi的状态,择需要捕获wifi发出的广播信息,创建接收器类如下:

private class WifiStateReceiver extends BroadcastReceiver { public void onReceive(Context c, Intent intent) { Bundle bundle = intent.getExtras(); // int oldInt = bundle.getInt("previous_wifi_state"); int newInt = bundle.getInt("wifi_state"); switch (newInt){ case WifiManager.WIFI_STATE_DISABLED: txtWifi.setText(R.string.wifi_disabled); break; case WifiManager.WIFI_STATE_DISABLING: txtWifi.setText(R.string.wifi_disabling); break; case WifiManager.WIFI_STATE_ENABLED: txtWifi.setText(R.string.wifi_enabled); break; case WifiManager.WIFI_STATE_ENABLING: txtWifi.setText(R.string.wifi_enabling); break; case WifiManager.WIFI_STATE_UNKNOWN: txtWifi.setText(R.string.wifi_unknow); break; } } }

 

特别要注意的是获取wifi状态是需要设置用户权限的,所以需要在AndroidManifest.xml 中添加权限说明如下:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"> </uses-permission> <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"> </uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"> </uses-permission>

 

 

 

你可能感兴趣的:(c,android,service,Class)