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
xamarin android,UWP 网络类型和IP地址的更多相关文章
- JAVA之旅(三十二)——JAVA网络请求,IP地址,TCP/UDP通讯协议概述,Socket,UDP传输,多线程UDP聊天应用
JAVA之旅(三十二)--JAVA网络请求,IP地址,TCP/UDP通讯协议概述,Socket,UDP传输,多线程UDP聊天应用 GUI写到一半电脑系统挂了,也就算了,最多GUI还有一个提示框和实例, ...
- VMware中安装CentOS7网络配置静态IP地址,常用配置和工具安装
VMware中安装CentOS7网络配置静态IP地址,常用配置和工具安装在阿里云开源镜像地址下载镜像Index of /centos/7.2.1511/isos/x86_64/http://mirro ...
- Java知多少(103)网络编程之IP地址和InetAddress类
Java语言的优势之一是Java程序能访问网络资源.Java提供一系列的类支持Java程序访问网络资源. TCP/IP协议和IP地址 为了进行网络通信,通信双方必须遵守通信协议.目前最广泛使用的是TC ...
- 网络基础之IP地址与子网划分
IP地址 Ipv4地址格式:点分十进制 IP地址的分类 A类 B类 C类: D类:组播 E类: 公共IP地址 私有IP地址 特殊地址 保留地址 子网掩码 什么是子网掩码 CIDR表示法 子网划分 为啥 ...
- 网络基础之IP地址和子网掩码
IP地址 IP是英文Internet Protocol的缩写,意思是"网络之间互连的协议",也就是为计算机网络相互连接进行通信而设计的协议.在因特网中,它是能使连接到网上的所有计算 ...
- linux 网络基础之IP地址
IP是英文Internet Protocol的缩写,意思是“网络之间互连的协议”,也就是为计算机网络相互连接进行通信而设计的协议. IP地址类型分为:公有地址.私有地址. 公有地址 公有地址(Publ ...
- 网络协议 2 - IP 地址和 MAC 地址
了解完网络协议,我们会发现,网络通信的五层模型里,有两个很重要的概念:IP 地址和 MAC 地址. 那么 IP 地址是怎么来的,又是怎么没的?MAC 地址与 IP 地址又有什么区别? 这回答上面问题前 ...
- 网络基础之IP地址
一.IP地址 1.IP地址就是给互联网上每一台主机 (或路由器)每一个接口分配一个在全世界范围内是唯一的32位二进制的地址标识符.现在由互联网名字和数字分配机构ICANN进行分配. 2.转换成十进制 ...
- 计算机网络-4-1-2-分类的IP地址
有关IP最重要的文档就是互联网的正式标准RFC 791 IP地址及其表示方法 整个互联网就是一个单一,抽象的网络,IP地址就是给互联网上的每一台主机(或者路由器)的每一个接口分配一个在全世界范围内都是 ...
随机推荐
- 故障重现, JAVA进程内存不够时突然挂掉模拟
背景,服务器上的一个JAVA服务进程突然挂掉,查看产生了崩溃日志,如下: # Set larger code cache with -XX:ReservedCodeCacheSize= # This ...
- mysql每秒最多能插入多少条数据 ? 死磕性能压测
前段时间搞优化,最后瓶颈发现都在数据库单点上. 问DBA,给我的写入答案是在1W(机械硬盘)左右. 联想起前几天infoQ上一篇文章说他们最好的硬件写入速度在2W后也无法提高(SSD硬盘) 但这东西感 ...
- MIP开发常见问题解答
校验相关 1. MIP 页面的 <a>链接校验报错,MIP 是强制 target="_blank" 吗? 如果想直接跳转MIP页,可以用mip-link 组件:MIP ...
- javascript的api设计原则
前言 本篇博文来自一次公司内部的前端分享,从多个方面讨论了在设计接口时遵循的原则,总共包含了七个大块.系卤煮自己总结的一些经验和教训.本篇博文同时也参考了其他一些文章,相关地址会在后面贴出来.很难做到 ...
- 在ubuntu16.10 PHP测试连接MySQL中出现Call to undefined function: mysql_connect()
1.问题: 测试php7.0 链接mysql数据库的时候发生错误: Fatal error: Uncaught Error: Call to undefined function mysqli_con ...
- Oracle学习之路-- 案例分析实现行列转换的几种方式
注:本文使用的数据库表为oracle自带scott用户下的emp,dept等表结构. 通过一个例子来说明行列转换: 需求:查询每个部门中各个职位的总工资 按我们最原始的思路可能会这么写: ...
- 通过AngularJS实现前端与后台的数据对接(一)——预备工作篇
最近,笔者在做一个项目:使用AngularJS,从而实现前端与后台的数据对接.笔者这是第一次做前端与后台的数据对接的工作,因此遇到了许多问题.笔者在这些问题中,总结了一些如何实现前端与后台的数据对接的 ...
- JDBC MySQL 多表关联查询查询
public static void main(String[] args) throws Exception{ Class.forName("com.mysql.jdbc.Driver&q ...
- Linux基础介绍【第四篇】
Linux文件和目录的属性及权限 命令: [root@oldboy ~]# ls -lhi total 40K 24973 -rw-------. 1 root root 1.1K Dec 10 16 ...
- Quartz
Quartz是一个开源的作业调度框架,它完全由Java写成,并设计用于J2SE和J2EE应用中.它提供了巨大的灵 活性而不牺牲简单性.你能够用它来为执行一个作业而创建简单的或复杂的调度. eg: ja ...