Skip to content

Instantly share code, notes, and snippets.

@MohamedAbdelrazek
Created May 18, 2019 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MohamedAbdelrazek/5930c5ef8625d96495fb12561cd5e8d3 to your computer and use it in GitHub Desktop.
Save MohamedAbdelrazek/5930c5ef8625d96495fb12561cd5e8d3 to your computer and use it in GitHub Desktop.
Check Network Connectivity in android
package com.mobotechnology.bipinpandey.mvp_hand_dirty.main_activity.broadCastReciever;
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.util.Log;
import java.net.URL;
import java.net.URLConnection;
public class CheckConnectivity extends BroadcastReceiver {
Click mClick;
public void setList(Click click) {
mClick = click;
}
@Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
checkConnectivity(context);
}
}
private void checkConnectivity(final Context context) {
if (!isNetworkInterfaceAvailable(context)) {
mClick.offline();
return;
}
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... voids) {
return isAbleToConnect();
}
@Override
protected void onPostExecute(Boolean isConnected) {
super.onPostExecute(isConnected);
if (isConnected) {
mClick.online();
} else {
mClick.offline();
}
}
}.execute();
}
//This only checks if the network interface is available, doesn't guarantee a particular network service is available, for example, there could be low signal or server downtime
private boolean isNetworkInterfaceAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
//This makes a real connection to an url and checks if you can connect to this url, this needs to be wrapped in a background thread
private boolean isAbleToConnect() {
try {
URL myUrl = new URL("http://www.google.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(1000);
connection.connect();
return true;
} catch (Exception e) {
Log.i("exception", "" + e.getMessage());
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment