-2

I have written a code that uses the internet to insert data into my database, but if the connection to the internet is not available my application gets the data from the database if the data base is not empty.

How can I write a code that checks the connectivity of the internet for my application?

Tolen
  • 111
  • 9

6 Answers6

2

Use below code for check internet.

public boolean check_Internet(Context mContext) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

        if (mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
            return true;
        else
            return false;
    }

Also add the following permission to the AndroidManifest.xml file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
SilentKiller
  • 6,944
  • 6
  • 40
  • 75
Niranj Patel
  • 32,980
  • 10
  • 97
  • 133
2

I've a network-util for you.

public final class NetworkUtils {
public static final byte CONNECTION_OFFLINE = 1;
public static final byte CONNECTION_WIFI = 2;
public static final byte CONNECTION_ROAMING = 3;
public static final byte CONNECTION_SLOW = 4;
public static final byte CONNECTION_FAST = 5;

private static String sUserId;

private NetworkUtils() {}


/**
 * Check if the device is connected to the internet (mobile network or
 * WIFI).
 */
public static boolean isOnline(Context _context) {
    boolean online = false;

    TelephonyManager tmanager = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE);
    if (tmanager != null) {
        if (tmanager.getDataState() == TelephonyManager.DATA_CONNECTED) {
            // Mobile network
            online = true;
        } else {
            // WIFI
            ConnectivityManager cmanager = (ConnectivityManager) _context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cmanager != null) {
                NetworkInfo info = cmanager.getActiveNetworkInfo();
                if (info != null)
                    online = info.isConnected();
            }
        }
    }

    return online;
}

/**
 * Get the User Agent String in the format
 * AppName + AppVersion + Model + ReleaseVersion + Locale
 */
public static String getUserAgentString(Context _c, String _appName) {
    if(_appName == null)
        _appName = "";

    String agent = _appName + " " + BackendUtil.getAppVersionString(_c) + " (" + Build.MODEL + "; Android "
            + Build.VERSION.RELEASE + "; " + Locale.getDefault() + ")";

    if(agent.startsWith(" "))
        agent = agent.substring(1);

    return agent;
}

/**
 * Evaluate the current network connection and return the
 * corresponding type, e.g. CONNECTION_WIFI.
 */
public static byte getCurrentNetworkType(Context _context){
    NetworkInfo netInfo = ((ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if(netInfo == null)
        return CONNECTION_OFFLINE;

    if(netInfo.getType() == ConnectivityManager.TYPE_WIFI)
        return CONNECTION_WIFI;

    if(netInfo.isRoaming())
        return CONNECTION_ROAMING;

    if(!(netInfo.getType() == ConnectivityManager.TYPE_MOBILE 
            &&  (netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_UMTS 
              || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSDPA
              || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSUPA
              || netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSPA 
              || netInfo.getSubtype() == 13 // NETWORK_TYPE_LTE
              || netInfo.getSubtype() == 15))) // NETWORK_TYPE_HSPAP  
         {

        return CONNECTION_SLOW;
    }

    return CONNECTION_FAST;
}


/**
 * Return the current IP adresse of the device or null if it could not be
 * found.
 */
public static String getIpAdress() {
    String result = null;
    try {
        for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
            NetworkInterface iface = interfaces.nextElement();
            for (Enumeration<InetAddress> adresses = iface.getInetAddresses(); adresses.hasMoreElements();) {
                InetAddress ip = adresses.nextElement();
                if (!ip.isLoopbackAddress())
                    result = ip.getHostAddress();
            }
        }
    } catch (SocketException _e) {
        LL.error("Could not find device's ip adress");
    }
    return result;
}


/**
 * Return a MD5 hash of the device id.
 */
public static synchronized String getUserId(Context _context) {
    if (sUserId == null) {
        TelephonyManager tm = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE);
        String id = tm.getDeviceId();
        try {
            MessageDigest digester = MessageDigest.getInstance("MD5");
            digester.update(id.getBytes());
            byte[] digest = digester.digest();

            // Convert to hex string
            BigInteger converter = new BigInteger(1, digest);
            String md5 = converter.toString(16);
            while (md5.length() < 32)
                md5 = "0" + md5;
            sUserId = md5;
        } catch (NoSuchAlgorithmException _e) {
            LL.error("Could not find MD5");
        }
    }
    return sUserId;
}

}

TeeTracker
  • 7,064
  • 8
  • 40
  • 46
1
if (InetAddress.getByName("www.google.com").isReachable(2000)){ // 2000 = timeout
    // connection is available. google is a good candidate
} else {
    // no connection
}
Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
1

http://www.androidhive.info/2012/07/android-detect-internet-connection-status/

Follow the tutorial...Will help you...

Looking Forward
  • 3,579
  • 8
  • 45
  • 65
1
Boolean online = isOnline();

        if (online == false) {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);

            // set title
            alertDialogBuilder.setTitle("Cellular Data is Turned Off!");

            // set dialog message
            alertDialogBuilder
                    .setMessage(
                            "Please turn on cellular data or use Wi-Fi to access data!")
                    .setCancelable(false)
                    .setNeutralButton("Settings",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {

                                    startActivity(new Intent(
                                            android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                                }
                            })
                    .setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.cancel();
                                }
                            });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
Droid
  • 419
  • 4
  • 15
1

Create a method like below :

public boolean checkInternet() { 
        ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
        State mobile = conMan.getNetworkInfo(0).getState(); 
        State wifi = conMan.getNetworkInfo(1).getState(); 
        if (mobile == NetworkInfo.State.CONNECTED || wifi== NetworkInfo.State.CONNECTED) 
            return true; 
        else 
            return false; 
        }

In Activity or Service, you can do this :

if(CheckInternet)
{
     // do your work
}
else
{
      Thread t = new Thread() {
                            @Override
                            public void run() {
                                try 
                                {
                                    //check if connected!
                                    while (!checkInternet()) 
                                    {
                                        //Wait to connect
                                        Thread.sleep(5000);                     
                                    }
                                    //do Your Work here
                                   } catch (Exception e) {
                                }
                            }
                        };
                        t.start();
}

Also add the following permission to the AndroidManifest.xml file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Manish Dubey
  • 4,206
  • 8
  • 36
  • 65