在我的應用程序中檢查Internet連接並訪問我的網站。我無法在另一個班上得到結果。通過localSettings.Values有一個解決方案,但它不是我想要的。請幫幫我。謝謝如何在不同的課程中獲得互聯網的檢查結果?
public class NetworkUtils{
public enum ConnType
{
CONN_MOBILE,
CONN_WIFI,
CONN_WAN,
CONN_NO,
CONN_MY
}
public ConnType GetConnectionGeneration()
{
string connectionProfileInfo = string.Empty;
try
{
ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (InternetConnectionProfile == null)
{
NotifyUser("Not connected to Internet\n");
return (ConnType.CONN_NO);
}
else
{
if (InternetConnectionProfile.IsWlanConnectionProfile)
{
HttpClient httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 0, 0, 300);
try
{
httpClient.GetAsync(new Uri("http://www.myexample.com")).Wait();
NotifyUser("MY SITE connected\n");
return (ConnType.CONN_MY);
}
catch (Exception ex)
{
NotifyUser("Unexpected exception occurred: " + ex.ToString());
}
return (ConnType.CONN_WIFI);
}
else if (InternetConnectionProfile.IsWwanConnectionProfile)
{
WwanDataClass connectionClass = InternetConnectionProfile.WwanConnectionProfileDetails.GetCurrentDataClass();
switch (connectionClass)
{
//2G-equivalent
case WwanDataClass.Edge:
case WwanDataClass.Gprs:
//3G-equivalent
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:
//4G-equivalent
case WwanDataClass.LteAdvanced:
return (ConnType.CONN_MOBILE);
//not connected
case WwanDataClass.None:
return (ConnType.CONN_NO);
//unknown
case WwanDataClass.Custom:
default:
HttpClient httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 0, 0, 300);
try
{
httpClient.GetAsync(new Uri("http://www.myexample.com")).Wait();
return (ConnType.CONN_MY);
}
catch (Exception ex)
{
NotifyUser("Unexpected exception occurred: " + ex.ToString());
}
return (ConnType.CONN_WAN);
}
}
return (ConnType.CONN_MOBILE);
}
}
catch (Exception ex)
{
NotifyUser("Unexpected exception occurred: " + ex.ToString());
return (ConnType.CONN_NO);
}
}
}
如果我做的事情不那麼正確。如果有好的想法,我也會很感激。我測試過,但沒有任何反應。
public sealed partial class TestPage : Page
{
public TestPage()
{
InitializeComponent();
if (NetworkUtils.ConnType.CONN_MY.ToString().Equals("CONN_MY"){
TextBlock.Text = "GOOD Connection";
} else if (NetworkUtils.ConnType.CONN_WIFI.ToString().Equals("CONN_MY"){
TextBlock.Text = "WIFI Connection";
}
...
}
}