Check if internet connection is available or not?

I am working on an online application. [Problem], when the Internet is unavailable or unavailable, it gives me an error [Force close], I tried to use the broadcast receiver, but did not answer the exact solutions, looking for the best solution.

public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { NetworkInfo info = intent .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if (null != info) { String state = info.getState().toString(); if (state.equalsIgnoreCase("CONNECTED")) { SplashScreen.isWiFiConnected = true; Log.i("isWifiConnected", "=================TRUE"); } else { SplashScreen.isWiFiConnected = false; Log.i("isWifiConnected", "=================FALSE"); } } } } 

thanks.

+6
source share
3 answers
 static String data = null; private static HttpPost httppost; private static HttpParams httpParameters; private static int timeoutConnection = 30000; private static HttpClient httpclient = null; private static HttpResponse response = null; private static int responseCode=0; public static ConnectivityManager mConnectivityManager; public static NetworkInfo mNetworkInfo; public static boolean isNetError=false; /** Post Http data and returns final string and status on network */ public static void postHttp(String Url, Activity mActivity) { try { isNetError=false; mConnectivityManager= (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE); mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting()) { httppost = new HttpPost(Url); httpParameters = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection); httpclient = new DefaultHttpClient(httpParameters); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("text", "some Text")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); // Execute HTTP Post Request response = httpclient.execute(httppost); data = EntityUtils.toString(response.getEntity()); } else isNetError=true; } catch (Exception e) { e.printStackTrace(); isNetError=true; } if (responseCode == 200) { isNetError=false; System.out.println("final..." + data); } else isNetError=true; } 

call this method in doInBackground () asyntask and onPostExecute () check the value of isNetError and, as indicated in another answer to add permission <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 if(isNetError) //No internet else //do your stuff 
+6
source

Just use this function to check if your internet connection is available:

 /** * Checks if the device has Internet connection. * * @return <code>true</code> 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:

Remember to add permission to the AndroidManifest.xml file: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

+4
source

A valid network connection does not necessarily mean that you can access the Internet, and the OP asks for ways to check the availability of an Internet connection . In some Wi-Fi networks, it may be necessary for users to open a browser and go through some kind of authorization before allowing access to the Internet, so in this case it is not enough to check the actual WiFi connection.

A naive approach to checking raw communication without creating a GET / POST connection:

 private boolean isConnected() { try { InetAddress.getByName("google.com"); } catch (UnknownHostException e) { return false; } return true; } 

warning1 : After some testing, I must warn that the code above DOES NOT WORK, even if it appears at the beginning a couple of times.

The code tries to resolve a host name that is not already in the DNS cache, so after a successful cache search, the code will continue to return true, even if the host is unavailable, since the whole modern OS performs DNS caching.

BUT ... On Android, the InetAddress class has an additional method that is not found in the standard JavaSE - InetAddress.isReachable (int timeout) , which according to javadocs:

"Trying to achieve this InetAddress. First, this method tries to use ICMP (ICMP ECHO REQUEST), returning to the TCP connection on port 7 (Echo) of the remote host."

So a possible fix for the above code would be

 InetAddress.getByName("google.com").isReachable(5000); 

If ICMP packets are blocked, the only reliable way to check availability is to create a real connection to your host, either through URLConnection , HttpClient , Socket, or anything in between.

0
source

Source: https://habr.com/ru/post/900834/


All Articles