检查是否有PROGRAMM通过WiFi网络 [英] Checking if programm has the internet over wifi

查看:140
本文介绍了检查是否有PROGRAMM通过WiFi网络的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读一些答案,并试图利用他们,我还是不能让我的code返回正确的状态,如果有互联网通过WiFi或不后。

After reading some answers and trying to use them I still can not make my code return a correct state, if there is internet over wifi or not.

我要平了WIFI,因为我们可以连接到接入点,没有进一步的网络连接。下面是一个完整code。

I must "ping" over WIFI, because we may be connected to the Access Point with no further internet connection. Here is a complete code.

ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NI = CM.getActiveNetworkInfo();
boolean IC = false;             
IC = CM.requestRouteToHost(ConnectivityManager.TYPE_WIFI, FlavaGr.lookupHost(pingyIp));
System.out.println("##### IC=" + IC + "  TYPE = " + NI.getTypeName());

在这里lookupHost,另一个用户建议:

is here lookupHost, suggested by another user :

public static int lookupHost(String hostname) {
InetAddress inetAddress;
try {
    inetAddress = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
    return -1;
}
byte[] addrBytes;
int addr;
addrBytes = inetAddress.getAddress();
addr = ((addrBytes[3] & 0xff) << 24)
        | ((addrBytes[2] & 0xff) << 16)
        | ((addrBytes[1] & 0xff) << 8)
        |  (addrBytes[0] & 0xff);
return addr;
}   

IC永远是假的。
我觉得答案是一步到位,但还是不知道该怎么做。

IC is always false. I feel like the answer is in one step, but still don't know, what to do.

PS对不起,我的英语。

PS Sorry for my English.

推荐答案

我的回答是:

    ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NI = CM.getActiveNetworkInfo();
    if (NI!=null) {
        if (NI.isAvailable()) { 
            boolean IC = false;
            if (NI.getTypeName()=="WIFI") {
                int response = 0;
                try {
                    URL url = new URL("http://www.google.com/");    
                    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                    response = in.read();
                    in.close();

                    IC = (response != -1) ? true : false;
                    System.out.println("##### IC=" + IC + "  TYPE = " + NI.getTypeName() + "  response = " + response);
                    if (true){
                                                ;
                    };
                } catch (Exception e) {
                }}}}}

只是为了检查,如果当前连接的WIFI,然后请求一个页面时,检查第一个字符。

Just to check, if the current connection is WIFI and then request a page, checking first character.

这篇关于检查是否有PROGRAMM通过WiFi网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