Skip to content

Instantly share code, notes, and snippets.

@devqmr
Created December 20, 2017 07:27
Show Gist options
  • Save devqmr/c67c9287c7b3296c8b053c236f30dc02 to your computer and use it in GitHub Desktop.
Save devqmr/c67c9287c7b3296c8b053c236f30dc02 to your computer and use it in GitHub Desktop.
Detect the internet connect status, to determine when application has access to the internet and when not! * Remember to add InternetConnectDetectReceiver receiver to "AndroidManifest" class
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Detect the internet connect status,
* to determine when application has access to the internet and when not!
*
* Remember to add InternetConnectDetectReceiver receiver to "AndroidManifest" class
*
* Created by Ahmed AbuQamar on 12/19/17.
*/
public class InternetConnectDetectReceiver extends BroadcastReceiver {
private static final String TAG = "InternetConnectDetectReceiver";
private static final String PING_ADDRESS = "www.google.com";
private Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
CheckConnectedToInternetTask task = new CheckConnectedToInternetTask();
task.execute();
}
private class CheckConnectedToInternetTask extends AsyncTask<Void, Void, Void> {
@SuppressLint("LongLogTag")
@Override
protected Void doInBackground(Void... voids) {
AppController.isConnected = isConnectedToNetwork(mContext) && pingAddress(PING_ADDRESS);
Log.i(TAG, "Application ConnectedToNetwork > " + AppController.isConnected);
return null;
}
}
private boolean isConnectedToNetwork(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
} else {
return false;
}
}
@SuppressLint("LongLogTag")
private boolean pingAddress(final String url) {
try {
final InetAddress address = InetAddress.getByName(url);
return address != null && !TextUtils.isEmpty(address.getHostAddress());
} catch (final UnknownHostException e) {
Log.e(TAG, "pingAddress: UnknownHostException > " + e.getMessage());
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment