Home > Software design >  how to get list of wifi with xamarian android app
how to get list of wifi with xamarian android app

Time:11-09

i have created one mobile app that gets list of wifi and get inserts to database. here is my code:

using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Content;
using System.Collections.Generic;
using Android.Net.Wifi;
using System.Text;
using Java.Lang;
using Xamarin.Forms;
using StringBuilder = System.Text.StringBuilder;
using Menu = Android.Views.Menu;
using Xamarin.Essentials;
using System.Threading.Tasks;

namespace WifiApp
{
    public partial class MainPage : ContentPage
    {
        //as temp list by shalin gajjar
        //IEnumerable<string> _wifiService = new List<string>() {"aaa","bbb","ccc","ddd","ffff"};

        IEnumerable<string> _wifiService ;

        public MainPage()
        {
            InitializeComponent();
            var wcurrent = Connectivity.NetworkAccess.ToString();
            //var wprofiles = Connectivity.ConnectionProfiles;

            if (wcurrent == NetworkAccess.Internet.ToString())
            {
                networkkState.Text = "Network is available..";
            }
            else
            {
                networkkState.Text = "Network is not available..";
            }


            /*if (wprofiles.ToString().Contains(ConnectionProfile.WiFi.ToString()))
            {
                networkkState.Text = wprofiles.FirstOrDefault().ToString();
            }
            else
            {
                networkkState.Text = wprofiles.FirstOrDefault().ToString();
            }*/
        }

        public interface IWifi
        {
            Task<IEnumerable<string>> GetAvailableNetworksAsync();
        }
   public async void Btn1get_Clicked(object sender, EventArgs e)
        {

            _wifiService = null;
            _wifiService = await DependencyService.Get<IWifi>().GetAvailableNetworksAsync();
            wifilist.ItemsSource = _wifiService;
        }
    }
}

and another most imp class :

using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Content;
using System.Collections.Generic;
using Android.Net.Wifi;
using System.Text;
using Java.Lang;
using Xamarin.Forms;
using StringBuilder = System.Text.StringBuilder;
using Menu = Android.Views.Menu;
using System.Timers;
using System.Threading;
using System.Threading.Tasks;

namespace WifiApp.Droid
{
    [Activity(Label = "WifiApp", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    public class Wifi : MainPage.IWifi
    {
        private Context context = null;

        public Wifi()
        {
            this.context = Android.App.Application.Context;
        }

        [Obsolete]
        public async Task<IEnumerable<string>> GetAvailableNetworksAsync()
        {
            IEnumerable<string> availableNetworks = null;

            // Get a handle to the Wifi
            var wifiMgr = (WifiManager)context.GetSystemService(Context.WifiService);
            var wifiReceiver = new WifiReceiver(wifiMgr);

            await Task.Run(() =>
            {
                // Start a scan and register the Broadcast receiver to get the list of Wifi Networks
                context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
                availableNetworks = wifiReceiver.Scan();
            });

            return availableNetworks;
        }

        [BroadcastReceiver(Enabled = true, Exported = false)]
        class WifiReceiver : BroadcastReceiver
        {
            private WifiManager wifi;
            private List<string> wifiNetworks;
            private AutoResetEvent receiverARE;
            private System.Threading.Timer tmr;
            private const int TIMEOUT_MILLIS = 20000; // 20 seconds timeout

            public WifiReceiver()
            {

            }
            public WifiReceiver(WifiManager wifi)
            {
                this.wifi = wifi;
                wifiNetworks = new List<string>();
                receiverARE = new AutoResetEvent(false);
            }

            [Obsolete]
            public IEnumerable<string> Scan()
            {
                tmr = new System.Threading.Timer(Timeout, null, TIMEOUT_MILLIS, System.Threading.Timeout.Infinite);
                wifi.StartScan();
                receiverARE.WaitOne();
                return wifiNetworks;
            }

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

                receiverARE.Set();
            }

            private void Timeout(object sender)
            {
                // NOTE release scan, which we are using now, or we throw an error?
                receiverARE.Set();
            }
        }
    }
}

i m new in Xamarian and this task is important for me.

i can't getting list with it.. there is error occurs from Btn1get_Clicked that Object reference to an instance of an object. please help me .....

CodePudding user response:

If you want to get the wifi list for Xamarin.From on Android Platform, it need to use the DependencyService to implement the function on each platform.

In Xamarin.Forms:

    public interface IGetWifiList
{
    ArrayList getWifiList();
}

Implementation on Android platform:

[assembly: Dependency(typeof(GetWifiList))]
namespace App14.Droid
{
public class GetWifiList : IGetWifiList
{
    public ArrayList getWifiList()
    {

        ArrayList myListrow = new ArrayList();


        var wifiMgr = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);

       
        var wifiList = wifiMgr.ScanResults;

        foreach (var item in wifiList)
        {
            var wifiLevel = WifiManager.CalculateSignalLevel(item.Level, 100);
            myListrow.Add(($"Wifi Name: {item.Ssid} - Single: {wifiLevel}"));

        }
        return myListrow;

    }
}
}

Usage in Xamarin.Forms:

   var LIST= DependencyService.Get<IGetWifiList>().getWifiList();

Do not forget to add the permission:

permission.ACCESS_COARSE_LOCATION
  • Related