this is my class that checks if the device is connected to the internet.
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
if (networkConnectivity()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL(
"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);
}
} else
return false;
}
private boolean networkConnectivity() {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
}
then i call it here but it doesnt seem to return true or false. there are no errors and my app doesnt crash it just doesnt print anything out. anyone know why?
public void CheckInternet(){
// Boolean isInternetPresent;
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
// isInternetPresent = cd.isConnectingToInternet();
if (cd.isConnectingToInternet()) {
// Internet Connection is Present
Log.i(TAG, "INTERNET IS GUUD");
} else {
// Internet connection is not present
// Ask user to connect to Internet
Log.i(TAG, "INTERNET IS NOOOO GUUD");
}
}
call this function :
Create a class :
Then you call methode from activity, it will return true or false:
And don't forget to add permission to android manifest
This isn't the correct approach to checking for internet connectivity. You should be using Android's built in ConnectivityManager class for this.
It's quite simple to use, you can simply do the following to check for network connectivity:
This will also allow you to determine things like the type of connection, if it's monitored, etc. so that you can make informed decisions about the network tasks you are executing.
There is more info in this lesson on the Android Developers site.
You must do it in an asynctask. I use http://clients3.google.com/generate_204 to detect connection.