user3507451
user3507451

Reputation: 39

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;
}

}

Upvotes: 0

Views: 1468

Answers (5)

Rashid
Rashid

Reputation: 1740

UPDATE:

Update the solution for internet checking. What works for me now is this

fun isNetworkAvailable(context: Context?): Boolean {
    if (context == null) return false

    val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val capabilities =
            connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        return capabilities != null &&
                (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                        capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                        capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET))
    } else {
        try {
            val activeNetworkInfo = connectivityManager.activeNetworkInfo
            return activeNetworkInfo != null && activeNetworkInfo.isConnected
        } catch (ignored: Exception) {
        }
    }

    return false
}

OLD:

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" />

Upvotes: 2

sandesh
sandesh

Reputation: 390

what happens if your device connected to internet, but no input data? You also have to check whether you are receiving data or not. Check below code to see you are connected internet and able access data. You just need to ping a site and see if your responce back is 200.

 public class internetchek extends AsyncTask<Void,Void,Void> {

 public boolean connection;
 Context ctx;
 public internetchek(Context context){
  this.ctx = context;
 }
 public internetchek(){

 }
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected Void doInBackground(Void... params) {

if(isNetworkAvailable(this.ctx))
{

 Log.d("NetworkAvailable","TRUE");
    if(connectGoogle())
    {

        Log.d("GooglePing","TRUE");
        connection=true;
    }
    else
    {

        Log.d("GooglePing","FALSE");
        connection=false;
    }
 }
 else {

    connection=false;
 }


 return null;
 }

 @Override
 protected void onPostExecute(Void aVoid) {
   super.onPostExecute(aVoid);
 }

 public static boolean isNetworkAvailable(Context context) {
   ConnectivityManager cm = (ConnectivityManager)        context.getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo netInfo = cm.getActiveNetworkInfo();
   if (netInfo != null && netInfo.isConnected()) {
    return true;
   }
   return false;
  }

  public static boolean connectGoogle() {
    try {
     HttpURLConnection urlc = (HttpURLConnection) (new     URL("http://www.google.com").openConnection());
    urlc.setRequestProperty("User-Agent", "Test");
    urlc.setRequestProperty("Connection", "close");
    urlc.setConnectTimeout(10000);
    urlc.connect();
    return (urlc.getResponseCode() == 200);

  } catch (IOException e) {

     Log.d("GooglePing","IOEXCEPTION");
     e.printStackTrace();
     return false;
  }
} 

UPDATE: If you want to use it for other classes you can do this..make sure you put below code in AsyncTask or background running thread.

       if(internetchek.isNetworkAvailable(this.ctx)||internetchek.connectGoogle())
 {

 //Do your stuff here. when you have internet access 

 }

Upvotes: 0

Abhishek Patel
Abhishek Patel

Reputation: 4328

like this you can make this method in your common file for your project

 public static boolean isNetworkAvailable(Context ctx) {
    ConnectivityManager cm = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        return false;
    }
}

and use like

if(commonfile.isNetworkAvilable(pass your context here))
{
  //call your method
}

and don't forgot to add permission for Internet in your manifeast

Upvotes: 0

Shubham
Shubham

Reputation: 531

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) {
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            return true;
        }
    }
    return false;
}

Upvotes: 0

Rohit Heera
Rohit Heera

Reputation: 2727

 protected boolean isNetworkAvilable() {
        boolean isNetworkAvilable = false;
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null && info.isAvailable() && info.isConnected()) {
            isNetworkAvilable = true;
        }
        return isNetworkAvilable;
    }


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

Upvotes: 0

Related Questions