Example usage for android.net NetworkInfo isConnected

List of usage examples for android.net NetworkInfo isConnected

Introduction

In this page you can find the example usage for android.net NetworkInfo isConnected.

Prototype

@Deprecated
public boolean isConnected() 

Source Link

Document

Indicates whether network connectivity exists and it is possible to establish connections and pass data.

Usage

From source file:ti.modules.titanium.network.NetworkModule.java

@Kroll.getProperty
@Kroll.method//from w w  w . j a va  2 s.  co  m
public int getNetworkType() {
    int type = NETWORK_UNKNOWN;

    // start event needs network type. So get it if we don't have it.
    if (connectivityManager == null) {
        connectivityManager = getConnectivityManager();
    }

    try {
        NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
        if (ni != null && ni.isAvailable() && ni.isConnected()) {
            type = networkTypeToTitanium(true, ni.getType());
        } else {
            type = NetworkModule.NETWORK_NONE;
        }
    } catch (SecurityException e) {
        Log.w(TAG, "Permission has been removed. Cannot determine network type: " + e.getMessage());
    }
    return type;
}

From source file:ti.modules.titanium.network.NetworkModule.java

@Kroll.getProperty
@Kroll.method/*from ww w.j ava2s .c om*/
public boolean getOnline() {
    boolean result = false;

    ConnectivityManager cm = getConnectivityManager();
    if (cm != null) {
        NetworkInfo ni = getConnectivityManager().getActiveNetworkInfo();

        if (ni != null && ni.isAvailable() && ni.isConnected()) {
            result = true;
        }
    } else {
        Log.w(TAG, "ConnectivityManager was null", Log.DEBUG_MODE);
    }
    return result;
}

From source file:com.pdfread.standardreader.net.AsyncHttpClient.java

public boolean isNetWorkAvilable() {

    boolean result = false;
    if (null != mContext) {
        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null) {

            result = info.isConnected();

        }/*from ww w . j a  v a  2s.c  om*/
    }

    return result;
}

From source file:edu.stanford.mobisocial.dungbeetle.MessagingManagerThread.java

public MessagingManagerThread(final Context context) {
    mContext = context;//  w ww.  j a v  a2 s  .  co  m
    mHelper = DBHelper.getGlobal(context);
    mIdent = new DBIdentityProvider(mHelper);
    mMessageDropHandler = new MessageDropHandler();

    ConnectionStatus status = new ConnectionStatus() {
        public boolean isConnected() {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cm.getActiveNetworkInfo();
            return info != null && info.isConnected();
        }
    };
    mMessenger = new RabbitMQMessengerService(wrapIdent(mIdent), status);
    mMessenger.addStateListener(new StateListener() {
        public void onReady() {
            Log.i(TAG, "Connected to message transport!");
        }

        public void onNotReady() {
            Log.i(TAG, "Message transport not available.");
        }
    });
    mMessenger.addMessageListener(new MessageListener() {
        public void onMessage(IncomingMessage incoming) {
            if (DBG)
                Log.i(TAG, "Got incoming message " + incoming);
            handleIncomingMessage(incoming);
        }
    });
    mMessenger.addConnectionStatusListener(new ConnectionStatusListener() {

        @Override
        public void onStatus(String msg, Exception e) {
            StringWriter err = new StringWriter();
            PrintWriter p = new PrintWriter(err);
            if (e != null) {
                p.println(e.toString());
                p.println(e.getMessage());
                e.printStackTrace(p);
            }
            Log.e(TAG, "Connection Status: " + msg + "\n" + err.toString());
        }
    });

    mOco = new ObjectContentObserver(new Handler(mContext.getMainLooper()));
    mContext.getContentResolver()
            .registerContentObserver(Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/feeds"), true, mOco);
    mContext.getContentResolver()
            .registerContentObserver(Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/out"), true, mOco);
}

From source file:com.appnexus.opensdk.AdRequest.java

private AdRequest(AdRequester adRequester, int httpRetriesLeft, int blankRetriesLeft) {
    owner = adRequester.getOwner();//from  w  w w. j a  v  a 2s. co m
    this.requester = adRequester;
    this.httpRetriesLeft = httpRetriesLeft;
    this.blankRetriesLeft = blankRetriesLeft;
    this.placementId = owner.getPlacementID();
    context = owner.getContext();
    String aid = android.provider.Settings.Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

    // Do we have access to location?
    if (context.checkCallingOrSelfPermission(
            "android.permission.ACCESS_FINE_LOCATION") == PackageManager.PERMISSION_GRANTED
            || context.checkCallingOrSelfPermission(
                    "android.permission.ACCESS_COARSE_LOCATION") == PackageManager.PERMISSION_GRANTED) {
        // Get lat, long from any GPS information that might be currently
        // available
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location lastLocation = lm.getLastKnownLocation(lm.getBestProvider(new Criteria(), false));
        if (lastLocation != null) {
            lat = "" + lastLocation.getLatitude();
            lon = "" + lastLocation.getLongitude();
            locDataAge = "" + (System.currentTimeMillis() - lastLocation.getTime());
            locDataPrecision = "" + lastLocation.getAccuracy();
        }
    } else {
        Clog.w(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_location));
    }

    // Do we have permission ACCESS_NETWORK_STATE?
    if (context.checkCallingOrSelfPermission(
            "android.permission.ACCESS_NETWORK_STATE") != PackageManager.PERMISSION_GRANTED) {
        Clog.e(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_network_state));
        fail();
        this.cancel(true);
        return;
    }

    // Get orientation, the current rotation of the device
    orientation = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
            ? "h"
            : "v";
    // Get hidmd5, hidsha1, the device ID hashed
    if (Settings.getSettings().hidmd5 == null) {
        Settings.getSettings().hidmd5 = HashingFunctions.md5(aid);
    }
    hidmd5 = Settings.getSettings().hidmd5;
    if (Settings.getSettings().hidsha1 == null) {
        Settings.getSettings().hidsha1 = HashingFunctions.sha1(aid);
    }
    hidsha1 = Settings.getSettings().hidsha1;
    // Get devMake, devModel, the Make and Model of the current device
    devMake = Settings.getSettings().deviceMake;
    devModel = Settings.getSettings().deviceModel;
    // Get carrier
    if (Settings.getSettings().carrierName == null) {
        Settings.getSettings().carrierName = ((TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperatorName();
    }
    carrier = Settings.getSettings().carrierName;
    // Get firstlaunch and convert it to a string
    firstlaunch = Settings.getSettings().first_launch;
    // Get ua, the user agent...
    ua = Settings.getSettings().ua;
    // Get wxh

    if (owner.isBanner()) {
        this.width = ((BannerAdView) owner).getAdWidth();
        this.height = ((BannerAdView) owner).getAdHeight();
    }

    maxHeight = owner.getContainerHeight();
    maxWidth = owner.getContainerWidth();

    if (Settings.getSettings().mcc == null || Settings.getSettings().mnc == null) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String networkOperator = tm.getNetworkOperator();
        if (networkOperator != null && networkOperator.length() >= 6) {
            Settings.getSettings().mcc = networkOperator.substring(0, 3);
            Settings.getSettings().mnc = networkOperator.substring(3);
        }
    }
    mcc = Settings.getSettings().mcc;
    mnc = Settings.getSettings().mnc;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    connection_type = wifi.isConnected() ? "wifi" : "wan";
    dev_time = "" + System.currentTimeMillis();

    if (owner instanceof InterstitialAdView) {
        // Make string for allowed_sizes
        allowedSizes = "";
        ArrayList<Size> sizes = ((InterstitialAdView) owner).getAllowedSizes();
        for (Size s : sizes) {
            allowedSizes += "" + s.width() + "x" + s.height();
            // If not last size, add a comma
            if (sizes.indexOf(s) != sizes.size() - 1)
                allowedSizes += ",";
        }
    }

    nativeBrowser = owner.getOpensNativeBrowser() ? "1" : "0";

    //Reserve price
    reserve = owner.getReserve();
    if (reserve <= 0) {
        this.psa = owner.shouldServePSAs ? "1" : "0";
    } else {
        this.psa = "0";
    }

    age = owner.getAge();
    if (owner.getGender() != null) {
        if (owner.getGender() == AdView.GENDER.MALE) {
            gender = "m";
        } else if (owner.getGender() == AdView.GENDER.FEMALE) {
            gender = "f";
        } else {
            gender = null;
        }
    }
    customKeywords = owner.getCustomKeywords();

    mcc = Settings.getSettings().mcc;
    mnc = Settings.getSettings().mnc;
    language = Settings.getSettings().language;
}

From source file:com.kiddobloom.bucketlist.AuthenticatorActivity.java

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

@Override
protected Integer doInBackground(Void... params) {

    SharedPreferences prefs = dataService.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE);

    // Connectivity receiver.
    final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
    ComponentName receiver = new ComponentName(dataService, WifiReceiver.class);
    PackageManager pm = dataService.getPackageManager();
    if (activeNetwork == null || !activeNetwork.isConnected()) {
        // We've missed a scheduled update. Enable the receiver so it can launch an update when we reconnect.
        Log.d(LOG_TAG, "Missed library update: not connected. Enabling connectivity receiver.");
        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        return RESULT_CODE_FAILURE;
    } else {//from  w  w w  . j a  v  a2 s  .  c  om
        // We are connected. Disable the receiver.
        Log.d(LOG_TAG, "Library updater connected. Disabling connectivity receiver.");
        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }

    InputStream in = null;
    String etag = prefs.getString(SETTING_LIBRARY_ETAG, null);

    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        if (etag != null && !force) {
            conn.setRequestProperty("If-None-Match", etag);
        }

        int code = conn.getResponseCode();
        switch (code) {
        case HttpStatus.SC_NOT_MODIFIED:
            // If we got a 304, we're done.
            // Use failure code to indicate there is no temp db to copy over.
            Log.d(LOG_TAG, "304 in library response.");
            return RESULT_CODE_FAILURE;
        default:
            // Odd, but on 1/3/13 I received correct json responses with a -1 for responseCode. Fall through.
            Log.w(LOG_TAG, "Error code in library response: " + code);
        case HttpStatus.SC_OK:
            // Parse response.
            in = conn.getInputStream();
            JsonFactory factory = new JsonFactory();
            final JsonParser parser = factory.createJsonParser(in);

            SQLiteDatabase tempDb = tempDbHelper.getWritableDatabase();
            tempDb.beginTransaction();
            try {
                tempDb.execSQL("delete from topic");
                tempDb.execSQL("delete from topicvideo");
                tempDb.execSQL("delete from video");

                parseObject(parser, tempDb, null, 0);
                tempDb.setTransactionSuccessful();
            } catch (Exception e) {
                e.printStackTrace();
                return RESULT_CODE_FAILURE;
            } finally {
                tempDb.endTransaction();
                tempDb.close();
            }

            // Save etag once we've successfully parsed the response.
            etag = conn.getHeaderField("ETag");
            prefs.edit().putString(SETTING_LIBRARY_ETAG, etag).apply();

            // Move this new content from the temp db into the main one.
            mergeDbs();

            return RESULT_CODE_SUCCESS;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        tempDbHelper.close();
    }

    return RESULT_CODE_FAILURE;
}

