Android java wifi scan

Android scan wifi networks programmatically

This example demonstrate about How to scan wifi networks programmatically.

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

Читайте также:  Asrock mini itx wifi

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 can I get Android Wifi Scan Results into a list?

I know how to get a of Android Wifi Scans but I can not figure out the best way to make a list adapter out of them. I would like to just bind SSID and BSSID from a of scans to text1 and text2. Samples of what I have been doing

wifi.startScan(); // get list of the results in object format ( like an array ) List results = wifi.getScanResults();` // loop that goes through list for (ScanResult result : results) < Toast.makeText(this, result.SSID + " " + result.level, Toast.LENGTH_SHORT).show(); 
private void fillDataFromDb() < Cursor scanCursor = Db.fetchAllScans(); startManagingCursor(scanCursor);` // Create an array to specify the fields we want to display in the list // (only TITLE) String[] from = new String[] < WifiDbAdapter.KEY_BSSID, WifiDbAdapter.KEY_SSID >; // and an array of the fields we want to bind those fields to (in this // case just text1) int[] to = new int[] < R.id.text1, R.id.text2 >; // Now create a simple cursor adapter and set it to display SimpleCursorAdapter scansdb = new SimpleCursorAdapter(this, R.layout.scan_row, scanCursor, from, to); setListAdapter(scansdb); > 

I'd like to see some code you have too. Are you getting the results like this?: List results = wifi.getScanResults();

I'm already doing this to just get toast messages: wifi.startScan(); // get list of the results in object format ( like an array ) List results = wifi.getScanResults(); // loop that goes through list for (ScanResult result : results) < Toast.makeText(this, result.SSID + " " + result.level, Toast.LENGTH_SHORT).show();

Читайте также:  Подключить вай фай автомобильный

@eternalmatt Yes that is exactly how I am getting results and it works great, just don't know how to bind that to a listview

5 Answers 5

public class WiFiDemo extends Activity implements OnClickListener < WifiManager wifi; ListView lv; TextView textStatus; Button buttonScan; int size = 0; Listresults; String ITEM_KEY = "key"; ArrayList> arraylist = new ArrayList>(); SimpleAdapter adapter; /* Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); textStatus = (TextView) findViewById(R.id.textStatus); buttonScan = (Button) findViewById(R.id.buttonScan); buttonScan.setOnClickListener(this); lv = (ListView)findViewById(R.id.list); wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled() == false) < Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show(); wifi.setWifiEnabled(true); >this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] < ITEM_KEY >, new int[] < R.id.list_value >); lv.setAdapter(this.adapter); registerReceiver(new BroadcastReceiver() < @Override public void onReceive(Context c, Intent intent) < results = wifi.getScanResults(); size = results.size(); >>, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); > public void onClick(View view) < arraylist.clear(); wifi.startScan(); Toast.makeText(this, "Scanning. " + size, Toast.LENGTH_SHORT).show(); try < size = size - 1; while (size >= 0) < HashMapitem = new HashMap(); item.put(ITEM_KEY, results.get(size).SSID + " " + results.get(size).capabilities); arraylist.add(item); size--; adapter.notifyDataSetChanged(); > > catch (Exception e) < >> > 

WiFiDemo.xml :

For ListView- row.xml

Add these permission in AndroidManifest.xml

Thank you for this code. How could I scan the Wifi continuously inside the list and return the RSS value?

In addition for the accepted answer you'll need the following permissions into your AndroidManifest to get it working:

Wrap an ArrayAdapter around your List . Override getView() to populate your rows with the ScanResult data. Here is a free excerpt from one of my books that covers how to create custom ArrayAdapters like this.

Find a complete working example below:

The code by @Android is very good but has few issues, namely:

  1. Populating to ListView code needs to be moved to onReceive of BroadCastReceiver where only the result will be available. In the case result is obtained at 2nd attempt.
  2. BroadCastReceiver needs to be unregistered after the results are obtained.
  3. size = size -1 seems unnecessary.
Читайте также:  Микроволновая печь глушит wifi

Find below the modified code of @Android as a working example:

WifiScanner.java which is the Main Activity

package com.arjunandroid.wifiscanner; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class WifiScanner extends Activity implements View.OnClickListener < WifiManager wifi; ListView lv; Button buttonScan; int size = 0; Listresults; String ITEM_KEY = "key"; ArrayList arraylist = new ArrayList<>(); ArrayAdapter adapter; /* Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); getActionBar().setTitle("Widhwan Setup Wizard"); setContentView(R.layout.activity_wifi_scanner); buttonScan = (Button) findViewById(R.id.scan); buttonScan.setOnClickListener(this); lv = (ListView)findViewById(R.id.wifilist); wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled() == false) < Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show(); wifi.setWifiEnabled(true); >this.adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arraylist); lv.setAdapter(this.adapter); scanWifiNetworks(); > public void onClick(View view) < scanWifiNetworks(); >private void scanWifiNetworks() < arraylist.clear(); registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); wifi.startScan(); Log.d("WifScanner", "scanWifiNetworks"); Toast.makeText(this, "Scanning. ", Toast.LENGTH_SHORT).show(); >BroadcastReceiver wifi_receiver= new BroadcastReceiver() < @Override public void onReceive(Context c, Intent intent) < Log.d("WifScanner", "onReceive"); results = wifi.getScanResults(); size = results.size(); unregisterReceiver(this); try < while (size >= 0) < size--; arraylist.add(results.get(size).SSID); adapter.notifyDataSetChanged(); >> catch (Exception e) < Log.w("WifScanner", "Exception: "+e); >> >; > 

activity_wifi_scanner.xml which is the layout file for the Activity

Also as mentioned above, do not forget to add Wifi permissions in the AndroidManifest.xml

Источник

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