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:com.silentcircle.silenttext.application.SilentTextApplication.java

private void checkNetworkState() {

    ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

    if (manager == null) {
        return;/*from  w  ww.ja  v  a2 s.c om*/
    }

    NetworkInfo network = manager.getActiveNetworkInfo();
    boolean c = network != null && network.isConnected();

    if (c == connected) {
        return;
    }

    connected = c;

}

From source file:com.newsrob.EntryManager.java

public boolean isNetworkConnected(Context ctx) {

    if (connectivityManager == null)
        connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
    if (ni == null) {
        PL.log("EntryManager. Wasn't able to get NI.", ctx);
        return false;
    }// ww w.  j  a  v a  2 s .  co m

    if (NewsRob.isDebuggingEnabled(ctx)) {
        PL.log("ActiveNetwork: " + ni.getTypeName(), ctx);
        PL.log("ActiveNetworkState: " + ni.getDetailedState(), ctx);
        PL.log("isNetworkConnected? " + ni.isConnected(), ctx);
    }

    return ni.isConnected();
}

From source file:com.grazerss.EntryManager.java

public boolean isNetworkConnected(Context ctx) {

    if (connectivityManager == null) {
        connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    }/*from ww  w .  j av a  2  s  .co m*/

    NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
    if (ni == null) {
        PL.log("EntryManager. Wasn't able to get NI.", ctx);
        return false;
    }

    if (NewsRob.isDebuggingEnabled(ctx)) {
        PL.log("ActiveNetwork: " + ni.getTypeName(), ctx);
        PL.log("ActiveNetworkState: " + ni.getDetailedState(), ctx);
        PL.log("isNetworkConnected? " + ni.isConnected(), ctx);
    }

    return ni.isConnected();
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static boolean isNetworkAvailable(final Context context) {
    final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo info = cm.getActiveNetworkInfo();
    return info != null && info.isConnected();
}

From source file:com.irccloud.android.NetworkConnection.java

public synchronized void connect(String sk) {
    Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
    session = sk;//  ww w. j  av a 2s  .  c om
    String host = null;
    int port = -1;

    if (sk == null || sk.length() == 0)
        return;

    if (ctx != null) {
        ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();

        if (ni == null || !ni.isConnected()) {
            cancel_idle_timer();
            state = STATE_DISCONNECTED;
            reconnect_timestamp = 0;
            notifyHandlers(EVENT_CONNECTIVITY, null);
            return;
        }
    }

    if (state == STATE_CONNECTING || state == STATE_CONNECTED) {
        Log.w(TAG, "Ignoring duplicate connect request");
        return;
    }
    state = STATE_CONNECTING;

    if (oobTasks.size() > 0) {
        Log.d("IRCCloud", "Clearing OOB tasks before connecting");
    }
    for (Integer bid : oobTasks.keySet()) {
        try {
            oobTasks.get(bid).cancel(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    oobTasks.clear();

    if (Build.VERSION.SDK_INT < 11) {
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (!wifiLock.isHeld())
        wifiLock.acquire();

    List<BasicNameValuePair> extraHeaders = Arrays.asList(
            new BasicNameValuePair("Cookie", "session=" + session),
            new BasicNameValuePair("User-Agent", useragent));

    String url = "wss://" + IRCCLOUD_HOST + IRCCLOUD_PATH;
    if (mEvents.highest_eid > 0) {
        url += "?since_id=" + mEvents.highest_eid;
        if (streamId != null && streamId.length() > 0)
            url += "&stream_id=" + streamId;
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        Crashlytics.log(Log.DEBUG, TAG, "Connecting: " + url + " via proxy: " + host);
    } else {
        Crashlytics.log(Log.DEBUG, TAG, "Connecting: " + url);
    }

    Crashlytics.log(Log.DEBUG, TAG, "Attempt: " + failCount);

    client = new WebSocketClient(URI.create(url), new WebSocketClient.Listener() {
        @Override
        public void onConnect() {
            Crashlytics.log(Log.DEBUG, TAG, "WebSocket connected");
            state = STATE_CONNECTED;
            notifyHandlers(EVENT_CONNECTIVITY, null);
            fetchConfig();
        }

        @Override
        public void onMessage(String message) {
            if (client != null && client.getListener() == this && message.length() > 0) {
                try {
                    synchronized (parserLock) {
                        parse_object(new IRCCloudJSONObject(mapper.readValue(message, JsonNode.class)));
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Unable to parse: " + message);
                    Crashlytics.logException(e);
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onMessage(byte[] data) {
            //Log.d(TAG, String.format("Got binary message! %s", toHexString(data));
        }

        @Override
        public void onDisconnect(int code, String reason) {
            Crashlytics.log(Log.DEBUG, TAG, "WebSocket disconnected");
            ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                    .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo ni = cm.getActiveNetworkInfo();
            if (state == STATE_DISCONNECTING || ni == null || !ni.isConnected())
                cancel_idle_timer();
            else {
                failCount++;
                if (failCount < 4)
                    idle_interval = failCount * 1000;
                else if (failCount < 10)
                    idle_interval = 10000;
                else
                    idle_interval = 30000;
                schedule_idle_timer();
                Crashlytics.log(Log.DEBUG, TAG, "Reconnecting in " + idle_interval / 1000 + " seconds");
            }

            state = STATE_DISCONNECTED;
            notifyHandlers(EVENT_CONNECTIVITY, null);

            if (reason != null && reason.equals("SSL")) {
                Crashlytics.log(Log.ERROR, TAG, "The socket was disconnected due to an SSL error");
                try {
                    JSONObject o = new JSONObject();
                    o.put("message", "Unable to establish a secure connection to the IRCCloud servers.");
                    notifyHandlers(EVENT_FAILURE_MSG, new IRCCloudJSONObject(o));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            client = null;
        }

        @Override
        public void onError(Exception error) {
            Crashlytics.log(Log.ERROR, TAG, "The WebSocket encountered an error: " + error.toString());
            if (state == STATE_DISCONNECTING)
                cancel_idle_timer();
            else {
                failCount++;
                if (failCount < 4)
                    idle_interval = failCount * 1000;
                else if (failCount < 10)
                    idle_interval = 10000;
                else
                    idle_interval = 30000;
                schedule_idle_timer();
                Crashlytics.log(Log.DEBUG, TAG, "Reconnecting in " + idle_interval / 1000 + " seconds");
            }

            state = STATE_DISCONNECTED;
            notifyHandlers(EVENT_CONNECTIVITY, null);
            client = null;
        }
    }, extraHeaders);

    Log.d("IRCCloud", "Creating websocket");
    reconnect_timestamp = 0;
    idle_interval = 0;
    accrued = 0;
    notifyHandlers(EVENT_CONNECTIVITY, null);
    if (client != null) {
        client.setSocketTag(WEBSOCKET_TAG);
        if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
                && !host.equalsIgnoreCase("127.0.0.1") && port > 0)
            client.setProxy(host, port);
        else
            client.setProxy(null, -1);
        client.connect();
    }
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static boolean isOnWifi(final Context context) {
    if (context == null)
        return false;
    final ConnectivityManager conn = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = conn.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
            && networkInfo.isConnected();
}

From source file:com.ubiLive.GameCloud.Browser.WebBrowser.java

private void processNetworkType(Intent intent, Context context) {
    int netType;//from   w  ww  .j  a  va 2s  .co m
    int netSubtype;
    int networkType;
    boolean isConnected;
    String reloadUrl;
    DebugLog.d(TAG, "processNetworkType() enter");

    NetworkInfo netInfo = Utils.getCurNetworkInfo(context);
    if (netInfo == null || netInfo.isAvailable() == false) {
        DebugLog.d(TAG, "getCurNetworkInfo() is null");
        netInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
    }

    if (netInfo == null || netInfo.isAvailable() == false) {
        DebugLog.d(TAG, "getCurNetworkInfo() netInfo is null line1383");
        if (mbNetworIsConnect != false) {
            mbNetworIsConnect = false;
            reloadUrl = GameInfo.getErrorUrl();
            reload(reloadUrl);
        }
        Utils.setNetworkType(Constants.NETWORKTYPE_NONE);
        return;
    }
    netType = netInfo.getType();
    netSubtype = netInfo.getSubtype();
    isConnected = netInfo.isConnected();
    DebugLog.e(TAG, "======processNetworkType nettype = " + netType + ",netSubtype = " + netSubtype
            + ",isConnect = " + isConnected);
    switch (netType) {
    case ConnectivityManager.TYPE_MOBILE_SUPL:
    case ConnectivityManager.TYPE_MOBILE_MMS:
    case ConnectivityManager.TYPE_MOBILE_HIPRI:
    case ConnectivityManager.TYPE_MOBILE_DUN:
    case ConnectivityManager.TYPE_MOBILE:
        DebugLog.d(TAG, "processNetworkType ConnectivityManager.TYPE_MOBILE netSubtype=" + netSubtype);
        if (netSubtype == TelephonyManager.NETWORK_TYPE_LTE) {//4
            DebugLog.d(TAG, "processNetworkType ConnectivityManager.TYPE_MOBILE 4G");
            networkType = Constants.NETWORKTYPE_LTE;
        } else {//3
            DebugLog.d(TAG, "processNetworkType ConnectivityManager.TYPE_MOBILE 3G");
            networkType = Constants.NETWORKTYPE_3G;
        }
        break;
    case ConnectivityManager.TYPE_WIFI:
        DebugLog.d(TAG, "processNetworkType ConnectivityManager.TYPE_WIFI");
        networkType = Constants.NETWORKTYPE_WIFI;
        break;
    case ConnectivityManager.TYPE_ETHERNET:
        DebugLog.d(TAG, "processNetworkType ConnectivityManager.TYPE_ETHERNET");
        networkType = Constants.NETWORKTYPE_ETHERNET;
        break;
    default:
        DebugLog.d(TAG, "other network status");
        networkType = Constants.NETWORKTYPE_OTHERS;
        break;
    }
    DebugLog.e(TAG, "======processNetworkType nettype = " + netType + ",netSubtype = " + netSubtype
            + ",isConnect = " + isConnected + ",mbNetworIsConnect = " + mbNetworIsConnect);
    if (isConnected) {
        reloadUrl = Utils.checkUrl(GameInfo.DEFAULT_URL);
        Utils.setNetworkType(networkType);
        //         Utils.setNetworkType(Constants.NETWORKTYPE_WIFI);//temp change
    } else {
        reloadUrl = GameInfo.getErrorUrl();
        Utils.setNetworkType(Constants.NETWORKTYPE_NONE);
    }

    //      if((networkType == Constants.NETWORKTYPE_WIFI || networkType == Constants.NETWORKTYPE_LTE) && mbNetworIsConnect != isConnected){
    if (mbNetworIsConnect != isConnected) {
        mbNetworIsConnect = isConnected;
        reload(reloadUrl);
        DebugLog.d(TAG, "Notify reload finish");
    }
}

From source file:com.lgallardo.qbittorrentclient.RefreshListener.java

private void refresh(String state, String label) {

    // If Contextual Action Bar is open, don't refresh
    if (firstFragment != null && firstFragment.mActionMode != null) {
        return;//from   w  w  w.j  av  a2s.c  o m
    }

    if (qb_version.equals("2.x")) {
        qbQueryString = "json";
        params[0] = qbQueryString + "/events";
    }

    if (qb_version.equals("3.1.x")) {
        qbQueryString = "json";
        params[0] = qbQueryString + "/torrents";
    }

    if (qb_version.equals("3.2.x")) {
        qbQueryString = "query";
        params[0] = qbQueryString + "/torrents?filter=" + state;

        // Get API version in case it hasn't been gotten before
        if (qb_api == null || qb_api.equals("") || qb_api.equals("0")) {
            new qBittorrentApiTask().execute(new Intent());
        }

        // Label
        if (label != null && !label.equals(getResources().getString(R.string.drawer_label_all))) {

            if (label.equals(getResources().getString(R.string.drawer_label_unlabeled))) {
                label = "";
            }

            if (!labels.contains(label)) {
                label = getResources().getString(R.string.drawer_label_all);
            }

            saveLastLabel(label);

            //                Log.d("Debug", "Label filter: " + label);

            try {

                if (!label.equals(getResources().getString(R.string.drawer_label_all))) {

                    // I used a dummy URL to encode label
                    String labelEncoded = Uri.encode("http://www.dummy.org?label=" + label);

                    // then I got the the encoded label
                    labelEncoded = labelEncoded.substring(labelEncoded.indexOf("%3D") + 3);

                    // to build the url and pass it to params[0]
                    if (Integer.parseInt(MainActivity.qb_api) < 10) {
                        params[0] = params[0] + "&label=" + labelEncoded;
                    } else {
                        params[0] = params[0] + "&category=" + labelEncoded;
                    }
                }

            } catch (Exception e) {
                Log.d("Debug", "[Main] Label Exception: " + e.toString());
            }
        } else {
            //                Log.d("Debug", "Label filter2: " + label);

        }

    }

    params[1] = state;

    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected() && !networkInfo.isFailover()) {

        // Logs for reporting
        if (CustomLogger.isMainActivityReporting()) {
            generateSettingsReport();
        }

        if (hostname.equals("")) {
            qBittorrentNoSettingsFoundDialog(R.string.info, R.string.about_help1);
        } else {

            //                Log.d("Report", "Report: " + CustomLogger.getReport());

            if (qb_version.equals("3.2.x") && (cookie == null || cookie.equals(""))) {
                // Request new cookie and execute task in background

                if (connection403ErrorCounter > 1) {

                    toastText(R.string.error403);

                    httpStatusCode = 0;
                    disableRefreshSwipeLayout();
                } else {
                    new qBittorrentCookieTask().execute(params);
                }

            } else {

                if (connection403ErrorCounter > 1) {

                    if (cookie != null && !cookie.equals("")) {
                        // Only toasts the message if there is not a cookie set before
                        toastText(R.string.error403);

                        cookie = null;
                    }

                    httpStatusCode = 0;
                    disableRefreshSwipeLayout();
                } else {

                    // Execute the task in background
                    qbTask = new qBittorrentTask().execute(params);

                    // Check if  alternative speed limit is set
                    new qBittorrentCommand().execute(new String[] { "alternativeSpeedLimitsEnabled", "" });
                }
            }

        }

    } else {

        // Connection Error message
        toastText(R.string.connection_error);

        disableRefreshSwipeLayout();
    }

}