Check Whether Internet Connection is available or not?

前端 未结 3 1547
北恋
北恋 2021-02-06 10:30

I am working on online app. [Problem] when internet is down or not available it gives me error [Force close], I tried to handle using broadCast Receiver but not meet exact solut

3条回答
  •  时光取名叫无心
    2021-02-06 11:03

    Just use this function to check whether the Internet connection is available or not:

    /**
       * Checks if the device has Internet connection.
       * 
       * @return true if the phone is connected to the Internet.
       */
        public static boolean checkNetworkConnection(Context context)
        {
            final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            
            final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            
            if(wifi.isAvailable()||mobile.isAvailable())
                return true;
            else
                return false;
        }
    

    Note:

    Don't forget to add permission inside the AndroidManifest.xml file:

提交回复
热议问题