Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Android snippet: Check if the device is connected to the internet

DZone's Guide to

Android snippet: Check if the device is connected to the internet

· Mobile Zone ·
Free Resource

Just a quick function to make your live easier :-)

Bart added a comment to the XML + ProgressBar post from yesterday that checks is the device that runs your application has an active internet connection. To make sure its properly searchable i chose to repost it as an Android snippet.

If you guys come across more useful little pieces of code. Just contact me or leave a comment below.

Here is the function

private Boolean isOnline()	{
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni != null && ni.isConnected())
return true;

return false;
}

 Also don't forget to add the INTERNET (and ACCESS_NETWORK_STATE) permissions to you application :-)

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

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}