Android java code to turn ON/OFF WiFi

getSystemService(Context.WIFI_SERVICE) is used to access Android mobile WiFi using Java code

Using getSystemService we can control Wifi in Android by checking its status and to toggle WiFi status ON/OFF

Following is example to toggle Android WiFi status

ackage com.example.wifitest; import; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.Toast; import; import android.content.Context; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Switch toggle = (Switch) findViewById(; toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { toggleWiFi(true); Toast.makeText(getApplicationContext(), "Wi-Fi Enabled!", Toast.LENGTH_LONG).show(); } else { toggleWiFi(false); Toast.makeText(getApplicationContext(), "Wi-Fi Disabled!", Toast.LENGTH_LONG).show(); } } }); } 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); } } }
Sign In or Register to comment.