0

我在这里看到了有关网络连接的所有答案,它们非常好。唯一的问题是下一个用例。

如果手机已连接到 wifi 网络,但路由器失去了与 Internet 的连接。所以我想把这个添加到围绕 SO 给出的代码中:

/** Google public DNS service IP address **/
public static final String GOOGLE = "http://8.8.8.8"; 

public static boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
        .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info == null) {
        return false;
    }
    if (info.isConnected()) {
        try {
            InetAddress addr = InetAddress.getByName(GOOGLE);
            return addr.isReachable(10000);
        } catch (UnknownHostException e) {
            Log.wtf("Utils", e);
        } catch (IOException e) {
            Log.wtf("Utils", e);
        }
        return false;
    } else
        return false;
    }
}

唯一的问题是它在主线程上运行,或者更准确地说,它在主线程上运行时崩溃。

如果我将在单独的线程中运行它,它将在从服务器获得有效答案之前返回。

关于如何测试互联网连接(相对于网络连接)的任何想法?

4

1 回答 1

0

您必须将逻辑拆分为检查连接之前和检查连接之后

然后通过使用Handler和后台线程,您可以像这样测试连接性:

private static void onConnectivityCheckFinish(boolean result){

}
 public static void isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
        .getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo info = cm.getActiveNetworkInfo();
        if (info == null) {

            onConnectivityCheckFinish(false);
        }
 if (info.isConnected()) {
        final Handler handler = new Handler(

        );
        new Thread(){
            @Override
            public void run(){
                     try {
                        InetAddress addr = InetAddress.getByName(GOOGLE);
                        final boolean result = addr.isReachable(10000);
                        handler.post(new Runnable(){
                            @Override
                            public void run(){
                                onConnectivityCheckFinish(result);
                            }
                        });
                     } catch (Exception e) {
                        Log.wtf("Utils", e);
                        handler.post(new Runnable(){

                                @Override
                                public void run(){
                                    onConnectivityCheckFinish(false);
                            }

                        });



            }
        }
        }.start();

onConnectivityCheckFinish(false);}
 else {
     onConnectivityCheckFinish(false);
 }
}
于 2013-03-17T12:41:43.083 回答