Getting / setting Wifi in Android is easy.
First, set permission in manifest.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
CHANGE_WIFI_STATE is not needed when only getting status. Now, simple code.
WifiManager wifi; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); wifi = (WifiManager)getSystemService(WIFI_SERVICE); } public boolean checkWifi() { return (wifi.isWifiEnabled()); } public void setWifi(boolean set){ wifi.setWifiEnabled(set); }
Since Wifi status changes realtime, register BroadcastReceiver if you want to get notified if status changes.
@Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); registerReceiver(mBroadcastReceiver, filter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(mBroadcastReceiver); } private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE , WifiManager.WIFI_STATE_UNKNOWN); if (extraWifiState == WifiManager.WIFI_STATE_DISABLED){ } else if (extraWifiState == WifiManager.WIFI_STATE_ENABLED){ } } } };
This post is also available in: Japanese