Sunday, July 8, 2012

Testing your Android Applications Internet Connection

Many droid apps rely on the internet to function.  My (soon to be released) PollKarma application relies on facebook for authentication, so I had to test this.  Googling the problem lead me to this solution:

public boolean isOnline() {
ConnectivityManager cm =
ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

return cm.getActiveNetworkInfo() != null &&

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

This only does half the job.  Thankfully I was working on this at a starbucks.  Most public wifi these days will allow any device to connect, but requires a further action before connecting to the internet.  The above code really test the network connection (are you on Wifi) not internet connection (can you get data from the www). 

After some trial and error I came up with this solution:

public void initialize() throws IOException{URL url = new URL("");URLConnection connection = url.openConnection();try { HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestMethod("GET"); httpConn.connect();        //initialize your application here now that the connection is confirmed } catch (Exception e) {        //set up an alert dialog for graceful failure if no connection is available              e.printStackTrace(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage( "No Connection.  Please logon to the Internet to continue.") .setCancelable(false) .setPositiveButton("Retry", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { initialize(); } catch (Exception ie) { ie.printStackTrace(); } } }) .setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { YOURCLASS.this.finish(); } }); AlertDialog alert = builder.create();;}}

which is called from onCreate like so:

try{  initialize();}catch(Exception e){  e.printStackTrace();}

This functionality not only performs a test ensure the connections you really need are available, but it also provides the user with an elegant alternative if there is no connection. Quite a few steps better than the default hang on no connection!

No comments:

Post a Comment