Scan and List All Available WiFi Network In Android

Scan and List All Available WiFi Network In Android

In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network.

You May Like Below Topic:

Introduction

In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. We will add this functionality to our existing Demo app “Video Gallery“.

If you would like to check out the demo of the app then downloaded the app from Google Play Store.

We are here dividing the whole tutorial into two parts, in the first part will search for all available network and show the results in a RecyclerView, in second part will connect to the particular network which is listed in the first part.

Creating Fragment for How to get Available wifi networks and display them in a list in android

As explained earlier we are creating this functionality to out existing Video Gallery app tutorial. Apart from this, some other tutorials are also used in this which are given below.

Create Layout File

So first we have to add a Fragment to our existing for which we will work on WiFi parts. First of all, we are going to create the layout of our Fragment.

WiFi Search Demo

For this fragment, we are going to use the constraint layout, a Recycler View and Button to refresh the list of available network. The layout will look like as given in the screenshot.

As you can see we are using constraint layout for this fragment, it is the new layout which is very useful to create the responsive layout in android you can learn more about this here.

Create Fragment Class

Right Click on your project > New > Fragment > Blank Fragment or alternatively, you can just create a class and modify the code as given here.
The Complete code will look like as given below.

 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 public class WifiFragment extends Fragment {  
   public HomeFragment() {  
     // Required empty public constructor  
   }  
   public static WifiFragment newInstance() {  
     WifiFragment fragment = new WifiFragment();  
     return fragment;  
   }  
   @Override  
   public void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
   }  
   @Override  
   public void onActivityCreated(Bundle savedInstanceState) {  
     super.onActivityCreated(savedInstanceState);  
   }  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container,  
                Bundle savedInstanceState) {  
     // Inflate the layout for this fragment  
     return inflater.inflate(R.layout.fragment_wifi, container, false);  
   }  
 }  

So, basic Fragment class we have created and inflated the layout which we have created in step 2.1.

Permission required to access the WiFi Network

For scanning the WiFi network we must declare the permission ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION in order to get valid results in Android Manifesto files.  If you are targeting Android M or the later version of Android then you have to also handle the permission in code as required.

You should add the all required permission in AndroidManifest as given below.

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

Registering the Broadcastreceiver from fragment

Broadcast receiver we will use and register it with application context so that any change in WiFi network should be get notified of our application. So add below code in onActivityCreated method of Fragment.

getActivity().registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                wifiList=wifi.getScanResults();
                netCount=wifiList.size();
                Log.d("Wifi","Total Wifi Network"+netCount);
            }
        },new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

Here wifi list, netCount and wifi the are variables which were declared as given below.

List<ScanResult> wifiList; 
private WifiManager wifi;
int netCount=0;

Scan Result-   It keeps track of information about the detected access point, like quality, noise, and maxbitrate.
wifi-  wifi is the instance of WifiManger class, its provide us primary API for managing all kind of the operation of WiFi.

Search and list all WiFi Network

Below is the code that needs to add to some event to detect the recently scanned wifi Network. startscan() function request a scan for access points. Returns immediately. The availability of the results is made known later by means of an asynchronous event sent on completion of the scan. It returns a boolean true if results are the success.

  wifi.startScan(); 
values.clear(); 
try { netCount=netCount -1; 
while (netCount>=0){ 
device d= new device(); 
d.setName(wifiList.get(netCount).SSID.toString()); values.add(d); 
wifiScanAdapter.notifyDataSetChanged(); netCount=netCount -1;
 }
 } 
catch (Exception e){ Log.d("Wifi", e.getMessage());
 }

The complete code of the WiFi Fragment is as given below.

WifiFragment.java

