Skip to main content

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/

Comments

  1. 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

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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.

    ReplyDelete
  4. 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.

    ReplyDelete
  5. Yes, you are right that' why I asked about version on which you are testing.

    ReplyDelete
  6. thanks a lot. happy New Year!

    ReplyDelete
  7. […] In last tutorial of WiFi we have learn about how to scan and list the all available Wifi network. In this part of the tutorial we will learn about how to scan and connect to specific SSID. We have have use the code of last part of the tutorial as base app. So if you don’t go through the last tutorial you can check out it Scan and List all WiFi Network In Android. […]

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

    ReplyDelete
  9. Hi Joe,

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

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

    ReplyDelete
  10. Hi bro, thanks for the sample. I would like to keep the list in a live mode. How can I achieve that? Now your list will be updated once the button has been clicked. Thanks

    ReplyDelete
  11. hi i want the complete source code for how to connect to the specific Network and take password input from the user.
    can u pls help me with this

    ReplyDelete
  12. You can find the code at https://github.com/debugandroid/WiFiDemoApp
    You can also refer the https://www.nplix.com/scan-wifi-network-connect-android/

    ReplyDelete
  13. You can find the code at https://github.com/debugandroid/WiFiDemoApp
    You can also refer the https://www.nplix.com/scan-wifi-network-connect-android/

    ReplyDelete

Post a Comment

Popular posts from this blog

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View. Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android Just go to the android folder and open it in separate windows. We will have the following project structure. Create the Activity Just right-click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project s

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface

Create Custom EditText View in Android

We use the EditText for taking the input from the user and use it at several places in our project. We required to do lots of customization for each time and there are lots of redundant code we write. Writing and managing these redundant codes is very difficult for example if we want to change the look and feel of the view them we need to modify it at each place where our EditText is getting used. So to avoid these kinds of the problem we can create our own Custom EditText View by just. The EditText view is just an extension of the TextView with lots of editing option and properties that required for the user input. How To Create Custom EditText View For creating the Custom EditText we need to extend the AppCompatEditText and override all three constructors of the view as given below. import android.content.Context; import android.graphics.Typeface; import android.support.annotation.Nullable; import android.support.v7.widget.AppCompatEditText; import android.util.AttributeSet; public