Testing Network Connection For Android Phones

After deciding to take a hold off of OpenSocial Metagenomics and the headaches that came along with it, I began to finally sit down and figure out how Josh and I could test network connection with our Android apps. Although we attempted to find the solution a few weeks into the development of GenomeSearch, we didn’t find anything that worked. But with a new determination to produce some results I discovered the solution using the NetworkInfo class and ConnectivityManager class that Android supplies. Here is the code for a test application I wrote which displays text on the screen saying whether there is a connection via wifi or phone service provider (3g):

public void onCreate(Bundle savedInstanceState) {

TextView tv = new TextView(this);
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

if ( cm.getNetworkInfo(cm.TYPE_MOBILE).isConnectedOrConnecting() ||
cm.getNetworkInfo(cm.TYPE_WIFI).isConnectedOrConnecting() )
tv.setText("Network available!");
tv.setText("No network available!");

Now we can implement this code into our applications to check and ensure users have network connection before performing any actions that require internet connection.