Android get wifi list

How to get available wifi networks and display them in a list in android

Friends, I want to find all available WiFi networks and display them in a list I have tried as below. But it’s not working. I have edited my code, and now I got the result but with all the result that I don’t need. I only need names of wifi network in my list.

public class MainActivity extends Activity < TextView mainText; WifiManager mainWifi; WifiReceiver receiverWifi; ListwifiList; StringBuilder sb = new StringBuilder(); @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainText = (TextView) findViewById(R.id.tv1); mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (mainWifi.isWifiEnabled() == false) < // If wifi disabled then enable it Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show(); mainWifi.setWifiEnabled(true); >receiverWifi = new WifiReceiver(); registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); mainWifi.startScan(); mainText.setText("Starting Scan. "); > public boolean onCreateOptionsMenu(Menu menu) < menu.add(0, 0, 0, "Refresh"); return super.onCreateOptionsMenu(menu); >public boolean onMenuItemSelected(int featureId, MenuItem item) < mainWifi.startScan(); mainText.setText("Starting Scan"); return super.onMenuItemSelected(featureId, item); >protected void onPause() < unregisterReceiver(receiverWifi); super.onPause(); >protected void onResume() < registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); super.onResume(); >// Broadcast receiver class called its receive method // when number of wifi connections changed class WifiReceiver extends BroadcastReceiver < // This method call when number of wifi connections changed public void onReceive(Context c, Intent intent) < sb = new StringBuilder(); wifiList = mainWifi.getScanResults(); sb.append("\n Number Of Wifi connections :"+wifiList.size()+"\n\n"); for(int i = 0; i < wifiList.size(); i++)< sb.append(new Integer(i+1).toString() + ". "); sb.append((wifiList.get(i)).toString()); sb.append("\n\n"); >mainText.setText(sb); > > > 

4 Answers 4

You need to create a BroadcastReceiver to listen for Wifi scan results:

private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() < @Override public void onReceive(Context c, Intent intent) < if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) < ListmScanResults = mWifiManager.getScanResults(); // add your logic here > > > 

In onCreate() you would assign mWifiManager and initiate a scan:

mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); mWifiManager.startScan(); 

getScanResults() will return data only if you have appropriate permissions. For this, add one of the following two lines to your AndroidManifest.xml :

Also note that in API 23+, permissions must be requested at runtime. (For a lab environment, you can also grant permissions manually in Settings instead—less coding required, but not recommended for an end-user app.)

Note that the code which handles your scan results would run every time a new scan result is available, updating the result.

Please see my updated code. now i got the all available networks in list but it comes with details like BSSID,level and all that. so i only need the name of that wifi network..can you pls help me to sort it out.

Читайте также:  Realtek wifi android driver

See the SDK documentation for ScanResult. There is a method called getSSID() (or similar). The SSID is the «display» name of the network.

Sorry, there is a bug in my Nexus 5, it shows the list of WiFi only when GPS is turned on..Your code works

@BalaVishnu Looks like the GPS setting enables/disables all location services, including wifi scans, so that no location can be inferred from nearby wifis.

android.permission.ACCESS_WIFI_STATE is also needed. Didn’t find anything in the docs, but that’s what the RuntimeException is telling me. Is this a new thing? Why isn’t anybody mentioning that here?

After Android 6.0

If your Android OS version is 6.0 or above then your application must ask for the following permission at runtime(Either of the following).

How to ask the permission at runtime

Just add this code in the onResume method of your activity

@Override public void onResume() < super.onResume(); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) < requestPermissions(new String[], 87); > > > 

What will happen if you don’t have the above permission at Runtime?

Wifi.getScanResults() will return 0 results.

Many people including me have faced this problem in Nexus 5 phones and referred to it as a «bug».

How to scan and read wifi networks? (Deeper Understanding)

Scanning can be requested by

boolean startScan() returns true or false immediately based on the fact whether the scan has started successfully or not.
However it starts an asynchronous event which sends an intent (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) when the scan completes. Since the scan results (asynchronous event result) will not be available immediately, you will have to register your activity with a BroadcastReceiver.

