I am looking for a way to check whether the Wi-Fi of the phone is on or off in Dote NET MAUI. Internet connection status is not important, but I just need to check Wi-Fi status.
I used “WifiManager” and came across warnings that pointed to null values and of course the program always encountered a null value when running and simulating.
I write the tested method below:
- I created an interface called IWifiService
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WifiTest9
{
public interface IWifiService
{
bool IsWifiEnabled();
}
}
- Then I created a class specially for android in Platforms/Android
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.Content;
using Android.Net.Wifi;
using WifiTest9.Platforms.Android;
using Microsoft.Maui;
using Microsoft.Maui.Controls;
[assembly: Dependency(typeof(WifiService))]
namespace WifiTest9.Platforms.Android
{
public class WifiService : IWifiService
{
public bool IsWifiEnabled()
{
var currentActivity = Platform.CurrentActivity;
var wifiManager = (WifiManager)currentActivity.GetSystemService(Context.WifiService);
return wifiManager.IsWifiEnabled;
}
}
}
These two lines of code that I am rewriting below are the same two lines where we encounter the warning of null values.
var wifiManager = (WifiManager)currentActivity.GetSystemService(Context.WifiService);
return wifiManager.IsWifiEnabled;
- and finally I used them in MainPage.xaml.cs
private void Button_Clicked(object sender, EventArgs e)
{
CheckWiFiStatus();
}
private void CheckWiFiStatus()
{
var wifiService = DependencyService.Get<IWifiService>();
bool isWifiEnabled = wifiService.IsWifiEnabled();
if (isWifiEnabled)
{
wifiStatusLabel.Text = "Wifi is ON";
}
else
{
wifiStatusLabel.Text = "Wifi is OFF";
}
}
In addition, I found another way in the Microsoft documentation, but I don’t know how to use it, and I will put the link with the code below.
public virtual bool IsWifiEnabled { [Android.Runtime.Register("isWifiEnabled", "()Z", "GetIsWifiEnabledHandler")] get; }
Link:
WifiManager.IsWifiEnabled Property
MohammadHossein Parvaneh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.