扫描Wifi网络未返回Xamarin代码中的值

时间:2019-03-08 08:34:04

标签: c# android xamarin wifi

我们已经研究了通过以下链接实现代码:https://spin.atomicobject.com/2018/02/15/connecting-wifi-xamarin-forms/,并根据我们的设置对其进行了修改。当我们调试代码时,没有任何回报。

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

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

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

    class WifiReceiver : BroadcastReceiver
    {
        private WifiManager wifi;
        private List<string> wifiNetworks;
        private AutoResetEvent receiverARE;
        private Timer tmr;
        private const int TIMEOUT_MILLIS = 20000; // 20 seconds timeout

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

        public IEnumerable<string> Scan()
        {
            tmr = new 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();
        }
    }
}

我们还尝试了对Android清单上的所需权限启用WIFI_ACCESS_STATE,ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION,CHANGE_WIFI_STATE,但无效。

我们正在寻求帮助以指出导致该错误的原因。我们已经在oneplus安卓设备和华硕手机上进行了尝试。

1 个答案:

答案 0 :(得分:1)

弄清楚了。最好在这里发布答案,以备将来参考。

我研究了Permissions for Android Xamarin。尽管我们通过清单文件添加了权限,但这似乎还不够,因为我们还需要在应用程序要求用户显式授予权限的情况下执行运行时权限。

此外,根据WIFI scanning的Android文档,我们必须满足以下条件才能成功:

enter image description here

需要注意的一件事是,在Android 8.0和Android 8.1上,如果关闭了位置服务,则无法使用。该文档指出,仅在Android 9.0及更高版本上才需要执行此操作,但是当我在Android 8.0设备上对其进行测试时,除非打开了定位服务,否则该功能将无效。另外,我必须添加Access_WIFI_State权限,该权限在文档中也未提及,否则将引发异常。您可以省略ACCESS_FINE_LOCATION或ACCESS_COARSE_LOCATION之一,它可以正常工作。