Friday 10 April 2015

Internet Check in android app

Most of the times we have to check for the internet connection in our android app.So thats how we do in android :

Android provided a class named ConnectivityManager which helps for checking the internet availability.Using this we can check for the internet as well as can get the type of connectiona available i.e wifi,mobile etc.

And here the code for it :


void checkInternet()
{
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager .getActiveNetworkInfo();
if(activeNetwork!=null && activeNetwork.isConnected()){
Log.e("State<><><>", activeNetwork.getState().toString()+"");
Log.e("activeNetwork", activeNetwork.getTypeName()+"");
}else{
Toast.makeText(getApplicationContext(), "Not Connected to internet", Toast.LENGTH_LONG).show();
}
}

Define these permissions in the manifest file :


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



No comments:

Post a Comment