如何通过Internet连接检查主机连接

时间:2013-09-10 11:16:08

标签: android internet-connection

我想全面检查与互联网和域名或主机的连接。我用一种方法检查互联网连接,但我无法添加检查主机可用性。我的代码在这里;

public class InternetCheck{
    public static boolean isInternetAvailable(Context context)
    {
        NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
        context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if (info == null){
            Constants.connectionProblem = "Check your internet connection";
            return false;
        }
        else{
            return true;
        }
    }
}

我想在 isInternetAvailable()方法中添加主机或域可用性检查。它必须返回false并设置Constant.connectionProblem = "Host is not available"。因为,我将在我的主要活动上调用该方法,如果它返回false,我将显示一个显示Constants.connectionProblem的Toast。

2 个答案:

答案 0 :(得分:8)

尝试这种方法

private boolean isHostRechable(String hostUrl) {
        try {
            URL url = new URL(hostUrl);
            final HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestProperty("User-Agent", "Android Application");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(10 * 1000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

答案 1 :(得分:1)

使用此方法:

public static boolean isInternetConnected(Context context) {
    final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
    final Dialog dialog = new AlertDialog.Builder(context).setIcon(R.drawable.ic_launcher).setTitle("Connection Error!!")
            .setMessage("Internet Connection not found.\nCheck your settings.").setNegativeButton("ok", null).create();
    if (activeNetwork != null && activeNetwork.isConnected())
        return true;
    else
        dialog.show();
    return false;
}

如果您不想显示吐司评论。

不要忘记在清单文件中放置权限。这是许可:

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