Forum Xamarin.Android

How to get list of Wifi Networks

MarkVivancoJrMarkVivancoJr USMember ✭✭
edited August 2018 in Xamarin.Android

I am trying to get a list of Wifi Networks. I am trying to isolate the code into its own class (see below.) The Intent Filter WifiReceiver never seems to be called. Once it is working, since I don't necessarily know when the WiFiNetworks List will be completely populated, is it proper programming, in Android, to set a flag letting me know once the WifiReciever class has completed populating the List? I want to populate a Spinner with the results from this List.

using Android.Content;
using Android.Net.Wifi;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace RingerLocation.Utility
{
    public class Wifi
    {
        private Context context = null;
        private static WifiManager wifi;
        private WifiReceiver wifiReceiver;
        public static List<string> WiFiNetworks;

        public Wifi(Context ctx)
        {
            this.context = ctx;
        }

        public void GetWifiNetworks()
        {
            WiFiNetworks = new List<string>();

            // Get a handle to the Wifi
            wifi = (WifiManager)context.GetSystemService(Context.WifiService);

            // Start a scan and register the Broadcast receiver to get the list of Wifi Networks
            wifiReceiver = new WifiReceiver();
            context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
            wifi.StartScan();
        }

        class WifiReceiver : BroadcastReceiver
        {
            public override void OnReceive(Context context, Intent intent)
            {
                IList<ScanResult> scanwifinetworks = wifi.ScanResults;
                foreach(ScanResult wifinetwork in scanwifinetworks)
                {
                    WiFiNetworks.Add(wifinetwork.Ssid);
                }
            }
        }
    }
}

