Ave
Ave

Reputation: 4430

How to check internet available in Android?

I created a class to check the internet available to upload a string to the server.

My application does not show any error or warning in log cat. So, I can't post any log.

But when I connected or not connect to the internet, it always shows the message: You do not connect to the internet. in the else clause.

When I debug to isInternetAvailable method, it go to the first line:

InetAddress ipAddr = InetAddress.getByName("google.com");

After, it throws exception like:

cause = {NetworkOnMainThreadException} "android.os.NetworkOnMainThreadException"

and return false.

Code bellow to show check internet available, all code in a class extends BroadcastReceiver:

public boolean isInternetAvailable() {
    try {
        InetAddress ipAddr = InetAddress.getByName("google.com");
        if (ipAddr.equals("")) {
            return false;
        } else {
            return true;
        }
    } catch (Exception e) {
        return false;
    }
}

@Override
public void onReceive(final Context context, final Intent intent) {
    String textToServer = "text example";
    if(isInternetAvailable()){
        sendToServer(context, textToServer.toString());
    } else {
        Toast.makeText(context, "You not connect to internet.", Toast.LENGTH_LONG).show();
    }
}

public void sendToServer(final Context context, final String text){
    contact = new AddContactActivity();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String textparam = "text1=" + URLEncoder.encode(text, "UTF-8");
                URL scripturl = new URL(scripturlstring);
                HttpURLConnection connection = (HttpURLConnection) scripturl.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setFixedLengthStreamingMode(textparam.getBytes().length);
                OutputStreamWriter contentWriter = new OutputStreamWriter(connection.getOutputStream());
                contentWriter.write(textparam);
                contentWriter.flush();
                contentWriter.close();

                InputStream answerInputStream = connection.getInputStream();
                final String answer = getTextFromInputStream(answerInputStream);

                if(answer!="") {
                    String[] contactInfo = answer.split(":::::");
                    if(!contactExists(context, contactInfo[1])) {
                        contact.insertContact(context, contactInfo[0], contactInfo[1], contactInfo[2], contactInfo[3], contactInfo[4]);
                    } else {
                        return;
                    }
                }
                answerInputStream.close();
                connection.disconnect();


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

}

Upvotes: 2

Views: 4680

Answers (4)

hmartinezd
hmartinezd

Reputation: 1186

I check the connectivity like this:

public boolean isDeviceOnline() {
    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

    // test for connection
    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected();
}

But, it may happen that the device is connected, but really doesn't have access to internet (for example in networks where user needs to accept terms and conditions). In that case, you just make the server request, and you check the network response to know the reason for the failure.

Upvotes: 2

Alex
Alex

Reputation: 1644

It's better to ping something. You can use AndroidNetworkTools. That library has a good documentation about pinging.

Upvotes: 2

UMESH0492
UMESH0492

Reputation: 1731

Below code to check is connected to internet

 public static boolean isConnectingToInternet(Context context) {

    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    return activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();
}

Add this to the manifest in addition to the code above: (from comment below)

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

Upvotes: 6

TDG
TDG

Reputation: 6151

InetAddress.getByName can return null which is different from empty string, that's why you get TRUE from isInternetAvailable().

Upvotes: 2

Related Questions