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 Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use.



Create a flutter project



So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter.



Once your project is created you will get the default counter app and you try running the app in the…

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 sync completed.
Update the project build config …

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit.
What is Retrofit?
If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps.

Further, you can check the Retrofit Library here.

So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website.
Prerequisite for using the Retrofit for WordPress Android App
There is s…