Example usage for android.net NetworkInfo getState

List of usage examples for android.net NetworkInfo getState

Introduction

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

Prototype

@Deprecated
public State getState() 

Source Link

Document

Reports the current coarse-grained state of the network.

Usage

From source file:com.mobilyzer.util.PhoneUtils.java

/** Returns the network that the phone is on (e.g. Wifi, Edge, GPRS, etc). */
public String getNetwork() {
    initNetwork();//w ww .j  av  a2 s. c o m
    NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
        Logger.d("Current Network: WIFI");
        return NETWORK_WIFI;
    } else {
        return getTelephonyNetworkType();
    }
}

From source file:indrora.atomic.irc.IRCService.java

/**
 * Connect to the given server//from w  w  w .  j a  v a2s  .com
 */
public void connect(final Server server) {
    final int serverId = server.getId();
    final int reconnectInterval = settings.getReconnectInterval() * 60000;
    final IRCService service = this;

    if (settings.isReconnectEnabled()) {
        server.setMayReconnect(true);
    }

    new Thread("Connect thread for " + server.getTitle()) {
        @Override
        public void run() {
            synchronized (alarmIntentsLock) {
                if (alarmIntents == null)
                    return;
                alarmIntents.remove(serverId);
                ReconnectReceiver lastReceiver = alarmReceivers.remove(serverId);
                if (lastReceiver != null) {
                    unregisterReceiver(lastReceiver);
                }
            }

            if (settings.isReconnectEnabled() && !server.mayReconnect()) {
                return;
            }

            try {
                IRCConnection connection = getConnection(serverId);

                connection.setNickname(server.getIdentity().getNickname());
                connection.setAliases(server.getIdentity().getAliases());
                connection.setIdent(server.getIdentity().getIdent());
                connection.setRealName(server.getIdentity().getRealName());
                connection.setUseSSL(server.useSSL());
                X509TrustManager[] trustMgr = MemorizingTrustManager.getInstanceList(getApplicationContext());
                connection.setTrustManagers(trustMgr);

                if (server.getCharset() != null) {
                    connection.setEncoding(server.getCharset());
                }

                if (server.getAuthentication().hasSaslCredentials()) {
                    connection.setSaslCredentials(server.getAuthentication().getSaslUsername(),
                            server.getAuthentication().getSaslPassword());
                }

                if (server.getPassword() != "") {
                    connection.connect(server.getHost(), server.getPort(), server.getPassword());
                } else {
                    connection.connect(server.getHost(), server.getPort());
                }
            } catch (Exception e) {
                server.setStatus(Status.DISCONNECTED);

                NetworkInfo ninf = ((ConnectivityManager) (IRCService.this
                        .getSystemService(Service.CONNECTIVITY_SERVICE))).getActiveNetworkInfo();
                if (ninf == null) {
                    _isTransient = false;
                } else {
                    _isTransient = !(ninf.getState() == NetworkInfo.State.CONNECTED);
                }

                Intent sIntent = Broadcast.createServerIntent(Broadcast.SERVER_UPDATE, serverId);
                sendBroadcast(sIntent);

                IRCConnection connection = getConnection(serverId);

                Message message;

                if (e instanceof NickAlreadyInUseException) {
                    message = new Message(getString(R.string.nickname_in_use, connection.getNick()));
                    server.setMayReconnect(false);
                } else if (e instanceof IrcException) {
                    message = new Message(
                            getString(R.string.irc_login_error, server.getHost(), server.getPort()));
                    server.setMayReconnect(false);
                } else if (e instanceof SSLException) {
                    // This happens when we declined the SSL certificate most of the time
                    // We should check what really happened.
                    message = new Message("SSL negotiation failed: " + e.toString());
                } else {
                    message = new Message(
                            getString(R.string.could_not_connect, server.getHost(), server.getPort()) + ":\n"
                                    + e.getMessage());

                    if (settings.isReconnectEnabled()) {
                        Intent rIntent = new Intent(Broadcast.SERVER_RECONNECT + serverId);
                        PendingIntent pendingRIntent = PendingIntent.getBroadcast(service, 0, rIntent, 0);
                        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                        ReconnectReceiver receiver = new ReconnectReceiver(service, server);
                        synchronized (alarmIntentsLock) {
                            alarmReceivers.put(serverId, receiver);
                            registerReceiver(receiver, new IntentFilter(Broadcast.SERVER_RECONNECT + serverId));
                            am.set(AlarmManager.ELAPSED_REALTIME,
                                    SystemClock.elapsedRealtime() + reconnectInterval, pendingRIntent);
                            alarmIntents.put(serverId, pendingRIntent);
                        }
                    }
                }

                message.setColor(Message.MessageColor.ERROR);
                message.setIcon(R.drawable.error);
                server.getConversation(ServerInfo.DEFAULT_NAME).addMessage(message);

                Intent cIntent = Broadcast.createConversationIntent(Broadcast.CONVERSATION_MESSAGE, serverId,
                        ServerInfo.DEFAULT_NAME);
                sendBroadcast(cIntent);
            }
        }
    }.start();
}

