-1

i have two activities

first one named: MainActivity

second one named: MountLebanonActivity

in the second activity i put this code to retrieve a text from website

private TextView txtdata;
final String textSource = "http://orthodoxprayers.yolasite.com/resources/saint_elie_sinelfil.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy); 
    setContentView(R.layout.activity_mount_lebanon);
    txtdata = (TextView)findViewById(R.id.txtdata);
    new MyTask().execute();
    URL textUrl;

       try {
        textUrl = new URL(textSource);

        BufferedReader bufferReader 
         = new BufferedReader(new InputStreamReader(textUrl.openStream()));

        String StringBuffer;
        String stringText = "";
        while ((StringBuffer = bufferReader.readLine()) != null) {
         stringText += StringBuffer;   
        }
        bufferReader.close();

        txtdata.setText(stringText);
       } catch (MalformedURLException e) {
        e.printStackTrace();
        txtdata.setText(e.toString());   
       } catch (IOException e) {
        e.printStackTrace();
        txtdata.setText(e.toString());   
       }

   }

   private class MyTask extends AsyncTask<Void, Void, Void>{

    String textResult;

    @Override
    protected Void doInBackground(Void... params) {

        URL textUrl;

        try {
         textUrl = new URL(textSource);

         BufferedReader bufferReader 
          = new BufferedReader(new InputStreamReader(textUrl.openStream()));

         String StringBuffer;
         String stringText = "";
         while ((StringBuffer = bufferReader.readLine()) != null) {
          stringText += StringBuffer;   
         }
         bufferReader.close();

         textResult = stringText;
        } catch (MalformedURLException e) {
         e.printStackTrace();
         textResult = e.toString();   
        } catch (IOException e) {
         e.printStackTrace();
         textResult = e.toString();   
        }

     return null;

    }

    @Override
    protected void onPostExecute(Void result) {

     txtdata.setText(Html.fromHtml(textResult));
     super.onPostExecute(result);   
    }

   }    

in the first activity i put this code in the onclick event of a button

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    android.net.NetworkInfo wifi = cm
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    android.net.NetworkInfo datac = cm
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if ((wifi != null & datac != null)
            && (wifi.isConnected() | datac.isConnected()
            && (wifi.isAvailable() | datac.isAvailable()))) {
            //connection is available
        Intent intent_main_time = new Intent(MainActivity.this,
                MountLebanonActivity.class);
        startActivity(intent_main_time);
        finish();
             }else{
            //no connection
              Toast toast = Toast.makeText(getBaseContext(), "No Internet",
            Toast.LENGTH_LONG);
    toast.show();  
            }

this code works fine if wifi or mobile is turned on or off

but if my wifi is turned on and there is no internet connection this code don't work coz i don't get the toast but the second activity is opened with error code java.net.connectesception: failed to connect ... port 80 connect failed econnrefused (connection refused)

any help?

BasILyoS
  • 845
  • 1
  • 10
  • 15
  • What do you mean by 'internet is available'? Do you mean that you can access every single host that has ever been connected? Or perhaps jus that you have connectivity to every host currently connected? More likely, you mean that you can access a certain small set of hosts. Ping them. – William Pursell Feb 14 '14 at 13:46
  • what i mean is my wifi is on but there is no internet connection this code check if wifi or mobile is turned on but what i need is to check also if there is internet connection – BasILyoS Feb 14 '14 at 13:49
  • Whith this code you will never get to the else: (wifi.isConnected() | datac.isConnected() The `if` will launch as wifi.isConnected() is working. – Sonhja Feb 14 '14 at 13:51
  • just check if you could connect to your url, and it not returned connecting error – streamride Feb 14 '14 at 13:52
  • Try to connect before launching Activity. – Sonhja Feb 14 '14 at 13:54
  • look guys what i need is to check if there is an active internet connection all the codes i tried just check if wifi or mobile is available not if there is an active connection – BasILyoS Feb 14 '14 at 14:10
  • what do you mean by active connection?? a connection that opens every domain in the world?? what you can check is if you have access to a service or a certain domain, checking connectivity to internet is an ambiguous question – Adnane.T Feb 14 '14 at 14:18
  • look adnan i will update my question – BasILyoS Feb 14 '14 at 14:21
  • adnan please take a look to my edited question – BasILyoS Feb 14 '14 at 14:28

1 Answers1

1

You are right. The code you've provided only checks if there is a network connection. The best way to check if there is an active Internet connection is to try and connect to a known server via http.

public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
    try {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500); 
        urlc.connect();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error checking internet connection", e);
    }
} else {
    Log.d(LOG_TAG, "No network available!");
}
return false;
}
Jebasuthan
  • 4,510
  • 3
  • 29
  • 48