如何使用 xamarin android 应用程序获取 wifi 列表

Posted

技术标签:

【中文标题】如何使用 xamarin android 应用程序获取 wifi 列表【英文标题】:how to get list of wifi with xamarian android app 【发布时间】:2021-12-17 19:54:38 【问题描述】:

我创建了一个移动应用程序,它可以获取 wifi 列表并插入数据库。这是我的代码:

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;
        
    

还有另一个最重要的类:

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();
            
        
    

我是 Xamarian 的新手,这项任务对我来说很重要。

我无法使用它获取列表.. Btn1get_Clicked 发生错误,该对象引用对象的实例。请帮帮我.....

【问题讨论】:

DependencyService.Get&lt;IWifi&gt;()的结果是否为空? 是的,你明白了 如何注册这个IWifi服务? 我没有得到你 docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/… 【参考方案1】:

如果要在Android平台上获取Xamarin.From的wifi列表,需要使用DependencyService在各个平台上实现该功能。

在 Xamarin.Forms 中:

    public interface IGetWifiList

    ArrayList getWifiList();

Android平台实现:

[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;

    


在 Xamarin.Forms 中的用法:

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

别忘了添加权限:

permission.ACCESS_COARSE_LOCATION

【讨论】:

尝试但仍然对象引用一个............发生在 DependencyService.Get().getWifiList(); 你在你的android实现中是否在命名空间之前添加了依赖关系? 你的意思是说[汇编:依赖(typeof(GetWifiList))] 是的,我就是这个意思。 非常感谢......它的工作就像魅力

以上是关于如何使用 xamarin android 应用程序获取 wifi 列表的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Dotfuscator 混淆 Xamarin.Android 应用程序的公共成员?

如何在 Xamarin Android 中使用 FontAwesome 图标

如何使用Xamarin在Visual Studio中创建Android应用

如何:使用 Parse 在 Xamarin.Android 应用程序上进行 Facebook 单点登录 (SSO)?

如何从 C++ 为 Xamarin.Android 创建 C# DLL

如何使用c#为android采取xamarin密码文本框