Android - Checking server or url availability

时间:2016-02-03 04:06:43

标签: android httpurlconnection

Can someone help me with this code. I found so many results but nothing seems to work. As android updates, some or most of its old code deprecates. Maybe there someone who would know how.

Example: URL = "192.168.1.14"

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

I am using Android Studio and I already put the above code in the AndroidManifest.xml

My current Android build for my project is Android 4.0

Forgot to mention that I used WAMP Server and MySQL, so the URL is from the server computer managing the website that I am attempting to access

The code below uses android device ip address specified above. But keeps returning false.

public Boolean isConnectedToServer(String url) {
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con =  (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");

        Toast.makeText(LogIn.this, "NETWORK CONNECTED", Toast.LENGTH_LONG).show();
        if(con.getResponseCode() == HttpURLConnection.HTTP_OK)
        {
            return true;
        }
        else
        {
            return false;
        }
    } catch (Exception e) {
        Toast.makeText(LogIn.this, "NETWORK ERROR CONNECTION", Toast.LENGTH_LONG).show();
        Log.e("APP", "exception", e);
        return false;
    }
}

The code below same as before uses android device ip address specified above but loops the array of ip or in this case the entire network. But still keeps returning false.

public Boolean isConnectedToServer(String url) {
    int index = url.lastIndexOf(".");
    Boolean result = false;
    for(int octet = 2; octet <= 254; octet++) {
        try {
            HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection con = (HttpURLConnection) new URL("http://" + url.substring(0, index + 1) + "" + octet + "/").openConnection();
            con.setRequestMethod("HEAD");

            //Toast.makeText(LogIn.this, "NETWORK CONNECTED", Toast.LENGTH_LONG).show();
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK)
            {
                result = true;
                break;
            }
            else
            {
                result = false;
            }
        } catch (Exception e) {
            //Toast.makeText(LogIn.this, "NETWORK ERROR CONNECTION", Toast.LENGTH_LONG).show();
            Log.e("APP", "exception", e);
            result = false;
        }
    }
    return result;
}

Any suggestion or fix to code?

Exception returns: android.os.NetworkOnMainThreadException

1 个答案:

答案 0 :(得分:0)

所有网络操作都应该使用asyntask完成。由于UI线程由手机中的其他资源共享,因此您无法运行与时间相关的操作。