How to check internet access on Android?

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class AppStatus {

   
private static AppStatus instance = new AppStatus();
   
static Context context;
   
ConnectivityManager connectivityManager;
   
NetworkInfo wifiInfo, mobileInfo;
   
boolean connected = false;

   
public static AppStatus getInstance(Context ctx) {
        context
= ctx;
       
return instance;
   
}

   
public boolean isOnline(Context con) {
       
try {
            connectivityManager
= (ConnectivityManager) con
                       
.getSystemService(Context.CONNECTIVITY_SERVICE);

       
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        connected
= networkInfo != null && networkInfo.isAvailable() &&
                networkInfo
.isConnected();
       
return connected;


       
} catch (Exception e) {
           
System.out.println("CheckConnectivity Exception: " + e.getMessage());
           
Log.v("connectivity", e.toString());
       
}
       
return connected;
   
}
}
Now to check if the your device has network connectivity then just add this code snippet where ever you want to check …
if (AppStatus.getInstance(this).isOnline(this)) {

   
Toast t = Toast.makeText(this,"You are online!!!!",8000).show();
} else {

   
Toast t = Toast.makeText(this,"You are not online!!!!",8000).show();
   
Log.v("Home", "############################You are not online!!!!");    }

You will also need:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: