Reputation: 7484
I followed this to check availability of internet connectivity. The issue I face is that even when my desktop(acting as wifi hotspot) has no internet connection, still this code returns positive. I want to make sure that if wifi signal is missing result must be negative. Can this be achieved?
Upvotes: 1
Views: 59
Reputation: 10601
So, you have a method that tells you, whether the internet connection is available or not, but you think, that this is not sufficient, because it doesn't describe the quality of the connection.
You could try polling some web site to see, if you get a response and based on that decide whether or not to proceed with some network request. But in my opinion, it's not worthwhile.
Instead, you can just send your request and handle the possible network error, because it's something you have to do anyways (the server might be down). So, why do extra tests?
Upvotes: 0
Reputation: 390
Although your device is connected to wifi, you may not get input data. So you may ping Google.com or any other site and see if that responds back with code 200.
public class internetchek extends AsyncTask<Void,Void,Void> {
public boolean connection;
Context ctx;
public internetchek(Context context){
this.ctx = context;
}
@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;
}
}}
Upvotes: 0
Reputation: 7479
This is the code I'm using to check if there's internet connection in my app, and it worked for me:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return ((activeNetworkInfo != null) && activeNetworkInfo.isConnected());
}
Upvotes: 2