Carlo
Carlo

Reputation: 1177

How to check whether Android has internet connection

I am developing an Android application.

I want my application to notify me whether Android has internet connection or not. How do I check it?

Upvotes: 1

Views: 844

Answers (3)

Padma Kumar
Padma Kumar

Reputation: 20041

//this will check for the wifi, 3G/EDGE and all network availability

public boolean networkStatus() {
        boolean status = false;
        int i = 0;
        try {
            String service = context.CONNECTIVITY_SERVICE;
            ConnectivityManager connectivity = (ConnectivityManager) BackupSettings.this.context.getSystemService(service);
            connectivity.setNetworkPreference(1);
            NetworkInfo networkInfo[] = connectivity.getAllNetworkInfo();
            int cnt = networkInfo.length;
            for (i = 0; i < cnt; i++) {
                if (networkInfo[i].isConnected() == true) {
                    status = true;
                }
            }
        } catch (Exception ee) {
            Log.e(getClass().getSimpleName(), " Error at networkStatus() :=" + ee.toString());
        }
        Log.e(getClass().getSimpleName(),"End  of  networkStatus() fun " + status);
        return status;
    }

Upvotes: 1

Arun Paarthi
Arun Paarthi

Reputation: 643

@Carlo: The simplest way is first to add ACCESS_NETWORK_STATE permission to your application manifest file and write a function like this

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

if the return value is true means internet is working or false means show an alert box :)

Upvotes: 4

ihrupin
ihrupin

Reputation: 6972

You need to create a broadcast receiver for android.net.conn.CONNECTIVITY_CHANGE intent in your application.

Here is the documentation http://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION

Hope, it help you!

Upvotes: 1

Related Questions