Enable And Disable Wi-Fi In Android Application Using toggle button
Hello Guys. Welcome to our new tutorial of Enable And Disable Wi-Fi In Android Application Using toggle button. enable or disable wifi by clicking the toggle button.
please follow the code given below to turn on and off wifi using toggle button.
- First Create a new project in Android Studio
- File ⇒ New Android ⇒ Application Project
- Then Open src -> package -> MainActivity.java and then add following code :
JAVA (MainActivity.java)
import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.tutorial.personal.androidstudiopro.R;
public class enableordisablewifiusingtogglebutton extends AppCompatActivity {
ToggleButton toggleButton;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enableordisablewifiusingtogglebutton);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
textView = (TextView) findViewById(R.id.textView);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
textView.setText("WiFi is ON");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
} else {
textView.setText("WiFi is OFF");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
}
});
if (toggleButton.isChecked()) {
textView.setText("WiFi is ON");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
} else {
textView.setText("WiFi is OFF");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
}
}
- Now Open res -> layout -> activity_main.xml and then add following code :
XML (activity_main.xml)
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:gravity="center"
android:orientation="vertical">
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
/>
</LinearLayout>
Output:
Finally, run this project.
This is how your application looks like.


