user3507451 user3507451 - 6 months ago 21
Android Question

How to check internet connection before app starts and while it is running?

I found a lot of answer about this but unable to implement those also.
I want to implement this code here but not able to do so.

This code I found on google documentation.

ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();


https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html#DetermineConnection

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;

// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}

// Convert response to string
try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
}
StringBuilder sb = new StringBuilder();
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
}
if (is != null) {
is.close();
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}

try {

jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}

return jArray;
}


}

Thank You all for the help

Answer

Simple function to check the internet connection

protected boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        return true;
    } else {
        return false;
    }
}

and in your AndroidManifest.xml you should add the permission

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