Check Wi-Fi State In Android

This example explains how to check Wi-Fi state from your application in android.

Algorithm:

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

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=".CheckWiFiStateActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

</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 CheckWiFiState and set the information as stated in the image.

Build Target: Android 4.4
Application Name: CheckWiFiState
Package Name: com.example.CheckWiFiState
Activity Name: CheckWiFiStateActivity

checkwifi1

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

 

package com.example.checkwifistate;

import android.app.Activity;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class CheckWiFiStateActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent();
int WifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE ,
WifiManager.WIFI_STATE_UNKNOWN);

if(WifiState == WifiManager.WIFI_STATE_ENABLED )
{
Toast.makeText(CheckWiFiStateActivity.this, "WI-FI enabled", Toast.LENGTH_LONG).show();
}
else if (WifiState == WifiManager.WIFI_STATE_ENABLING)
{
Toast.makeText(CheckWiFiStateActivity.this, "WI-FI enabling", Toast.LENGTH_LONG).show();

}
else
Toast.makeText(CheckWiFiStateActivity.this, "WI-FI disabled", Toast.LENGTH_LONG).show();

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

 

 

3.) Compile and build the project.

Output

checkwifi2