1

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

C3D41C
  • 19
  • 2

1 Answers1

0

All network operations should be done using asyntask.since UI thread is shared by other resources in the phone you cannot run time dependent operation.

RanjitRock
  • 1,421
  • 5
  • 20
  • 36