xamarin android,UWP 网络类型和IP地址

时间:2023-03-09 03:55:54
xamarin android,UWP 网络类型和IP地址

App开发经常要判断网络连通情况,并判断网络类型,获取网络IP。xamarin中可以使用Dependencies提供各平台下的方法,现把各平台代码记录如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using Test.Droid.Dependencies;
using Android.Net;
using Test.Dependencies;
using Java.Net;
using Java.Util;
using Android.Telephony;
using Android.Net.Wifi;
using Org.Apache.Http.Conn.Util; [assembly: Dependency(typeof(NetworkStatusAndroid))]
namespace Test.Droid.Dependencies
{
public class NetworkStatusAndroid : INetworkStatus
{
public bool HasNetwork()
{ //Test(); ConnectivityManager cwjManager = (ConnectivityManager)Android.App.Application.Context.GetSystemService(Context.ConnectivityService);
bool hasNetwork = true;
if (cwjManager.ActiveNetworkInfo != null)
{
hasNetwork = cwjManager.ActiveNetworkInfo.IsAvailable;
}
else
{
hasNetwork = false;
} return hasNetwork;
}
public string GetNetType()
{
return getCurrentNetType(Android.App.Application.Context);
} /// <summary>
/// 获取网络类型
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string getCurrentNetType(Context context)
{
String type = "";
ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
NetworkInfo info = cm.ActiveNetworkInfo;
if (info == null)
{
type = "null";
}
else if (info.Type == ConnectivityType.Wifi)
{
type = "wifi";
}
else if (info.Type == ConnectivityType.Mobile)
{
int subType = (int)info.Subtype;
if (subType == (int)NetworkType.Cdma || subType == (int)NetworkType.Gprs
|| subType == (int)NetworkType.Edge)
{
type = "2g";
}
else if (subType == (int)NetworkType.Umts || subType == (int)NetworkType.Hsdpa
|| subType == (int)NetworkType.EvdoA || subType == (int)NetworkType.Evdo0
|| subType == (int)NetworkType.EvdoB)
{
type = "3g";
}
else if (subType == (int)NetworkType.Lte)
{// LTE是3g到4g的过渡,是3.9G的全球标准
type = "4g";
}
}
return type;
} /// <summary>获取手机wifi
/// </summary>
/// <returns></returns>
public string GetWifiIP()
{
string IP = String.Empty;
Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)Forms.Context.GetSystemService(Context.WifiService);
if (wifi.IsWifiEnabled)
{
Android.Net.Wifi.WifiInfo wifiInfo = wifi.ConnectionInfo;
IP = Mixin.Common.StringFormat.intToIp(wifiInfo.IpAddress);
}
return IP;
} /// <summary>
/// 获取手机IP地址
/// </summary>
/// <returns></returns>
public string Test()
{
IEnumeration ie = NetworkInterface.NetworkInterfaces;
while (ie.HasMoreElements)
{
NetworkInterface intf = ie.NextElement() as NetworkInterface;
IEnumeration enumIpAddr = intf.InetAddresses;
while (enumIpAddr.HasMoreElements)
{ InetAddress inetAddress = enumIpAddr.NextElement() as InetAddress; if (!inetAddress.IsLoopbackAddress && (inetAddress as Inet4Address) != null && inetAddress.HostAddress.ToString() != "127.0.0.1")
{
return inetAddress.HostAddress.ToString();
}
}
}
return null;
}
}
}

Android

 using Test.Dependencies;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking.Connectivity;
