How to check internet access on Android? InetAddress never times out

后端 未结 30 3460
猫巷女王i
猫巷女王i 2020-11-21 04:45

I got a AsyncTask that is supposed to check the network access to a host name. But the doInBackground() is never timed out. Anyone have a clue?

30条回答
  •  后悔当初
    2020-11-21 05:01

    Update 29/06/2015 If you are using Xamarin.Android and want to check for connectivity, you can use a Nuget package that would give you this functionality on multiple platforms. Good candidates are here and here. [End of Update]

    The Answers above are quite good, but they are all in Java, and almost all of them check for a connectivity. In my case, I needed to have connectivity with a specific type of connection and I am developing on Xamarin.Android. Moreover, I do not pass a reference to my activities Context in the Hardware layer, I use the Application Context. So here is my solution, in case somebody comes here with similar requirements. I have not done full testing though, will update the answer once I am done with my testing

    using Android.App;
    using Android.Content;
    using Android.Net;
    
    namespace Leopard.Mobile.Hal.Android
    {
        public class AndroidNetworkHelper
        {
            public static AndroidNetworkStatus GetWifiConnectivityStatus()
            {
                return GetConnectivityStatus(ConnectivityType.Wifi);
            }
    
            public static AndroidNetworkStatus GetMobileConnectivityStatus()
            {
                return GetConnectivityStatus(ConnectivityType.Mobile);
            }
    
            #region Implementation
    
            private static AndroidNetworkStatus GetConnectivityStatus(ConnectivityType connectivityType)
            {
                var connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
                var wifiNetworkInfo = connectivityManager.GetNetworkInfo(connectivityType);
                var result = GetNetworkStatus(wifiNetworkInfo);
                return result;
            }
    
            private static AndroidNetworkStatus GetNetworkStatus(NetworkInfo wifiNetworkInfo)
            {
                var result = AndroidNetworkStatus.Unknown;
                if (wifiNetworkInfo != null)
                {
                    if (wifiNetworkInfo.IsAvailable && wifiNetworkInfo.IsConnected)
                    {
                        result = AndroidNetworkStatus.Connected;
                    }
                    else
                    {
                        result = AndroidNetworkStatus.Disconnected;
                    }
                }
                return result;
            } 
    
            #endregion
        }
    
        public enum AndroidNetworkStatus
        {
            Connected,
            Disconnected,
            Unknown
        }
    

提交回复
热议问题