Turn On/Off Wi-Fi From Your Application

This example explains how to turn on/off Wi-Fi from your application in android.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it WiFiOnOffExample.

2.) Write following into main.xml:

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".WiFiOnOffExampleActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle button to Turn ON/Off WiFi" />

<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginLeft="48dp"
android:text="ToggleButton" />

</RelativeLayout>

 

3.) Add following permissions to your manifest:

 

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

 

4.) Run for output.

Steps:

1.) Create a project named WiFiOnOffExample and set the information as stated in the image.

Build Target: Android 4.4
Application Name: WiFiOnOffExample
Package Name: com.example.WiFiOnOffExample
Activity Name: WiFiOnOffExampleActivity

wifionoff1

2.) Open WiFiOnOffExampleActivity.java file and write following code there:

 

package com.example.wifionoffexample;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;

public class WiFiOnOffExampleActivity extends Activity {
ToggleButton b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (ToggleButton) findViewById(R.id.toggleButton1);
b1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if((b1.isChecked()))
{
WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
else
{
WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}
}

});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.wi_fi_on_off_example, menu);

return true;
}
}

 

 

3.) Compile and build the project.

Output

wifionoff2

wifionoff3