Skip to content

Instantly share code, notes, and snippets.

@stephensprinkle-zz
Created May 15, 2012 20:08
Show Gist options
  • Save stephensprinkle-zz/2704716 to your computer and use it in GitHub Desktop.
Save stephensprinkle-zz/2704716 to your computer and use it in GitHub Desktop.
Test for Network Connection Before Activity Runs in Android
try{
if (isOnline()){
// Activity Stuff Goes Here
} else {
Log.d("Connection Status", "Connection Not Available");
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("No Network Connection");
alertDialog.setMessage("Internet access is necessary for the use of this app.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
} catch(NullPointerException e){
Log.d("Connection Status", "Connection Not Available");
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("No Network Connection");
alertDialog.setMessage("Internet access is necessary for the use of this app.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
public boolean isOnline() {
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
try {
if (connectionManager.getActiveNetworkInfo().isConnected()) {
Log.d("ConStatus", "Data Connection On");
return true;
} else {
Log.d("ConStatus", "Data Connection off");
return false;
}
} catch (NullPointerException e) {
// No Active Connection
Log.i("ConStatus", "No Active Connection");
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment