简体   繁体   中英

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();

}

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" /> 

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

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.

InetAddress.getByName可以返回与空字符串不同的null ,这就是从isInternetAvailable()获得TRUE的原因。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM