Turn WiFi enable/disable using WIFI Manager in Android Application
Using the Wifi Manager class you can get access to Wifi to
change its state.
In this Application, as shown TextView shows the WiFi status.
Here is how you can programmatically access Wifi in Android Application
:-
import
android.app.Activity;
import
android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import
android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import
android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import android.widget.ImageSwitcher;
import
android.widget.TextView;
public class
ConnectivitymanagerActivity extends
Activity implements OnClickListener {
Button TurnWifion, TurnWifioff;
TextView
wifistatus;
WifiManager
wifi;
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TurnWifion = (Button)findViewById(R.id.button1);
TurnWifioff = (Button)findViewById(R.id.button2);
WifiStatus = (TextView)findViewById(R.id.textView1);
//
Getting the WiFi Services
wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
//Checking whether Wifi is on or off
if(wifi.isWifiEnabled())
{
wifistatus.setText("Connected");//If WiFi is
on, enable "Turn WiFi off" button.
TurnWifioff.setEnabled(true);
TurnWifion.setEnabled(false);
}
else
{
wifistatus.setText("Disconnected");//If WiFi is
off, enable "Turn WiFi on" button.
Turnwifion.setEnabled(true);
TurnWifioff.setEnabled(false);
}
Turnwifion.setOnClickListener(this);
Turnwifioff.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated
method stub
if(Turnwifion.isPressed()) //If "Turn WiFi on" button is Pressed
{
wifi.setWifiEnabled(true);// Enabling WiFi
Turnwifioff.setEnabled(true);
Turnwifion.setEnabled(false);
wifistatus.setText("Connected");
}
if(Turnwifioff.isPressed()) //If
"Turn WiFi off" button is Pressed
{
wifi.setWifiEnabled(false); //Disabling WiFi
Turnwifion.setEnabled(true);
Tunwifioff.setEnabled(false);
wifistatus.setText("Disconnected");
}
}
}
Permissions : You need to
declare the following permissions in AndroidManifest.xml to let Wifi Manager class access the WiFi.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"
/>
<uses-permission android:name="android.permission.INTERNET"
/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"
/>
<uses-permission android:name="android.permission.WAKE_LOCK" />