Skip to content Skip to sidebar Skip to footer

How Can I Check My Android Device Having A Internet Connection In Android?

Explanation: I am trying to connect my device which has internet connection.I added a permission in manifiest both network state and internet.I check correctly my device

Solution 1:

This Exception is thrown because you performing networking operation in your main Thread. Do it in your Background Thread. ie AsyncTask

classTaskextendsAsyncTask<String, void, boolean> {

private Exception exception;

protectedbooleandoInBackground(String... xyz) {
    if (networkConnectivity()) {
        try {
            HttpURLConnectionurlc= (HttpURLConnection) (newURL(
                    "http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(3000);
            urlc.setReadTimeout(4000);
            urlc.connect();
            // networkcode2 = urlc.getResponseCode();return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            return (false);
        }
    } elsereturnfalse;
}


  privatebooleannetworkConnectivity() {
    ConnectivityManagercm= (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfonetworkInfo= cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        returntrue;
    }
    returnfalse;
}


}

Solution 2:

it is because you are calling httprequest on main thread . use AsyncTask instead .

Post a Comment for "How Can I Check My Android Device Having A Internet Connection In Android?"