1

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

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,我将显示一个 Toast,它显示 Constants.connectionProblem 。

4

2 回答 2

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;
    }
于 2013-09-10T11:22:38.653 回答
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" />
于 2013-09-10T11:22:19.243 回答