Pages

Search Tutorials

Monday, 28 October 2013

Enable and Disable WiFi using Program in Android

In this application, we will learn how to enable and disable WiFi using simple code. So create new project and drop only one button on relative layout which will use to enable and disable WiFi and give id button1 to button. The code of android XML file is given below:

Now open your Java file and WiFi manager is used to get WiFi service and enable and disable WiFi. This is very simple because only isWiFienabled() method is used to check WiFi is on or off and change the state of WiFi. The code of android Java file is given below with explanation:

package
innosen.wwf; //your
package name

import
android.net.wifi.WifiManager;

import
android.os.Bundle;

import
android.app.Activity;

import
android.view.View;

import
android.widget.Button;

publicclass
MainActivity extends
Activity {

WifiManager
wm;

@Override

protectedvoid
onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}

//this
method will call on button click

publicvoid
wwf(View v)

{

Button
b1=(Button)findViewById(R.id.button1);

//get
Wifi
service

wm=(WifiManager)getSystemService(WIFI_SERVICE);

//Check
Wifi
is on or off

if(wm.isWifiEnabled())

{

b1.setText("Wifi
ON");

//enable
or disable Wifi

//for
enable pass true value

//for
disable pass false value

wm.setWifiEnabled(false);

}

else

{

b1.setText("Wifi
OFF");

wm.setWifiEnabled(true);

}

}

}

Now open your AndroidManifest.xml file and take permission to check WiFi state and to change WiFi state. The code of AndroidManifest.xml file is given below:

<?xmlversion="1.0"encoding="utf-8"?>

<manifestxmlns:android="http://schemas.android.com/apk/res/android"

package="selecm.wwf"

android:versionCode="1"

android:versionName="1.0">

<uses-sdk

android:minSdkVersion="8"

android:targetSdkVersion="10"/>

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

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

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme">

<activity

android:name="innosen.wwf.MainActivity"

android:label="@string/app_name">

<intent-filter>

<actionandroid:name="android.intent.action.MAIN"/>

<categoryandroid:name="android.intent.category.LAUNCHER"/>

</intent-filter>

</activity>

</application>

</manifest>

Now run your application and install .APK file in your mobile and test. You can’t test this application on emulator.
If you have any doubts please comment. Thanks… :)