How do I check connection to Internet in Android?

Hi There,

Is there a way to check whether if the app is connected to the internet or not? I’ve look around and most I found are pinging server and WWW request. I am not sure if there are a much ideal way method for me to check if it is connect to the internet or not.

Open to any suggestion please.

Regards,
Gibbie

using UnityEngine;

public class InternetChecker : MonoBehaviour
{
	private const bool allowCarrierDataNetwork = false;
	private const string pingAddress = "8.8.8.8"; // Google Public DNS server
	private const float waitingTime = 5.0f;
	public bool internetConnectBool;
	private Ping ping;
	private float pingStartTime;
	
	public void Start()
	{
		bool internetPossiblyAvailable;
		switch (Application.internetReachability)
		{
		case NetworkReachability.ReachableViaLocalAreaNetwork:
			internetPossiblyAvailable = true;
			break;
		case NetworkReachability.ReachableViaCarrierDataNetwork:
			//internetPossiblyAvailable = allowCarrierDataNetwork;
			internetPossiblyAvailable = true;
			break;
		default:
			internetPossiblyAvailable = false;
			break;
		}
		if (!internetPossiblyAvailable)
		{
			InternetIsNotAvailable();
			return;
		}
		ping = new Ping(pingAddress);
		pingStartTime = Time.time;
	}
	
	public void Update()
	{
		if (ping != null)
		{
			bool stopCheck = true;
			if (ping.isDone)
				InternetAvailable();
			else if (Time.time - pingStartTime < waitingTime)
				stopCheck = false;
			else
				InternetIsNotAvailable();
			if (stopCheck)
				ping = null;
		}
	}
	
	public void InternetIsNotAvailable()
	{
		//Debug.Log("No Internet");
		
		internetConnectBool = false;
	}
	
	public void InternetAvailable()
	{
		//Debug.Log("Internet is available;)");
		
		internetConnectBool = true;
	}    	
}

if(Application.internetReachability == NetworkReachability.NotReachable)
{
Debug.Log(“Error. Check internet connection!”);
}

hm.
you could write some java code, perhaps.

hitting a known server might be the best way.

I’ve created an Android’s library that can be used as Unity’s plugin for this purpose. If anyone’s interested it’s available under GitHub - rixment/awu-plugin: Android Wrapper for Unity
Hope it helps, cheers!

if(Application.internetReachability == NetworkReachability.NotReachable)
{
Debug.Log(“Error. Check internet connection!”);
}