using Xamarin.Forms; [assembly: Dependency(typeof(Test.UWP.Dependencies.NetworkStatus))]
namespace Test.UWP.Dependencies
{
public class NetworkStatus : INetworkStatus
{
static string None = "None";
static string Unknown = "Unknown";
static string IIG = "2G";
static string IIIG = "3G";
static string IVG = "4G";
static string Wifi = "wifi";
static string Lan = "Lan";
/// <summary>当前应用是否联网
/// </summary>
/// <returns></returns>
public bool HasNetwork()
{
bool isConnected = false; string InternetType = null;
ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();
if (profile == null)
{
InternetType = NetworkStatus.None;
}
else
{
NetworkConnectivityLevel cl = profile.GetNetworkConnectivityLevel();
isConnected = (cl != NetworkConnectivityLevel.None);
}
return isConnected;
}
/// <summary>
/// </summary>
/// <returns></returns>
public string GetWifiIP()
{
var icp = NetworkInformation.GetInternetConnectionProfile(); if (icp?.NetworkAdapter == null) return null;
var hostname =
NetworkInformation.GetHostNames()
.SingleOrDefault(
hn =>
hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId
== icp.NetworkAdapter.NetworkAdapterId); // the ip address
return hostname?.CanonicalName;
//return null;
}
/// <summary>
/// 获取UWP连接类型
/// </summary>
/// <returns></returns>
public string GetNetType()
{
bool isConnected = false; string InternetType = null;
ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();
if (profile == null)
{
InternetType = NetworkStatus.None;
}
else
{
NetworkConnectivityLevel cl = profile.GetNetworkConnectivityLevel();
isConnected = (cl != NetworkConnectivityLevel.None);
}
if (!isConnected)
{
return NetworkStatus.None;
}
if (profile.IsWwanConnectionProfile)
{
if (profile.WwanConnectionProfileDetails == null)
{
InternetType = NetworkStatus.Unknown;
}
WwanDataClass connectionClass = profile.WwanConnectionProfileDetails.GetCurrentDataClass();
switch (connectionClass)
{
//2G
case WwanDataClass.Edge:
case WwanDataClass.Gprs:
InternetType = NetworkStatus.IIG;
break;
//3G
case WwanDataClass.Cdma1xEvdo:
case WwanDataClass.Cdma1xEvdoRevA:
case WwanDataClass.Cdma1xEvdoRevB:
case WwanDataClass.Cdma1xEvdv:
case WwanDataClass.Cdma1xRtt:
case WwanDataClass.Cdma3xRtt:
case WwanDataClass.CdmaUmb:
case WwanDataClass.Umts:
case WwanDataClass.Hsdpa:
case WwanDataClass.Hsupa:
InternetType = NetworkStatus.IIIG;
break;
//4G
case WwanDataClass.LteAdvanced:
InternetType = NetworkStatus.IVG;
break;
//无网
case WwanDataClass.None:
InternetType = NetworkStatus.Unknown;
break;
case WwanDataClass.Custom:
default:
InternetType = NetworkStatus.Unknown;
break;
}
}
else if (profile.IsWlanConnectionProfile)
{
InternetType = NetworkStatus.Wifi;
}
else
{
///不是Wifi也不是蜂窝数据判断为Lan
InternetType = NetworkStatus.Lan;
}
return InternetType;
}
}
}

UWP

