Full project with source how to programmatically activate and deactivate WiFi using the WifiManager class and it’s setWifiEnabled method. For this we have to add the ACCESS_WIFI_STATE and the CHANGE_WIFI_STATE Manifest permissions
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="tech.codingpoint.togglewifiexample.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="enableWifi"
android:text="Wifi ON" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="disableWifi"
android:text="Wifi OFF" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tech.codingpoint.togglewifiexample">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package tech.codingpoint.togglewifiexample;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private WifiManager wifiManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
}
public void enableWifi(View v) {
wifiManager.setWifiEnabled(true);
}
public void disableWifi(View v) {
wifiManager.setWifiEnabled(false);
}
}