Tutorials Android Code Snippet: Turn on and off Wi-Fi using Android API

Code Snippet: Turn on and off Wi-Fi using Android API

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>
Total
0
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post
Android Tutorials

How to Add Click Listener to Android Switch

Next Post
Firebase Crash Reporing Android

How to Use Firebase Crash Reporting in Android

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
0
Would love your thoughts, please comment.x
()
x