IOS的方法还没写全后面不上,先写一部分

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using Foundation;
using UIKit;
using Test.iOS.Dependencies;
using Xamarin.Forms;
using Test.Dependencies;
using SystemConfiguration;
using System.Net;
using CoreFoundation;
using ObjCRuntime; [assembly: Dependency(typeof(NetworkStatusIOS))]
namespace Test.iOS.Dependencies
{
public class NetworkStatusIOS : INetworkStatus
{ public bool HasNetwork()
{
//创建零地址,0.0.0.0的地址表示查询本机的网络连接状态
System.Net.IPAddress zeroAddress = System.Net.IPAddress.Parse("0.0.0.0");
bool hasNetWork = false;
NetworkReachability defaultRouteReachability = new NetworkReachability(null, zeroAddress);
NetworkReachabilityFlags flags;
//获得连接的标志
bool didRetrieveFlags = defaultRouteReachability.TryGetFlags(out flags);
if (!didRetrieveFlags)
{
hasNetWork = false;
}
//根据获得的连接标志进行判断
bool isReachable = (flags & NetworkReachabilityFlags.Reachable) == NetworkReachabilityFlags.Reachable;
bool needsConnection = (flags & NetworkReachabilityFlags.ConnectionRequired) == NetworkReachabilityFlags.ConnectionRequired; hasNetWork = (isReachable && !needsConnection); return hasNetWork;
} public string GetWifiIP()
{
//SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress); //创建测试连接的引用:
System.Net.IPAddress zeroAddress = System.Net.IPAddress.Parse("0.0.0.0");
NetworkReachabilityFlags flags = NetworkReachabilityFlags.IsLocalAddress;
IsAdHocWiFiNetworkAvailable(out flags);
//NetworkReachability defaultRouteReachability = new NetworkReachability(null, zeroAddress);
//defaultRouteReachability.TryGetFlags return "";
}
public string GetNetType()
{
string strNetworkType = ""; //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态
System.Net.IPAddress zeroAddress = System.Net.IPAddress.Parse("0.0.0.0");
bool hasNetWork = false;
NetworkReachability defaultRouteReachability = new NetworkReachability(null, zeroAddress);
NetworkReachabilityFlags flags;
//获得连接的标志
bool didRetrieveFlags = defaultRouteReachability.TryGetFlags(out flags);
if (!didRetrieveFlags)
{
hasNetWork = false;
} if ((flags & NetworkReachabilityFlags.ConnectionRequired) == )
{
strNetworkType = "WIFI";
}
if (
((flags & NetworkReachabilityFlags.ConnectionOnDemand) != ) ||
(flags & NetworkReachabilityFlags.ConnectionOnTraffic) !=
)
{
if ((flags & NetworkReachabilityFlags.InterventionRequired) == )
{
strNetworkType = "WIFI";
}
} if ((flags & NetworkReachabilityFlags.IsWWAN)==NetworkReachabilityFlags.IsWWAN)
{
if ((float)PlatformName.iOS > )
{
CoreTelephony.CTTelephonyNetworkInfo info = new CoreTelephony.CTTelephonyNetworkInfo();
string currentRadioAccessTechnology = info.CurrentRadioAccessTechnology;
if (!string.IsNullOrEmpty(currentRadioAccessTechnology))
{
if (currentRadioAccessTechnology == "CTRadioAccessTechnologyLTE")
{
strNetworkType = "4G";
}
else if (currentRadioAccessTechnology == "CTRadioAccessTechnologyEdge" ||
currentRadioAccessTechnology == "CTRadioAccessTechnologyGPRS"
)
{
strNetworkType = "2G";
}
else
{
strNetworkType = "3G";
}
}
}
else
{
if ((flags & NetworkReachabilityFlags.Reachable)== NetworkReachabilityFlags.Reachable)
{
if ((flags & NetworkReachabilityFlags.TransientConnection) == NetworkReachabilityFlags.TransientConnection)
{
if ((flags & NetworkReachabilityFlags.ConnectionRequired) == NetworkReachabilityFlags.ConnectionRequired)
{
strNetworkType = "2G";
}
else
{
strNetworkType = "3G";
}
}
}
}
} return strNetworkType;
} #region 方式一
public bool IsConnected { get; set; }
public void CheckNetworkConnection()
{
InternetConnectionStatus();
} private void UpdateNetworkStatus()
{
if (InternetConnectionStatus())
{
IsConnected = true;
}
else if (LocalWifiConnectionStatus())
{
IsConnected = true;
}
else
{
IsConnected = false;
}
} private event EventHandler ReachabilityChanged;
private void OnChange(NetworkReachabilityFlags flags)
{
var h = ReachabilityChanged;
if (h != null)
h(null, EventArgs.Empty);
} private NetworkReachability defaultRouteReachability;
private bool IsNetworkAvailable(out NetworkReachabilityFlags flags)
{
if (defaultRouteReachability == null)
{
defaultRouteReachability = new NetworkReachability(new IPAddress());
//defaultRouteReachability.SetCallback(OnChange);
defaultRouteReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
}
if (!defaultRouteReachability.TryGetFlags(out flags))
return false;
return IsReachableWithoutRequiringConnection(flags);
} private NetworkReachability adHocWiFiNetworkReachability;
private bool IsAdHocWiFiNetworkAvailable(out NetworkReachabilityFlags flags)
{
if (adHocWiFiNetworkReachability == null)
{
adHocWiFiNetworkReachability = new NetworkReachability(new IPAddress(new byte[] { , , , }));
//adHocWiFiNetworkReachability.SetCallback(OnChange);
adHocWiFiNetworkReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
} if (!adHocWiFiNetworkReachability.TryGetFlags(out flags))
return false; return IsReachableWithoutRequiringConnection(flags);
} public static bool IsReachableWithoutRequiringConnection(NetworkReachabilityFlags flags)
{
// Is it reachable with the current network configuration?
bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != ; // Do we need a connection to reach it?
bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == ; // Since the network stack will automatically try to get the WAN up,
// probe that
if ((flags & NetworkReachabilityFlags.IsWWAN) != )
noConnectionRequired = true; return isReachable && noConnectionRequired;
} private bool InternetConnectionStatus()
{
NetworkReachabilityFlags flags;
bool defaultNetworkAvailable = IsNetworkAvailable(out flags);
if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != ))
{
return false;
}
else if ((flags & NetworkReachabilityFlags.IsWWAN) != )
{
return true;
}
else if (flags == )
{
return false;
} return true;
} private bool LocalWifiConnectionStatus()
{
NetworkReachabilityFlags flags;
if (IsAdHocWiFiNetworkAvailable(out flags))
{
if ((flags & NetworkReachabilityFlags.IsDirect) != )
return true;
}
return false;
} #endregion #region 方式二 #endregion
}
}

IOS