Here is the code snippet to read those results(asynchronously) using BroadcastReceiver.

public class WifiScanReceiver extends BroadcastReceiver < @Override public void onReceive(Context context, Intent intent) < if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) < ListscanResults = wifimanager.getScanResults(); // Write your logic to show in the list > > > 

probably «android.permission.ACCESS_FINE_LOCATION» also covers «android.permission.ACCESS_COARSE_LOCATION» if am not wrong

 class WifiReceiver extends BroadcastReceiver < public void onReceive(Context c, Intent intent) < sb = new StringBuilder(); wifiList = mainWifi.getScanResults(); for (int i = 0; i < wifiList.size(); i++)< sb.append(new Integer(i+1).toString() + "."); sb.append((wifiList.get(i)).SSID); sb.append("\n"); >mainText.setText(sb); > > 

Android 10 (API level 29) and higher:

A successful call to WifiManager.startScan() requires all of the following conditions to be met:

If your app is targeting Android 10 (API level 29) SDK or higher, your app has the ACCESS_FINE_LOCATION permission. If your app is targeting SDK lower than Android 10 (API level 29), your app has the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission. Your app has the CHANGE_WIFI_STATE permission. Location services are enabled on the device (under Settings > Location). 

To successfully call WifiManager.getScanResults(), ensure all of the following conditions are met:

If your app is targeting Android 10 (API level 29) SDK or higher, your app has the ACCESS_FINE_LOCATION permission. If your app is targeting SDK lower than Android 10 (API level 29), your app has the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission. Your app has the ACCESS_WIFI_STATE permission. Location services are enabled on the device (under Settings > Location). 

If the calling app doesn’t meet all of these requirements, the call fails with a SecurityException.

Читайте также:  Фотоаппараты настройка вай фай

this is the code which you can try:

BtWifiscan.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < requestPermissions(new String[], 1); > > >); public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) < if (requestCode == 1/*PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION*/ && grantResults[0] == PackageManager.PERMISSION_GRANTED) < permisio_state[1] = 1; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < requestPermissions(new String[], 2); > > if (requestCode == 2/*PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION*/ && grantResults[0] == PackageManager.PERMISSION_GRANTED) < permisio_state[2] = 2; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < requestPermissions(new String[], 3); > > if (requestCode == 3/*PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION*/ && grantResults[0] == PackageManager.PERMISSION_GRANTED) < permisio_state[3] = 3; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < requestPermissions(new String[], 4); > > if (requestCode == 4/*PERMISSIONS_REQUEST_CODE_ACCESS_COARSE_LOCATION*/ && grantResults[0] == PackageManager.PERMISSION_GRANTED) < permisio_state[4] = 4; >if (permisio_state[1] == 1 && permisio_state[2] == 2 && permisio_state[3] == 3 && permisio_state[4] == 4) WifiScaning(); > 

Источник

How to get available wifi networks and display them in a list in android

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.java