From source file:com.example.loc.MainActivity.java

public boolean isOnline(Context con) {
    ConnectivityManager connectivityManager = (ConnectivityManager) con
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return (networkInfo != null) && networkInfo.isAvailable() && networkInfo.isConnected();
}

From source file:com.danielme.android.webviewdemo.WebViewDemoActivity.java

/**
 * Checks networking status.//from  ww  w  .  java  2 s.c o m
 */
private boolean checkConnectivity() {
    boolean enabled = true;

    ConnectivityManager connectivityManager = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = connectivityManager.getActiveNetworkInfo();

    if ((info == null || !info.isConnected() || !info.isAvailable())) {
        enabled = false;
        Builder builder = new Builder(this);
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.setMessage(getString(R.string.noconnection));
        builder.setCancelable(false);
        builder.setNeutralButton(R.string.ok, null);
        builder.setTitle(getString(R.string.error));
        builder.create().show();
    }
    return enabled;
}

From source file:com.cybrosys.currency.CurrencyMain.java

public final boolean isConnection() {
    @SuppressWarnings("static-access")
    ConnectivityManager cm = (ConnectivityManager) getActivity()
            .getSystemService(getActivity().CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
        return true;
    }//from  w  ww .  jav a2s  .  c o m
    NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
        return true;
    }
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        return true;
    }
    return false;
}