En caso de Xamarin.Android, lo primero que debemos hacer es agregar los permisos adecuados al AndroidManifest.xml.
Seguido de ello podemos hacer lo siguiente para validar si tenemos algun tipo de conexión:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(Context.ConnectivityService);
NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
bool isOnline = (activeConnection != null) && activeConnection.IsConnected;
if (!isOnline)
Toast.MakeText(this, "Por favor, segurese de estar conectado a internet y vuelva a intentarlo.", ToastLength.Long).Show();
O lo siguiente para saber si tenemos conexión con algún host en específico.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try
{
URL myUrl = new URL("https://reachsos.com");
URLConnection connection = myUrl.OpenConnection();
connection.ConnectTimeout = 3000;
await connection.ConnectAsync();
}
catch (Exception)
{
Toast.MakeText(this, "Tenemos problemas para contactar con el servidor.", ToastLength.Long).Show();
}
Si son instrucciones recurrentes en nuestra aplicación, deberíamos encapsularlas y ponerlas en una clase llamada ConnectivityService.cs por ejemplo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Android.App;
using Android.Content;
using Android.Net;
using Java.Net;
using System;
using System.Threading.Tasks;
namespace blog.epicalsoft.com
{
public class ConnectivityService
{
public static ConnectivityService Instance = new ConnectivityService();
private ConnectivityService()
{
}
public bool IsConnected
{
get
{
ConnectivityManager connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
return (activeConnection != null) && activeConnection.IsConnected;
}
}
public async Task<bool> IsRemoteReachable(string url)
{
try
{
URL myUrl = new URL(url);
URLConnection connection = myUrl.OpenConnection();
connection.ConnectTimeout = 3000;
await connection.ConnectAsync();
return true;
}
catch (Exception)
{
return false;
}
}
}
}
Para mayor info acerca de ConnectivityManager, véase la documentación oficial: https://developer.xamarin.com/api/type/Android.Net.ConnectivityManager/
No hay comentarios.:
Publicar un comentario