package com.example.myapplication; import android.Manifest; import android.content.Context; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.wifi.WifiManager; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends AppCompatActivity < private ListView wifiList; private WifiManager wifiManager; private final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1; WifiReceiver receiverWifi; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wifiList = findViewById(R.id.wifiList); Button buttonScan = findViewById(R.id.scanBtn); wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) < Toast.makeText(getApplicationContext(), "Turning WiFi ON. ", Toast.LENGTH_LONG).show(); wifiManager.setWifiEnabled(true); >buttonScan.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) < ActivityCompat.requestPermissions( MainActivity.this, new String[], MY_PERMISSIONS_ACCESS_COARSE_LOCATION); > else < wifiManager.startScan(); >> >); > @Override protected void onPostResume() < super.onPostResume(); receiverWifi = new WifiReceiver(wifiManager, wifiList); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); registerReceiver(receiverWifi, intentFilter); getWifi(); >private void getWifi() < if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < Toast.makeText(MainActivity.this, "version>= marshmallow", Toast.LENGTH_SHORT).show(); if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) < Toast.makeText(MainActivity.this, "location turned off", Toast.LENGTH_SHORT).show(); ActivityCompat.requestPermissions(MainActivity.this, new String[], MY_PERMISSIONS_ACCESS_COARSE_LOCATION); > else < Toast.makeText(MainActivity.this, "location turned on", Toast.LENGTH_SHORT).show(); wifiManager.startScan(); >> else < Toast.makeText(MainActivity.this, "scanning", Toast.LENGTH_SHORT).show(); wifiManager.startScan(); >> @Override protected void onPause() < super.onPause(); unregisterReceiver(receiverWifi); >@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) < super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) < case MY_PERMISSIONS_ACCESS_COARSE_LOCATION: if (grantResults.length >0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) < Toast.makeText(MainActivity.this, "permission granted", Toast.LENGTH_SHORT).show(); wifiManager.startScan(); >else < Toast.makeText(MainActivity.this, "permission not granted", Toast.LENGTH_SHORT).show(); return; >break; > > >

Step 4 − Add the following code to src/WifiReceiver

package com.example.myapplication; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; class WifiReceiver extends BroadcastReceiver < WifiManager wifiManager; StringBuilder sb; ListView wifiDeviceList; public WifiReceiver(WifiManager wifiManager, ListView wifiDeviceList) < this.wifiManager = wifiManager; this.wifiDeviceList = wifiDeviceList; >public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) < sb = new StringBuilder(); ListwifiList = wifiManager.getScanResults(); ArrayList deviceList = new ArrayList<>(); for (ScanResult scanResult : wifiList) < sb.append("
").append(scanResult.SSID).append(" - ").append(scanResult.capabilities); deviceList.add(scanResult.SSID + " - " + scanResult.capabilities); > Toast.makeText(context, sb, Toast.LENGTH_SHORT).show(); ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, deviceList.toArray()); wifiDeviceList.setAdapter(arrayAdapter); > > >

Step 5 − Add the following code to androidManifest.xml

Читайте также:  Лагает вай фай ростелеком

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –

Click here to download the project code

Источник

How to get a list of available WiFI networks in Android 6+?

I Want to get a List of available WIFis and I followed this question: how to get available wifi networks and display them in a list in android But there is a problem that most of the time it doesn’t return WiFi list! (When I run my application on devices below android 6 it works well.) This is my code:

 WifiManager mainWifi; WifiReceiver receiverWifi; List wifiList; StringBuilder sb = new StringBuilder(); private final Handler handler = new Handler(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new PermissionHandler().checkPermission(this, permissions, new PermissionHandler.OnPermissionResponse() < @Override public void onPermissionGranted() < mainWifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (mainWifi.isWifiEnabled() == false) < // If wifi disabled then enable it Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show(); mainWifi.setWifiEnabled(true); >receiverWifi = new WifiReceiver(); registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); mainWifi.startScan(); > @Override public void onPermissionDenied(Activity activity, String[] deniedPermissions, PermissionHandler.OnPermissionResponse listener) < >>); > class WifiReceiver extends BroadcastReceiver < // This method call when number of wifi connections changed public void onReceive(Context c, Intent intent) < sb = new StringBuilder(); wifiList = mainWifi.getScanResults(); sb.append("\n Number Of Wifi connections :"+wifiList.size()+"\n\n"); for(int i = 0; i < wifiList.size(); i++)< sb.append(new Integer(i+1).toString() + ". "); sb.append((wifiList.get(i)).toString()); sb.append("\n\n"); Log.i("LOGO_WIFI", sb.toString()); >> > 
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION Manifest.permission.ACCESS_WIFI_STATE Manifest.permission.CHANGE_WIFI_STATE Manifest.permission.ACCESS_NETWORK_STATE Manifest.permission.CHANGE_NETWORK_STATE 

Источник

Оцените статью
Adblock
detector