0

I have a BroadcastReceiver that monitors the network connection, and what I'm trying to do is reload a web view when an internet connection becomes available.

However, when getActiveNetworkInfo().isConnect() returns true, and I reload the url, the web view fails saying:

web view error:(-6) The connection to the server was unsuccessful.

The method that determines the connection is viable:

public static boolean isConnectedToInternet()
{
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = false;

    if(activeNetwork != null &&
            activeNetwork.isConnected())
    {
        isConnected = true;
    }

    return isConnected;
}

Thanks in advance for the help

TMacGyver
  • 1,281
  • 3
  • 12
  • 27
  • Your code doesn't verify that your device is actually able to connect to the internet. Only that it is connected to a Network. That is not the same as having a working Internet connection. – kaderud Apr 26 '13 at 22:20
  • how do i verify that the device is able to connect to the internet? – TMacGyver Apr 26 '13 at 22:28
  • damn man, awesome code, thank you very – TMacGyver Apr 27 '13 at 01:39
  • After having read a little bit more about the `get()`-method in AsyncTask, this might not be the best way to do it, if I understand correctly the get()-method waits for the result, so if the doInBackground() method takes a long time, the UI will freeze since we put it in onCreate(). I'll do some more reading and update the answer. It might perhaps just be enough to add the `onPostExecute()` method to the AsyncTask and assign a global boolean from it. – kaderud Apr 27 '13 at 02:20
  • Don't get me wrong, the code works, I've verified it in the emulator with Internet and disabled, and on a real 4.2.2 device with WiFi, WiFi disabled, and in Airplane mode, and all checks goes instantly, so I'm not sure how that code could, if possible, "hang" during the `get()` method. – kaderud Apr 27 '13 at 18:35
  • http://developer.android.com/reference/android/os/AsyncTask.html#get() `Waits if necessary for the computation to complete, and then retrieves its result.` – kaderud Apr 27 '13 at 18:36
  • I really like ur answer, but i do like the simplicity of the other. So I added another question to see what other ppl think: http://android.stackexchange.com/questions/44524/the-better-way-of-determining-internet-connectivity (in retrospect, maybe i shoulda put it on SO) – TMacGyver Apr 27 '13 at 19:36
  • that wasnt the right spot, its now on SO: http://stackoverflow.com/questions/16256163/the-better-way-of-determining-internet-connectivity – TMacGyver Apr 27 '13 at 19:42

2 Answers2

2

The code below should hopefully give you an idea on how to implement it to suit your needs, to verify if a device is able to connect to the Internet.

Add the required permissions to AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

MainActivity

public class MainActivity extends Activity {
    boolean mConnected = false;
    String mURL = "http://www.google.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        VerifyInternetConnectionTask task = new VerifyInternetConnectionTask();
        try {
            mConnected = task.execute(mURL).get();
        } catch (InterruptedException e) {
            Log.e(TAG, "AsyncTask Interrupted Exception", e);
        } catch (ExecutionException e) {
            Log.e(TAG, "AsyncTask Execution Exception", e);
        } 

        if (mConnected) {
            Toast.makeText(this, "Connected to Internet",  Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "Unable to connect to the Internet",  Toast.LENGTH_LONG).show();
        }
    }

    private class VerifyInternetConnectionTask extends AsyncTask<String, Void, Boolean> {

       private static final String TAG = "VerifyInternetConnectionTask";

       private boolean isNetworksAvailable() {
          ConnectivityManager mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
          if (mConnMgr != null)  {
             NetworkInfo[] mNetInfo = mConnMgr.getAllNetworkInfo();
             if (mNetInfo != null) {
                for (int i = 0; i < mNetInfo.length; i++) {
                   if (mNetInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                      return true;
                   }
                }
             }
          }
          return false;
       }

       @Override
       protected Boolean doInBackground(final String... params) {
          final int CONNECTION_TIMEOUT = 2000;

          if (isNetworksAvailable()) {
             try {
                HttpURLConnection mURLConnection = (HttpURLConnection) (new URL(params[0]).openConnection());
                mURLConnection.setRequestProperty("User-Agent", "ConnectionTest");
                mURLConnection.setRequestProperty("Connection", "close");
                mURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
                mURLConnection.setReadTimeout(CONNECTION_TIMEOUT);
                mURLConnection.connect();
                return (mURLConnection.getResponseCode() == 200);
             } catch (IOException ioe) {
                Log.e(TAG, "Exception occured while checking for Internet connection: ", ioe);
             }
          } else {
             Log.e(TAG, "Not connected to WiFi/Mobile and no Internet available.");
          }
          return false;
       }
    }

}

kaderud
  • 5,457
  • 2
  • 36
  • 49
0

I'm not sure why its not behaving as I excepted, but found this suitable workaround:

public void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
{
    super.onReceivedError(view, errorCode, description, failingUrl);
    Log.e("web view error: "+errorCode, description);

    if(errorCode == -6 && 
               isConnectedToInternet())
    {
        view.reload();
    }
    else
    {
        view.loadUrl("");
    }
}

I hope this help someone else

TMacGyver
  • 1,281
  • 3
  • 12
  • 27