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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<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.