首页 > 代码库 > xamarin android,UWP 网络类型和IP地址

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

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

技术分享
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 
  6 using Android.App;
  7 using Android.Content;
  8 using Android.OS;
  9 using Android.Runtime;
 10 using Android.Views;
 11 using Android.Widget;
 12 using Xamarin.Forms;
 13 using Test.Droid.Dependencies;
 14 using Android.Net;
 15 using Test.Dependencies;
 16 using Java.Net;
 17 using Java.Util;
 18 using Android.Telephony;
 19 using Android.Net.Wifi;
 20 using Org.Apache.Http.Conn.Util;
 21 
 22 [assembly: Dependency(typeof(NetworkStatusAndroid))]
 23 namespace Test.Droid.Dependencies
 24 {
 25     public class NetworkStatusAndroid : INetworkStatus
 26     {
 27         public bool HasNetwork()
 28         {
 29 
 30             //Test();
 31 
 32             ConnectivityManager cwjManager = (ConnectivityManager)Android.App.Application.Context.GetSystemService(Context.ConnectivityService);
 33             bool hasNetwork = true;
 34             if (cwjManager.ActiveNetworkInfo != null)
 35             {
 36                 hasNetwork = cwjManager.ActiveNetworkInfo.IsAvailable;
 37             }
 38             else
 39             {
 40                 hasNetwork = false;
 41             }
 42 
 43             return hasNetwork;
 44         }
 45         public string GetNetType()
 46         {
 47             return getCurrentNetType(Android.App.Application.Context);
 48         }
 49 
 50         /// <summary>
 51         /// 获取网络类型
 52         /// </summary>
 53         /// <param name="context"></param>
 54         /// <returns></returns>
 55         public static string getCurrentNetType(Context context)
 56         {
 57             String type = "";
 58             ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
 59             NetworkInfo info = cm.ActiveNetworkInfo;
 60             if (info == null)
 61             {
 62                 type = "null";
 63             }
 64             else if (info.Type == ConnectivityType.Wifi)
 65             {
 66                 type = "wifi";
 67             }
 68             else if (info.Type == ConnectivityType.Mobile)
 69             {
 70                 int subType = (int)info.Subtype;
 71                 if (subType == (int)NetworkType.Cdma || subType == (int)NetworkType.Gprs
 72                 || subType == (int)NetworkType.Edge)
 73                 {
 74                     type = "2g";
 75                 }
 76                 else if (subType == (int)NetworkType.Umts || subType == (int)NetworkType.Hsdpa
 77               || subType == (int)NetworkType.EvdoA || subType == (int)NetworkType.Evdo0
 78               || subType == (int)NetworkType.EvdoB)
 79                 {
 80                     type = "3g";
 81                 }
 82                 else if (subType == (int)NetworkType.Lte)
 83                 {// LTE是3g到4g的过渡,是3.9G的全球标准
 84                     type = "4g";
 85                 }
 86             }
 87             return type;
 88         }
 89 
 90         /// <summary>获取手机wifi
 91         /// </summary>
 92         /// <returns></returns>
 93         public string GetWifiIP()
 94         {
 95             string IP = String.Empty;
 96             Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)Forms.Context.GetSystemService(Context.WifiService);
 97             if (wifi.IsWifiEnabled)
 98             {
 99                 Android.Net.Wifi.WifiInfo wifiInfo = wifi.ConnectionInfo;
100                 IP = Mixin.Common.StringFormat.intToIp(wifiInfo.IpAddress);
101             }
102             return IP;
103         }
104 
105         /// <summary>
106         /// 获取手机IP地址
107         /// </summary>
108         /// <returns></returns>
109         public string Test()
110         {
111             IEnumeration ie = NetworkInterface.NetworkInterfaces;
112             while (ie.HasMoreElements)
113             {
114                 NetworkInterface intf = ie.NextElement() as NetworkInterface;
115                 IEnumeration enumIpAddr = intf.InetAddresses;
116                 while (enumIpAddr.HasMoreElements)
117                 {
118 
119                     InetAddress inetAddress = enumIpAddr.NextElement() as InetAddress;
120 
121                     if (!inetAddress.IsLoopbackAddress && (inetAddress as Inet4Address) != null && inetAddress.HostAddress.ToString() != "127.0.0.1")
122                     {
123                         return inetAddress.HostAddress.ToString();
124                     }
125                 }
126             }
127             return null;
128         }
129     }
130 }
Android
技术分享
  1 using Test.Dependencies;
  2 using System;
  3 using System.Collections.Generic;
  4 using System.Linq;
  5 using System.Text;
  6 using System.Threading.Tasks;
  7 using Windows.Networking.Connectivity;
  8 using Xamarin.Forms;
  9 
 10 [assembly: Dependency(typeof(Test.UWP.Dependencies.NetworkStatus))]
 11 namespace Test.UWP.Dependencies
 12 {
 13     public class NetworkStatus : INetworkStatus
 14     {
 15         static string None = "None";
 16         static string Unknown = "Unknown";
 17         static string IIG = "2G";
 18         static string IIIG = "3G";
 19         static string IVG = "4G";
 20         static string Wifi = "wifi";
 21         static string Lan = "Lan";
 22         /// <summary>当前应用是否联网
 23         /// </summary>
 24         /// <returns></returns>
 25         public bool HasNetwork()
 26         {
 27             bool isConnected = false;
 28 
 29             string InternetType = null;
 30             ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();
 31             if (profile == null)
 32             {
 33                 InternetType = NetworkStatus.None;
 34             }
 35             else
 36             {
 37                 NetworkConnectivityLevel cl = profile.GetNetworkConnectivityLevel();
 38                 isConnected = (cl != NetworkConnectivityLevel.None);
 39             }
 40             return isConnected;
 41         }
 42         /// <summary>
 43         /// </summary>
 44         /// <returns></returns>
 45         public string GetWifiIP()
 46         {
 47             var icp = NetworkInformation.GetInternetConnectionProfile();
 48 
 49             if (icp?.NetworkAdapter == null) return null;
 50             var hostname =
 51                 NetworkInformation.GetHostNames()
 52                     .SingleOrDefault(
 53                         hn =>
 54                             hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId
 55                             == icp.NetworkAdapter.NetworkAdapterId);
 56 
 57             // the ip address  
 58             return hostname?.CanonicalName;
 59             //return null;
 60         }
 61         /// <summary>
 62         /// 获取UWP连接类型
 63         /// </summary>
 64         /// <returns></returns>
 65         public string GetNetType()
 66         {
 67             bool isConnected = false;
 68 
 69             string InternetType = null;
 70             ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();
 71             if (profile == null)
 72             {
 73                 InternetType = NetworkStatus.None;
 74             }
 75             else
 76             {
 77                 NetworkConnectivityLevel cl = profile.GetNetworkConnectivityLevel();
 78                 isConnected = (cl != NetworkConnectivityLevel.None);
 79             }
 80             if (!isConnected)
 81             {
 82                 return NetworkStatus.None;
 83             }
 84             if (profile.IsWwanConnectionProfile)
 85             {
 86                 if (profile.WwanConnectionProfileDetails == null)
 87                 {
 88                     InternetType = NetworkStatus.Unknown;
 89                 }
 90                 WwanDataClass connectionClass = profile.WwanConnectionProfileDetails.GetCurrentDataClass();
 91                 switch (connectionClass)
 92                 {
 93                     //2G
 94                     case WwanDataClass.Edge:
 95                     case WwanDataClass.Gprs:
 96                         InternetType = NetworkStatus.IIG;
 97                         break;
 98                     //3G
 99                     case WwanDataClass.Cdma1xEvdo:
100                     case WwanDataClass.Cdma1xEvdoRevA:
101                     case WwanDataClass.Cdma1xEvdoRevB:
102                     case WwanDataClass.Cdma1xEvdv:
103                     case WwanDataClass.Cdma1xRtt:
104                     case WwanDataClass.Cdma3xRtt:
105                     case WwanDataClass.CdmaUmb:
106                     case WwanDataClass.Umts:
107                     case WwanDataClass.Hsdpa:
108                     case WwanDataClass.Hsupa:
109                         InternetType = NetworkStatus.IIIG;
110                         break;
111                     //4G
112                     case WwanDataClass.LteAdvanced:
113                         InternetType = NetworkStatus.IVG;
114                         break;
115                     //无网
116                     case WwanDataClass.None:
117                         InternetType = NetworkStatus.Unknown;
118                         break;
119                     case WwanDataClass.Custom:
120                     default:
121                         InternetType = NetworkStatus.Unknown;
122                         break;
123                 }
124             }
125             else if (profile.IsWlanConnectionProfile)
126             {
127                 InternetType = NetworkStatus.Wifi;
128             }
129             else
130             {
131                 ///不是Wifi也不是蜂窝数据判断为Lan
132                 InternetType = NetworkStatus.Lan;
133             }
134             return InternetType;
135         }
136     }
137 }
UWP

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

技术分享
 1         public bool HasNetwork()
 2         {
 3             //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态 
 4             System.Net.IPAddress zeroAddress = System.Net.IPAddress.Parse("0.0.0.0");
 5             bool hasNetWork = false;
 6             NetworkReachability defaultRouteReachability = new NetworkReachability(null, zeroAddress);
 7             NetworkReachabilityFlags flags;
 8             //获得连接的标志 
 9             bool didRetrieveFlags = defaultRouteReachability.TryGetFlags(out flags);
10             if (!didRetrieveFlags)
11             {
12                 hasNetWork = false;
13             }
14             //根据获得的连接标志进行判断
15             bool isReachable = (flags & NetworkReachabilityFlags.Reachable) == NetworkReachabilityFlags.Reachable;
16             bool needsConnection = (flags & NetworkReachabilityFlags.ConnectionRequired) == NetworkReachabilityFlags.ConnectionRequired;
17 
18             hasNetWork = (isReachable && !needsConnection);
19 
20             return hasNetWork;
21         }
IOS

 

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