From source file:fr.inria.ucn.collectors.NetworkStateCollector.java

/**
 * /*from w w w  . ja v a  2s  . co  m*/
 * @param c
 * @param ts
 * @param change
 */
@SuppressWarnings("deprecation")
@SuppressLint({ "DefaultLocale", "NewApi" })
public void run(Context c, long ts, boolean change) {
    try {
        // current active interface (wifi or mobile) and config
        ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();

        JSONObject data = new JSONObject();
        data.put("on_network_state_change", change); // this collection run was triggered by network change
        data.put("is_connected", (ni != null && ni.isConnectedOrConnecting()));
        data.put("is_roaming", tm.isNetworkRoaming());

        // airplane mode ?
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            data.put("is_airplane_mode",
                    (Settings.System.getInt(c.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0));
        } else {
            data.put("is_airplane_mode",
                    (Settings.Global.getInt(c.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0));
        }

        if (ni != null) {
            JSONObject active = new JSONObject();
            active.put("type", ni.getType());
            active.put("subtype", ni.getSubtype());
            active.put("type_name", ni.getTypeName());
            active.put("subtype_name", ni.getSubtypeName());
            active.put("state", ni.getState().toString());
            active.put("detailed_state", ni.getDetailedState().toString());
            active.put("is_wifi", (ni.getType() == ConnectivityManager.TYPE_WIFI));
            data.put("active_network", active);

            if (ni.getType() == ConnectivityManager.TYPE_WIFI) {
                data.put("wifi_network", getWifi(c));
            }
        }

        // mobile network details
        data.put("mobile_network", getMobile(tm));

        // kernel network statistics
        data.put("netstat", getNetstat());

        // interfaces config
        Map<String, JSONObject> stats = networkStats();
        data.put("ifconfig", getIfconfig(stats));

        // double check interfaces
        data.put("ip_addr_show", getIpAddr(stats));

        Helpers.sendResultObj(c, "network_state", ts, data);

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json object", jex);
    }
}

From source file:com.sonetel.ui.dialpad.DialerFragment.java

protected boolean isInternetAvail(Context context) {
    connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = connectivityManager.getActiveNetworkInfo();

    if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {
        Log.d(THIS_FILE, "Wifi state is now " + ni.getState().name());
        if (ni.getState() == NetworkInfo.State.CONNECTED) {
            return true;
        }/*from  w w  w.j a  v  a2 s. c  om*/
    }
    if (ni != null && ni.getType() == ConnectivityManager.TYPE_MOBILE) {
        // Any mobile network connected
        if (ni.getState() == NetworkInfo.State.CONNECTED) {
            int subType = ni.getSubtype();

            // 3G (or better)
            if (subType >= TelephonyManager.NETWORK_TYPE_UMTS) {
                return true;
            }

            // GPRS (or unknown)
            if (subType == TelephonyManager.NETWORK_TYPE_GPRS
                    || subType == TelephonyManager.NETWORK_TYPE_UNKNOWN) {
                return true;
            }

            // EDGE
            if (subType == TelephonyManager.NETWORK_TYPE_EDGE) {
                return true;
            }
        }
    }
    if (ni != null && ni.getType() != ConnectivityManager.TYPE_MOBILE
            && ni.getType() != ConnectivityManager.TYPE_WIFI) {
        if (ni.getState() == NetworkInfo.State.CONNECTED) {
            return true;
        }
    }
    return false;

}

From source file:org.brandroid.openmanager.activities.OpenExplorer.java

public boolean isNetworkConnected() {
    ConnectivityManager conman = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (!conman.getBackgroundDataSetting())
        return false;
    NetworkInfo ni = conman.getActiveNetworkInfo();
    if (ni == null)
        return false;
    if (!ni.isAvailable() || !ni.isConnected())
        return false;
    if (ni.getState() == State.CONNECTING)
        return false;
    return true;/*from w  w w.j a va  2 s.  c  o  m*/
}