问题
I'm developing Windows Phone 8 application. In this application, I have to connect to the server to get the data.
So Before connecting to the server, I want to check whether the internet connection available or not to the device. If the internet connection is available, then only I'll get the data from the server, Otherwise I'll show an error message.
Please tell me how to do this in Windows Phone 8.
回答1:
NetworkInterface.GetIsNetworkAvailable()
returns the status of the NICs.
Depending on the status you can ask if the connectivity is established by using:
ConnectionProfile
-Class of Windows Phone 8.1 which uses the enum NetworkConnectivityLevel
:
- None
- Local Access
- Internet Access
This code should do the trick.
bool isConnected = NetworkInterface.GetIsNetworkAvailable();
if (isConnected)
{
ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
NetworkConnectivityLevel connection = InternetConnectionProfile.GetNetworkConnectivityLevel();
if (connection == NetworkConnectivityLevel.None || connection == NetworkConnectivityLevel.LocalAccess)
{
isConnected = false;
}
}
if(!isConnected)
await new MessageDialog("No internet connection is avaliable. The full functionality of the app isn't avaliable.").ShowAsync();
回答2:
public static bool checkNetworkConnection()
{
var ni = NetworkInterface.NetworkInterfaceType;
bool IsConnected = false;
if ((ni == NetworkInterfaceType.Wireless80211)|| (ni == NetworkInterfaceType.MobileBroadbandCdma)|| (ni == NetworkInterfaceType.MobileBroadbandGsm))
IsConnected= true;
else if (ni == NetworkInterfaceType.None)
IsConnected= false;
return IsConnected;
}
Call this function and check whether internet connection is available or not.
回答3:
You can use NetworkInterface.GetIsNetworkAvailable()
method. It returns true if network connection is available and false if not. And don't forget to add using Microsoft.Phone.Net.NetworkInformation
or using System.Net.NetworkInformation
if you are in PCL.
回答4:
Since this question appears in first result of google search for checking internet availability, I would put the answer for windows phone 8.1 XAML also. It has a little different APIs compared to 8.
//Get the Internet connection profile
string connectionProfileInfo = string.Empty;
try {
ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (InternetConnectionProfile == null) {
NotifyUser("Not connected to Internet\n");
}
else {
connectionProfileInfo = GetConnectionProfile(InternetConnectionProfile);
NotifyUser("Internet connection profile = " +connectionProfileInfo);
}
}
catch (Exception ex) {
NotifyUser("Unexpected exception occurred: " + ex.ToString());
}
For more reading go to MSDN How to retrieve network connection...
回答5:
You can use NetworkInformation.GetInternetConnectionProfile
to get the profile that is currently in use, from this you can work out the connectivity level. More info here GetInternetConnectionProfile msdn
Example of how you might use.
private void YourMethod()
{
if (InternetConnection) {
// Your code connecting to server
}
}
public static bool InternetConnection()
{
return NetworkInformation.GetInternetConnectionProfile().GetNetworkConnectivityLevel() >= NetworkConnectivityLevel.InternetAccess;
}
回答6:
This is how I did it...
class Internet
{
static DispatcherTimer dispatcherTimer;
public static bool Available = false;
public static async void StartChecking()
{
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(IsInternetAvailable1);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10); //10 Secconds or Faster
await IsInternetAvailable(null, null);
dispatcherTimer.Start();
}
private static async void IsInternetAvailable1(object sender, EventArgs e)
{
await IsInternetAvailable(sender, e);
}
private static async Task IsInternetAvailable(object sender, EventArgs ev)
{
string url = "https://www.google.com/";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
string json = "{ \"302000001\" }"; //Post Anything
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
WebClient hc = new WebClient();
hc.DownloadStringCompleted += (s, e) =>
{
try
{
if (!string.IsNullOrEmpty(e.Result))
{
Available = true;
}
else
{
Available = false;
}
}
catch (Exception ex)
{
if (ex is TargetInvocationException)
{
Available = false;
}
}
};
hc.DownloadStringAsync(new Uri(url));
}
}
}
Since windows phone 8 does not have a way of checking internet connectivity, you need to do it by sending a POST HTTP request. You can do that by sending it to any website you want. I chose google.com. Then, check every 10 seconds or less to refresh the state of the connection.
回答7:
There can be some delay in response of web request. Therefore this method may not be fast enough for some applications. This will check the internet connection on any device. A better way is to check whether port 80, the default port for http traffic, of an always online website.
public static bool TcpSocketTest()
{
try
{
System.Net.Sockets.TcpClient client =
new System.Net.Sockets.TcpClient("www.google.com", 80);
client.Close();
return true;
}
catch (System.Exception ex)
{
return false;
}
}
来源:https://stackoverflow.com/questions/20676816/how-to-check-the-internet-connection-availability-in-windows-phone-8-application