Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>UPDATE:</strong> updated the codes to avoid <code>NetworkOnMainThreadException</code></p> <p>I'm currently using the following method to determine whether the device can access the internet or not:</p> <pre><code>public class NetworkConnectivityHelper { public void isDeviceConnectedToInternet(final Activity activity, final ResultCallback callback){ new Thread(new Runnable() { @Override public void run() { boolean isDeviceConnectedToInternet = false; NetworkInfo activeNetworkInfo = ((ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if(activeNetworkInfo != null &amp;&amp; activeNetworkInfo.isConnected()){ try { InetAddress.getByName("google.com").isReachable(2); isDeviceConnectedToInternet = true; } catch (UnknownHostException e){ isDeviceConnectedToInternet = false; } catch (IOException e){ isDeviceConnectedToInternet = false; } } final boolean result = isDeviceConnectedToInternet; activity.runOnUiThread(new Runnable() { @Override public void run() { callback.done(result); } }); } }).start(); } public static abstract class ResultCallback{ public abstract void done(boolean connected); } } </code></pre> <p>call this by:</p> <pre><code>@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); .... //Populate NetworkConnectivityHelper networkConnectivityHelper = new NetworkConnectivityHelper(); networkConnectivityHelper.isDeviceConnectedToInternet(activity, new NetworkConnectivityHelper.ResultCallback() { @Override public void done(boolean connected) { if (connected) { //Yey, the device is connected. //Now, do some work }else{ //The device is disconnected } } }); .... } </code></pre> <p>hope this helps!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload