How to Programmatically Turn on and off Wifi on Android Device

LinkedIn
Hacker News

Use the following code snippets to turn on and off wifi on Android devices.

Switch toggle = (Switch) findViewById(R.id.wifi_switch);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		toggleWiFi(isChecked);
	}
});

public void toggleWiFi(boolean status) {
	WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
	if (status == true && !wifiManager.isWifiEnabled()) {
		wifiManager.setWifiEnabled(true);
	} else if (status == false && wifiManager.isWifiEnabled()) {
		wifiManager.setWifiEnabled(false);
	}
}

Please note, for changing wifi state, you need the following permissions in your manifest file.

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

-Advertisement-

Tagged in : Android Java

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.