Posts

  • CheesebaronCheesebaron DKInsider, University mod

    Create an event in your BroadcastReceiverwith the data would probably be a good way to do this.

  • MarkVivancoJrMarkVivancoJr USMember ✭✭

    Problem is my BroadcastReceiver OnReceive isn't getting called to populate my List;

    That is what my real issue is. You see anything glarringly wrong with my code?

    I forgot to mention, in my Android.manifest file I also have


  • MarkVivancoJrMarkVivancoJr USMember ✭✭

    Hmm my code seems to have gotten chopped off on the top. Below is the entire Wifi.cs class file.

    using Android.Content;
    using Android.Net.Wifi;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace NetworkLocation.Utility
    {
    public class Wifi
    {
    private Context context = null;
    private static WifiManager wifi;
    private WifiReceiver wifiReceiver;
    public static List WiFiNetworks;

        public Wifi(Context ctx)
        {
            this.context = ctx;
        }
    
        public void GetWifiNetworks()
        {
            WiFiNetworks = new List<string>();
    
            // Get a handle to the Wifi
            wifi = (WifiManager)context.GetSystemService(Context.WifiService);
    
            // Start a scan and register the Broadcast receiver to get the list of Wifi Networks
            wifiReceiver = new WifiReceiver();
            context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
            wifi.StartScan();
        }
    
        class WifiReceiver : BroadcastReceiver
        {
            public override void OnReceive(Context context, Intent intent)
            {
                IList<ScanResult> scanwifinetworks = wifi.ScanResults;
                foreach(ScanResult wifinetwork in scanwifinetworks)
                {
                    WiFiNetworks.Add(wifinetwork.Ssid);
                }
            }
        }
    }
    

    }

  • MarkVivancoJrMarkVivancoJr USMember ✭✭

    Hmm seems the forum software is truncating the top part of my class file. Attached is my Wifi.cs class file

  • CheesebaronCheesebaron DKInsider, University mod

    It is not truncating it. You didn't tell it to display it as a code block. Mark your code and press the C button in the toolbar. Or indent each line with 4 spaces.

  • MarkVivancoJrMarkVivancoJr USMember ✭✭

    OK here is the code formatted properly.

    using Android.Content;
    using Android.Net.Wifi;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace NetworkLocation.Utility
    {
        public class Wifi
        {
            private Context context = null;
            private static WifiManager wifi;
            private WifiReceiver wifiReceiver;
            public static List<string> WiFiNetworks;
    
            public Wifi(Context ctx)
            {
                this.context = ctx;
            }
    
            public void GetWifiNetworks()
            {
                WiFiNetworks = new List<string>();
    
                // Get a handle to the Wifi
                wifi = (WifiManager)context.GetSystemService(Context.WifiService);
    
                // Start a scan and register the Broadcast receiver to get the list of Wifi Networks
                wifiReceiver = new WifiReceiver();
                context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
                wifi.StartScan();
            }
    
            class WifiReceiver : BroadcastReceiver
            {
                public override void OnReceive(Context context, Intent intent)
                {
                    IList<ScanResult> scanwifinetworks = wifi.ScanResults;
                    foreach(ScanResult wifinetwork in scanwifinetworks)
                    {
                        WiFiNetworks.Add(wifinetwork.Ssid);
                    }
                }
            }
        }
    }
    
  • MarkVivancoJrMarkVivancoJr USMember ✭✭

    Does the Android Emulator display wifi networks with the API calls? If it doesn't, that might be what my problem is.

  • SebastianSeidel.9226SebastianSeidel.9226 DEInsider, University ✭✭✭✭
    edited November 2014

    Have you tried it on a real device with different wifi-networks available? I am not sure about the emulator displaying any wifi, so it would probably the best to test on a real device.

    Also naming you class Wifi and name your WifiManager instance also Wifi isn't a good convention at all.

  • MarkVivancoJrMarkVivancoJr USMember ✭✭

    I started going down the route yesterday of trying to get the code on my Samsung S5 and am having no luck with that either. Drivers weren't getting installed. I finally got them installed and no errors are showing up on Device Manager. However, the Galaxy S5 is not showing up on the Device list as an option so I am confused there as well.

    Regarding the Wifi class name and variable, i honestly hadn't notice it. Mostly because the code was written pretty quickly and then just trying all sorts of things to try and get it to work. Thanks for pointing that out.

  • MarkVivancoJrMarkVivancoJr USMember ✭✭

    Good news. I finally got the code to load on my Galaxy and its working just fine. So it appears the emulator doesn't emulate that part of the API.

    Thanks for your help.

  • It connects to wifi. Thats fine. I want to show the list of available wifi networks in a recycler view. How could I achieve using your Wifi class. ?

  • kamalSkamalS INMember
    edited April 2016

    Hi All.
    I want to show the list of available wifi networks. How could I achieve using your Wifi class. can any one help me.
    I try your wifi class. but unfortunately i can't getting the list of available wifi networks on real device.

  • RoyDoronRoyDoron USMember ✭✭

    I Don't know how the Dude @Mark Vivanco Jr. done that..
    but here is a simple solution that works for me:

    Initialize a BackgroundWorker:

    worker = new BackgroundWorker { WorkerSupportsCancellation = true };
    worker.DoWork += Worker_FindWiFisOnNetwork;
    worker.RunWorkerAsync();
    

    Implement Worker_FindWiFisOnNetwork Function like that:

            private void Worker_FindWiFisOnNetwork(object sender, DoWorkEventArgs e)
            {
                var worker = (BackgroundWorker)sender;
                worker.DoWork -= Worker_FindWiFisOnNetwork;
    
                if (worker.CancellationPending)
                {
                    e.Cancel = true; //Cancel the BackgroungWirker Properly.                    
                }
                else
                {
                    wifi = (WifiManager)GetSystemService(Context.WifiService);
                    if (wifi.WifiState == WifiState.Enabled)
                    {
                        wifi.StartScan();
                        Thread.Sleep(5000);
                        wifi.ScanResults.CopyTo(scanned,0);
                    }
                }
            }
    

    The longer the sleep(), the more WiFi network it gets within the 16km radius.
    Good Luck.

  • VladimirDjordjevicVladimirDjordjevic USMember ✭✭
    edited August 2018

    Hi guys,

    I have almost the same code as Mark and it works fine within mainactivity on my S7 (android 6).
    But if I put the same code within service that runs in the background IList<ScanResult> scanwifinetworks = wifi.ScanResults; in wifireceiver is empty.

    Any idea why?

    My service:

            [Service]
             class wifiservice : Service
             public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
            {
                    wifi = (WifiManager)GetSystemService(WifiService);
                    wifiReceiver = new WifiReceiver();
                    RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
                    wifi.StartScan();
    
                    return StartCommandResult.Sticky;
            }
    

    WiFiReceiver:

    internal class WifiReceiver : BroadcastReceiver
        {
            string directoryname;
            string filename;
            string wifilista;
            private WifiManager wifi;
    
            public override void OnReceive(Context context, Intent intent)
            {
                wifi = (WifiManager)context.GetSystemService(Context.WifiService);
    
                try
                {
                    IList<ScanResult> scanwifinetworks = wifi.ScanResults;
                    foreach (ScanResult wifinetwork in scanwifinetworks)
                    {
                        wifilista = wifilista + " - " + wifinetwork.Ssid + " mac:" + wifinetwork.Bssid.ToString() + " level:" +         wifinetwork.Level.ToString();
                    }
                }
                catch (Exception)
                {             
                }
            }
        }
    
  • @MarkVivancoJr said:
    OK here is the code formatted properly.

    using Android.Content;
    using Android.Net.Wifi;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace NetworkLocation.Utility
    {
        public class Wifi
        {
            private Context context = null;
            private static WifiManager wifi;
            private WifiReceiver wifiReceiver;
            public static List<string> WiFiNetworks;
    
            public Wifi(Context ctx)
            {
                this.context = ctx;
            }
    
            public void GetWifiNetworks()
            {
                WiFiNetworks = new List<string>();
    
                // Get a handle to the Wifi
                wifi = (WifiManager)context.GetSystemService(Context.WifiService);
    
                // Start a scan and register the Broadcast receiver to get the list of Wifi Networks
                wifiReceiver = new WifiReceiver();
                context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
                wifi.StartScan();
            }
    
            class WifiReceiver : BroadcastReceiver
            {
                public override void OnReceive(Context context, Intent intent)
                {
                    IList<ScanResult> scanwifinetworks = wifi.ScanResults;
                    foreach(ScanResult wifinetwork in scanwifinetworks)
                    {
                        WiFiNetworks.Add(wifinetwork.Ssid);
                    }
                }
            }
        }
    }
    

    How do you get the return of the WifiNetworks list ?
    Because the list is created in void method, so no return is possible..
    I want to print the listview in the MainPage.xaml for Xamarin in PCL.

    Can you help me please ? I'm stuck on this problem since 2 days now..

  • ClovyClovClovyClov Member ✭✭

    @PlanchetJulien same here :'(

  • waynewayne Member ✭✭

    wifiManager.ScanResults;
    it return empty list.
    why does ScanResults return empty list?

  • FArrigorriagaFArrigorriaga Member ✭✭

    @wayne said:
    wifiManager.ScanResults;
    it return empty list.
    why does ScanResults return empty list?

    It's because you need to manually activate the location permissions for your app. I can't post links right now, but a little search on google will give you more info (search for "ScanResult returns empty list"). Best regards.

  • LucasSossaiLucasSossai Member ✭✭✭

    @PlanchetJulien said:

    @MarkVivancoJr said:
    OK here is the code formatted properly.

    using Android.Content;
    using Android.Net.Wifi;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace NetworkLocation.Utility
    {
        public class Wifi
        {
            private Context context = null;
            private static WifiManager wifi;
            private WifiReceiver wifiReceiver;
            public static List<string> WiFiNetworks;
    
            public Wifi(Context ctx)
            {
                this.context = ctx;
            }
    
            public void GetWifiNetworks()
            {
                WiFiNetworks = new List<string>();
    
                // Get a handle to the Wifi
                wifi = (WifiManager)context.GetSystemService(Context.WifiService);
    
                // Start a scan and register the Broadcast receiver to get the list of Wifi Networks
                wifiReceiver = new WifiReceiver();
                context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
                wifi.StartScan();
            }
    
            class WifiReceiver : BroadcastReceiver
            {
                public override void OnReceive(Context context, Intent intent)
                {
                    IList<ScanResult> scanwifinetworks = wifi.ScanResults;
                    foreach(ScanResult wifinetwork in scanwifinetworks)
                    {
                        WiFiNetworks.Add(wifinetwork.Ssid);
                    }
                }
            }
        }
    }
    

    How do you get the return of the WifiNetworks list ?
    Because the list is created in void method, so no return is possible..
    I want to print the listview in the MainPage.xaml for Xamarin in PCL.

    Can you help me please ? I'm stuck on this problem since 2 days now..

    Did you manage to return the wifinetworks list?

  • @MarkVivancoJr said:
    Good news. I finally got the code to load on my Galaxy and its working just fine. So it appears the emulator doesn't emulate that part of the API.

    Thanks for your help.

    Hi @MarkVivancoJr I didn't get any list of available wifi near by me can you please tell about this issue.

  • how did you register your WifiReceiver?

  • yousufctecyousufctec USMember ✭✭✭

    @PlanchetJulien said:

    @MarkVivancoJr said:
    OK here is the code formatted properly.

    using Android.Content;
    using Android.Net.Wifi;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace NetworkLocation.Utility
    {
        public class Wifi
        {
            private Context context = null;
            private static WifiManager wifi;
            private WifiReceiver wifiReceiver;
            public static List<string> WiFiNetworks;
    
            public Wifi(Context ctx)
            {
                this.context = ctx;
            }
    
            public void GetWifiNetworks()
            {
                WiFiNetworks = new List<string>();
    
                // Get a handle to the Wifi
                wifi = (WifiManager)context.GetSystemService(Context.WifiService);
    
                // Start a scan and register the Broadcast receiver to get the list of Wifi Networks
                wifiReceiver = new WifiReceiver();
                context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
                wifi.StartScan();
            }
    
            class WifiReceiver : BroadcastReceiver
            {
                public override void OnReceive(Context context, Intent intent)
                {
                    IList<ScanResult> scanwifinetworks = wifi.ScanResults;
                    foreach(ScanResult wifinetwork in scanwifinetworks)
                    {
                        WiFiNetworks.Add(wifinetwork.Ssid);
                    }
                }
            }
        }
    }
    

    How do you get the return of the WifiNetworks list ?
    Because the list is created in void method, so no return is possible..
    I want to print the listview in the MainPage.xaml for Xamarin in PCL.

    Can you help me please ? I'm stuck on this problem since 2 days now..

    You can create a static variable in your class Wifi and make it public. Then create a dependency service which reads this static variable and send it back to your PCL in timely manner, or you can also use messaging center for this.

    Regards,
    Yousuf.

  • yousufctecyousufctec USMember ✭✭✭

    @VladimirDjordjevic said:
    Hi guys,

    I have almost the same code as Mark and it works fine within mainactivity on my S7 (android 6).
    But if I put the same code within service that runs in the background IList<ScanResult> scanwifinetworks = wifi.ScanResults; in wifireceiver is empty.

    Any idea why?

    My service:

            [Service]
             class wifiservice : Service
             public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
            {
                    wifi = (WifiManager)GetSystemService(WifiService);
                    wifiReceiver = new WifiReceiver();
                    RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
                    wifi.StartScan();
                
                    return StartCommandResult.Sticky;
            }
    

    WiFiReceiver:

    internal class WifiReceiver : BroadcastReceiver
        {
            string directoryname;
            string filename;
            string wifilista;
            private WifiManager wifi;
    
            public override void OnReceive(Context context, Intent intent)
            {
                wifi = (WifiManager)context.GetSystemService(Context.WifiService);
              
                try
                {
                    IList<ScanResult> scanwifinetworks = wifi.ScanResults;
                    foreach (ScanResult wifinetwork in scanwifinetworks)
                    {
                        wifilista = wifilista + " - " + wifinetwork.Ssid + " mac:" + wifinetwork.Bssid.ToString() + " level:" +       wifinetwork.Level.ToString();
                    }
                }
                catch (Exception)
                {             
                }
            }
        }
    
           
    

    You should start a Foreground service to get frequent updates, even though Android 9 and later will not allow you to scan not more than 4 times per 2 minutes gap (link).

    Regards,
    Yousuf.

  • Sivakumar017Sivakumar017 Member
    edited August 2020

    Hi all,
    I'm facing the Problem in context null value passing on WiFi class
    so that error raised in this line
    wifi = (WifiManager)context.GetSystemService(Context.WifiService);

    can you please help me using xamarin forms

        public Wifi(Context ctx)
        {
            this.context = ctx;
        }
    
        public void GetWifiNetworks()
        {
            WiFiNetworks = new List<string>();
    
            // Get a handle to the Wifi
            wifi = (WifiManager)context.GetSystemService(Context.WifiService);
    
            // Start a scan and register the Broadcast receiver to get the list of Wifi Networks
            wifiReceiver = new WifiReceiver();
            context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
            wifi.StartScan();
        }
    
Sign In or Register to comment.