Created
May 15, 2012 20:08
-
-
Save stephensprinkle-zz/2704716 to your computer and use it in GitHub Desktop.
Test for Network Connection Before Activity Runs in Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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