简体   繁体   English

如何检查Android中的互联网?

[英]How to check internet available in Android?

I created a class to check the internet available to upload a string to the server. 我创建了一个类来检查可用于将字符串上传到服务器的Internet。

My application does not show any error or warning in log cat. 我的应用程序在日志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. 但是当我连接或未连接到互联网时,它始终显示消息: You do not connect to the internet. in the else clause. 在else子句中。

When I debug to isInternetAvailable method, it go to the first line: 当我调试到isInternetAvailable方法时,它转到第一行:

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

After, it throws exception like: 之后,它抛出异常,如:

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

and return false. 并返回false。

Code bellow to show check internet available, all code in a class extends BroadcastReceiver : 代码显示检查互联网可用,类中的所有代码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. ping一些东西会更好。 You can use AndroidNetworkTools . 您可以使用AndroidNetworkTools That library has a good documentation about pinging. 该库有关于ping的良好文档。

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的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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