package com.debugandroid.VideoGallery;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.net.wifi.WifiManager;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WifiFragment extends Fragment {
public class device{
CharSequence name;
public void setName(CharSequence name) {
this.name = name;
}
public CharSequence getName (){
return name;
}
}
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 125;
List<ScanResult> wifiList;
private WifiManager wifi;
List<device> values = new ArrayList<device>();
int netCount=0;
RecyclerView recyclerView;
WifiScanAdapter wifiScanAdapter;
public WifiFragment() {
// Required empty public constructor
}
public static WifiFragment newInstance() {
WifiFragment fragment = new WifiFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Make instance of Wifi
Button btnScan= (Button) getActivity().findViewById(R.id.wifiScan);
wifi = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//Check wifi enabled or not
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getActivity(), "Wifi is disabled enabling...", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
//register Broadcast receiver
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
wifiList=wifi.getScanResults();
netCount=wifiList.size();
// wifiScanAdapter.notifyDataSetChanged();
Log.d("Wifi","Total Wifi Network"+netCount);
}
},new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiScanAdapter=new WifiScanAdapter(values,getContext());
recyclerView= (RecyclerView) getActivity().findViewById(R.id.wifiRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(wifiScanAdapter);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkandAskPermission();
} else {
wifi.startScan();
values.clear();
try {
netCount = netCount - 1;
while (netCount >= 0) {
device d = new device();
d.setName(wifiList.get(netCount).SSID.toString());
Log.d("WiFi",d.getName().toString());
values.add(d);
wifiScanAdapter.notifyDataSetChanged();
netCount=netCount -1;
}
}
catch (Exception e){
Log.d("Wifi", e.getMessage());
}
}
btnScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
wifi.startScan();
values.clear();
try {
netCount=netCount -1;
while (netCount>=0){
device d= new device();
d.setName(wifiList.get(netCount).SSID.toString());
values.add(d);
wifiScanAdapter.notifyDataSetChanged();
netCount=netCount -1;
}
}
catch (Exception e){
Log.d("Wifi", e.getMessage());
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_wifi, container, false);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
if (perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
wifi.startScan();
} else {
// Permission Denied
Toast.makeText(getContext(), "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
}
}
}
}
private void checkandAskPermission() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
permissionsNeeded.add("Network");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 0; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
});
return;
}
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
// initVideo();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(getActivity())
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (getActivity().checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
return true;
}
}

Creating Adapter for Recyclerview

Now, We also required a Recyclerview Adapter to hold the scan network list and display the same on fragment so create an adapter class by right clicking on project>New> New Class and modify it as given below.

WifiScanAdapter.java

package com.debugandroid.VideoGallery;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.NativeExpressAdView;
import java.util.List;
public class WifiScanAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<WifiFragment.device> wifiList;
private Context context;
public WifiScanAdapter(List<WifiFragment.device> wifiList, Context context) {
this.wifiList = wifiList;
this.context=context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.network_list, viewGroup, false);
VideoViewHolder holder = new VideoViewHolder(itemView);
itemView.setTag(holder);
return holder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
WifiFragment.device device=wifiList.get(position);
String name=device.getName().toString();
((VideoViewHolder) holder).vName.setText(name);
((VideoViewHolder) holder).vImage.setImageResource(R.drawable.ic_network_wifi_black_24dp);
((VideoViewHolder) holder).context = context;
((VideoViewHolder) holder).position = position;
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public int getItemCount() {
int itemCount = wifiList.size();
return itemCount;
}
public class VideoViewHolder extends RecyclerView.ViewHolder {
protected ImageView vImage;
protected TextView vName;
protected  Context context;
protected int position;
public VideoViewHolder(View v) {
super(v);
vName =  (TextView) v.findViewById(R.id.ssid_name);
vImage = (ImageView)  v.findViewById(R.id.Wifilogo);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
}

 

Above adapter are display the list of all available network when you click on refresh button. Download the complete source code from GitHub.

If you like to go through this as well to check out how to connect to the specific Network and take password input from the user.

How to read and write JSON data from File:-

https://www.nplix.com/how-to-read-and-write-json-data-using-gson/

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

This Post Has 9 Comments

  1. Hi, this code works great btw!!!
    Is there a way to modify it so that BSSID and RSSI is also in the output?

    1. Hi Joe,

      You can get the all the details that can be returned from the scan result.

      wifiList.get(netCount).SSID.toString()

  2. is it work now?? i’m trying to test it, but there is no result.
    the only way to use this is turn on the gps.
    if i didn’t turn on the gps even if get permission, there is no result
    i download the github file. plz reply

    1. Can you let me know on which Android version you are testing. However this sample tutorial is only work when your wifi network is manually enabled, it will not start your WiFi.

      1. i tested it on Nougat-Android 7.1
        of course my wifi is manually on, only GPS is off.

        plus, when i change target SDK 25 to 22 it works.
        i think it related with Permission or SDK level.

      2. hi! i find some discussion about this issue. “https://issuetracker.google.com/issues/37060483#c18” following this url, GPS must turned On When you get WifiList over API 23 even if wifi turned on. but following your blog you don’t have to Turn on GPS. only wifi network is manually enable and FineLocation Or CoarseLocation Permission. would you plz test it work well on target API 25 or over.

        1. Yes, you are right that’ why I asked about version on which you are testing.

          1. thanks a lot. happy New Year!

Leave a Reply

Close Menu
%d bloggers like this: