library.network.maui/Network/Connectivity.cs

56 lines
1.3 KiB
C#

namespace Blahblah.Library.Network;
public partial class Connectivity
{
const string hostName = "www.baidu.com";
static NetworkStatus currentStatus;
static Action<NetworkStatus>? changedInternal;
public static NetworkStatus Status => PlatformGetStatus();
public static event Action<NetworkStatus> Changed
{
add
{
var running = changedInternal != null;
changedInternal += value;
if (!running && changedInternal != null)
{
currentStatus = Status;
StartListeners();
}
}
remove
{
var running = changedInternal != null;
changedInternal -= value;
if (running && changedInternal == null)
{
StopListeners();
}
}
}
private static partial NetworkStatus PlatformGetStatus();
private static partial void StartListeners();
private static partial void StopListeners();
static void OnConnectivityChanged()
{
var status = Status;
if (currentStatus != status)
{
currentStatus = status;
changedInternal?.Invoke(status);
}
}
}
public enum NetworkStatus
{
NotReachable,
ReachableViaCarrierDataNetwork,
ReachableViaWiFiNetwork
}