1. Are you ready for the Galaxy S20? Here is everything we know so far!

Help with Wifi Scanning via app

Discussion in 'Android Development' started by diuz, Feb 23, 2021 at 6:47 AM.

  1. diuz

    diuz Lurker
    Thread Starter

    The function wifiManager.startScan() does not return any results when tested on a device instead of in the emulator. After searching around I found posts from 2 years ago stating that for API 26+ the wifiManager was changed to work differently. My question is: how to get it to work, aka to return me the list of available wifi networks to connect?

    I have a button and a listview and on create I enable the wifi. When the button is pressed I scan for wifi networks and populate the listview with their names. Upon clicking a list item a pop asking for the wifi passwords appears. Afterwards it attempts to connect via the network name and the entered password.

    Here is my current code (although I have a lot of experience in programming, I have little experience in Android Studio, so everything is crammed in one script). It works in the emulator (I get the predefined wifi network and successfully connect to it). On a device, however, it doesn't find any wifi networks despite seeing 4-5 when opening my wifi settings from the top navbar and not from the app. The three commented out lines are what I found I'm supposed to do to get the wifiManager to get scan results on API 26+ (though I probably put it in the wrong place due to my limited knowledge of Android Studio)

    Code (Java):
    1. package com.example.bla;
    2.  
    3. import android.Manifest;
    4. import android.annotation.SuppressLint;
    5. import android.content.BroadcastReceiver;
    6. import android.content.Context;
    7. import android.content.DialogInterface;
    8. import android.content.Intent;
    9. import android.content.IntentFilter;
    10. import android.content.pm.PackageManager;
    11. import android.net.wifi.ScanResult;
    12. import android.net.wifi.WifiConfiguration;
    13. import android.net.wifi.WifiManager;
    14. import android.net.wifi.WifiNetworkSuggestion;
    15. import android.os.Build;
    16. import android.os.Bundle;
    17. import android.util.Log;
    18. import android.view.View;
    19. import android.widget.AdapterView;
    20. import android.widget.ArrayAdapter;
    21. import android.widget.Button;
    22. import android.widget.EditText;
    23. import android.widget.ListView;
    24. import android.widget.Toast;
    25.  
    26. import androidx.annotation.NonNull;
    27. import androidx.appcompat.app.AlertDialog;
    28. import androidx.appcompat.app.AppCompatActivity;
    29. import androidx.core.app.ActivityCompat;
    30. import androidx.core.content.ContextCompat;
    31.  
    32. import java.util.ArrayList;
    33. import java.util.List;
    34.  
    35. public class MainActivity extends AppCompatActivity {
    36.  
    37.     private WifiManager wifiManager;
    38.     private ListView listView;
    39.     private Button buttonScan;
    40.     private int size = 0;
    41.     private List<ScanResult> results;
    42.     private ArrayList<String> arrayList = new ArrayList<String>();
    43.     private ArrayAdapter adapter;
    44.     private int REQUEST_LOCATION = 101;
    45.     private EditText input;
    46.     private AlertDialog ad;
    47.  
    48.     private int ItemNumb;
    49.  
    50.     @Override
    51.     protected void onCreate(Bundle savedInstanceState) {
    52.         super.onCreate(savedInstanceState);
    53.         setContentView(R.layout.activity_main);
    54.         buttonScan = findViewById(R.id.scanBtn);
    55.         buttonScan.setOnClickListener(new View.OnClickListener() {
    56.             @Override
    57.             public void onClick(View view) {
    58.                 scanWifi();
    59.             }
    60.         });
    61.  
    62.         listView = findViewById(R.id.wifilist);
    63.         wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    64.  
    65.         if (!wifiManager.isWifiEnabled()) {
    66.             Toast.makeText(this, "Wifi is disabled... Enabling it", Toast.LENGTH_LONG).show();
    67.             wifiManager.setWifiEnabled(true);
    68.         }
    69.  
    70.         adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
    71.         listView.setAdapter(adapter);
    72.  
    73.         AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
    74.         alertBuilder.setTitle("Connect to network?");
    75.         alertBuilder.setMessage("Please enter network password");
    76.         input = new EditText(MainActivity.this);
    77.         alertBuilder.setView(input);
    78.         alertBuilder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
    79.             @Override
    80.             public void onClick(DialogInterface dialogInterface, int i) {
    81.                 connectToNetwork("\"" + results.get(ItemNumb).SSID.toString() + "\"", input.getText().toString());
    82.             }
    83.         });
    84.         alertBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    85.             @Override
    86.             public void onClick(DialogInterface dialogInterface, int i) {
    87.                 dialogInterface.dismiss();
    88.             }
    89.         });
    90.  
    91.         ad = alertBuilder.create();
    92.  
    93.         listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    94.             @Override
    95.             public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    96.                 ItemNumb = I;
    97.                 ad.show();
    98.             }
    99.         });
    100.  
    101.         //IntentFilter intentFilter = new IntentFilter();
    102.         //intentFilter.addAction("android.net.wifi.SCAN_RESULTS");
    103.         //registerReceiver(wifiReceiver, intentFilter);
    104.     }
    105.  
    106.     private void scanWifi() {
    107.         if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    108.             requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
    109.         }
    110.         if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
    111.             requestPermissions(new String[]{Manifest.permission.ACCESS_WIFI_STATE}, REQUEST_LOCATION);
    112.         }
    113.         arrayList.clear();
    114.         registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    115.         wifiManager.startScan();
    116.         Toast.makeText(this, "Scanning Wifi...", Toast.LENGTH_SHORT).show();
    117.     }
    118.  
    119.     @Override
    120.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    121.         if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
    122.             Toast.makeText(getApplicationContext(), permissions[0] + " permission refused", Toast.LENGTH_SHORT).show();
    123.         } else {
    124.             Toast.makeText(getApplicationContext(), permissions[0] + " permission granted", Toast.LENGTH_SHORT).show();
    125.         }
    126.     }
    127.  
    128.     BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
    129.         @Override
    130.         public void onReceive(Context context, Intent intent) {
    131.             results = wifiManager.getScanResults();
    132.             unregisterReceiver(this);
    133.  
    134.             for (ScanResult scanResult : results) {
    135.                 arrayList.add(scanResult.SSID + " - " + scanResult.capabilities);
    136.                 adapter.notifyDataSetChanged();
    137.             }
    138.         }
    139.     };
    140.  
    141.     private void connectToNetwork(String networkSSID,  String networkPass)
    142.     {
    143.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
    144.         {
    145.             WifiNetworkSuggestion networkSuggestion1 =
    146.                     new WifiNetworkSuggestion.Builder()
    147.                             .setSsid(networkSSID)
    148.                             .setWpa2Passphrase(networkPass)
    149.                             .build();
    150.  
    151.             WifiNetworkSuggestion networkSuggestion2 =
    152.                     new WifiNetworkSuggestion.Builder()
    153.                             .setSsid(networkSSID)
    154.                             .setWpa3Passphrase(networkPass)
    155.                             .build();
    156.  
    157.             List<WifiNetworkSuggestion> suggestionsList = new ArrayList<>();
    158.             suggestionsList.add(networkSuggestion1);
    159.             suggestionsList.add(networkSuggestion2);
    160.  
    161.             wifiManager.addNetworkSuggestions(suggestionsList);
    162.         }
    163.         else
    164.         {
    165.             WifiConfiguration wifiConfiguration = new WifiConfiguration();
    166.             wifiConfiguration.SSID = String.format("\"%s\"", networkSSID);
    167.             wifiConfiguration.preSharedKey = String.format("\"%s\"", networkPass);
    168.             int wifiID = wifiManager.addNetwork(wifiConfiguration);
    169.             wifiManager.enableNetwork(wifiID, true);
    170.         }
    171.     }
    172. }
    I'm developing an app for the less technologically capable. For that purpose the app itself enables wifi, lists networks and lets you connect to a preferred network via the app rather than having you manually do it from the top android navbar. This is a non-negotiable product requirement, so I'm searching for solutions on how to change my code to get the wifi list successfully for API 26+ and not suggestions for alternate designs.
     



    1. Download the Forums for Android™ app!


      Download

       
Loading...

Share This Page

Loading...