Example usage for android.net NetworkInfo getType

List of usage examples for android.net NetworkInfo getType

Introduction

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

Prototype

@Deprecated
public int getType() 

Source Link

Document

Reports the type of network to which the info in this NetworkInfo pertains.

Usage

From source file:com.z3r0byte.magistify.Services.OldBackgroundService.java

private Boolean usingWifi() {
    final ConnectivityManager connMgr = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = connMgr.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
}

From source file:com.starup.traven.travelkorea.ImageGridFragment.java

private void updateConnectedFlags() {
    ConnectivityManager connMgr = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
    if (activeInfo != null && activeInfo.isConnected()) {
        wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
        mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
    } else {/* ww w.  ja v a2s .c  o m*/
        wifiConnected = false;
        mobileConnected = false;
    }
}

From source file:edu.utexas.quietplaces.services.PlacesUpdateService.java

/**
 * {@inheritDoc}/*from  w  w w  .  j ava 2s.c o  m*/
 * Checks the battery and connectivity state before removing stale venues
 * and initiating a server poll for new venues around the specified
 * location within the given radius.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    //noinspection deprecation
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = prefs.getBoolean(PlacesConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (!backgroundAllowed && inBackground)
        return;

    // Extract the location and radius around which to conduct our search.
    Location location = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER);
    int radius = PlacesConstants.PLACES_SEARCH_RADIUS;

    Bundle extras = intent.getExtras();
    if (intent.hasExtra(PlacesConstants.EXTRA_KEY_LOCATION)) {
        location = (Location) (extras.get(PlacesConstants.EXTRA_KEY_LOCATION));
        radius = extras.getInt(PlacesConstants.EXTRA_KEY_RADIUS, PlacesConstants.PLACES_SEARCH_RADIUS);
    }

    // Check if we're in a low battery situation.
    IntentFilter batIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent battery = registerReceiver(null, batIntentFilter);
    lowBattery = getIsLowBattery(battery);

    // Check if we're connected to a data network, and if so - if it's a mobile network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    mobileData = activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;

    // If we're not connected, enable the connectivity receiver and disable the location receiver.
    // There's no point trying to poll the server for updates if we're not connected, and the
    // connectivity receiver will turn the location-based updates back on once we have a connection.
    if (!isConnected) {
        Log.w(TAG, "Not connected!");
    } else {
        // If we are connected check to see if this is a forced update (typically triggered
        // when the location has changed).
        boolean doUpdate = intent.getBooleanExtra(PlacesConstants.EXTRA_KEY_FORCEREFRESH, false);

        // If it's not a forced update (for example from the Activity being restarted) then
        // check to see if we've moved far enough, or there's been a long enough delay since
        // the last update and if so, enforce a new update.
        if (!doUpdate) {
            // Retrieve the last update time and place.
            long lastTime = prefs.getLong(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_TIME, Long.MIN_VALUE);
            float lastLat;
            try {
                lastLat = prefs.getFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LAT, Float.MIN_VALUE);
            } catch (ClassCastException e) {
                // handle legacy version
                lastLat = Float.MIN_VALUE;
            }
            float lastLng;
            try {
                lastLng = prefs.getFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LNG, Float.MIN_VALUE);
            } catch (ClassCastException e) {
                lastLng = Float.MIN_VALUE;
            }
            Location lastLocation = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER);
            lastLocation.setLatitude(lastLat);
            lastLocation.setLongitude(lastLng);

            long currentTime = System.currentTimeMillis();
            float distanceMovedSinceLast = lastLocation.distanceTo(location);
            long elapsedTime = currentTime - lastTime;

            Log.i(TAG, "Last Location in places update service: " + lastLocation + " distance to current: "
                    + distanceMovedSinceLast + " - current: " + location);

            if (location == null) {
                Log.w(TAG, "Location is null...");
            }
            // If update time and distance bounds have been passed, do an update.
            else if (lastTime < currentTime - PlacesConstants.MAX_TIME_BETWEEN_PLACES_UPDATE) {
                Log.i(TAG, "Time bounds passed on places update, " + elapsedTime / 1000 + "s elapsed");
                doUpdate = true;
            } else if (distanceMovedSinceLast > PlacesConstants.MIN_DISTANCE_TRIGGER_PLACES_UPDATE) {
                Log.i(TAG, "Distance bounds passed on places update, moved: " + distanceMovedSinceLast
                        + " meters, time elapsed:  " + elapsedTime / 1000 + "s");
                doUpdate = true;
            } else {
                Log.d(TAG, "Time/distance bounds not passed on places update. Moved: " + distanceMovedSinceLast
                        + " meters, time elapsed: " + elapsedTime / 1000 + "s");
            }
        }

        if (location == null) {
            Log.e(TAG, "null location in onHandleIntent");
        } else if (doUpdate) {
            // Refresh the prefetch count for each new location.
            prefetchCount = 0;
            // Remove the old locations - TODO: we flush old locations, but if the next request
            // fails we are left high and dry
            removeOldLocations(location, radius);
            // Hit the server for new venues for the current location.
            refreshPlaces(location, radius, null);

            // Tell the main activity about the new results.
            Intent placesUpdatedIntent = new Intent(Config.ACTION_PLACES_UPDATED);
            LocalBroadcastManager.getInstance(this).sendBroadcast(placesUpdatedIntent);

        } else {
            Log.i(TAG, "Place List is fresh: Not refreshing");
        }

        // Retry any queued checkins.
        /*
                    Intent checkinServiceIntent = new Intent(this, PlaceCheckinService.class);
                    startService(checkinServiceIntent);
        */
    }
    Log.d(TAG, "Place List Download Service Complete");
}

From source file:com.gelakinetic.mtgfam.FamiliarActivity.java

/**
 * Checks the networks state/*w  w  w  .  j  a  va  2 s. com*/
 *
 * @param context         the context where this is being called
 * @param shouldShowToast true, if you want a Toast to be shown indicating a lack of network
 * @return -1 if there is no network connection, or the type of network, like ConnectivityManager.TYPE_WIFI
 */
public static int getNetworkState(Context context, boolean shouldShowToast) {
    try {
        ConnectivityManager conMan = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        for (NetworkInfo ni : conMan.getAllNetworkInfo()) {
            if (ni.isConnected()) {
                return ni.getType();
            }
        }
        if (shouldShowToast) {
            ToastWrapper.makeText(context, R.string.no_network, ToastWrapper.LENGTH_SHORT).show();
        }
        return -1;
    } catch (NullPointerException e) {
        if (shouldShowToast) {
            ToastWrapper.makeText(context, R.string.no_network, ToastWrapper.LENGTH_SHORT).show();
        }
        return -1;
    }
}

From source file:org.odk.collect.android.upload.AutoSendWorker.java

/**
 * Returns whether the currently-available connection type is included in the app-level auto-send
 * settings.//from   w  ww  .j ava  2s  .  c  om
 *
 * @return true if a connection is available and settings specify it should trigger auto-send,
 * false otherwise.
 */
private boolean networkTypeMatchesAutoSendSetting(NetworkInfo currentNetworkInfo) {
    if (currentNetworkInfo == null) {
        return false;
    }

    String autosend = (String) GeneralSharedPreferences.getInstance().get(PreferenceKeys.KEY_AUTOSEND);
    boolean sendwifi = autosend.equals("wifi_only");
    boolean sendnetwork = autosend.equals("cellular_only");
    if (autosend.equals("wifi_and_cellular")) {
        sendwifi = true;
        sendnetwork = true;
    }

    return currentNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI && sendwifi
            || currentNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE && sendnetwork;
}

From source file:org.pidome.client.services.aidl.service.SystemServiceAidl.java

private void setHome() {
    if (prefs != null) {
        if (prefs.getBoolPreference("wifiConnectHomeEnabled", false)) {
            ConnectivityManager connManager = (ConnectivityManager) getSystemService(
                    Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
                if (connectionInfo != null) {
                    String SSID = connectionInfo.getSSID();
                    String BSSID = connectionInfo.getBSSID();
                    if (SSID != null && BSSID != null) {
                        if (SSID.equals(prefs.getStringPreference("wifiConnectSSID",
                                java.util.UUID.randomUUID().toString()))
                                && BSSID.equals(prefs.getStringPreference("wifiConnectBSSID",
                                        java.util.UUID.randomUUID().toString()))) {
                            singleThreadfPipeExecutor.execute((Runnable) () -> {
                                int i = SystemServiceAidl.this.clientCallBackList.beginBroadcast();
                                while (i > 0) {
                                    i--;
                                    try {
                                        clientCallBackList.beginBroadcast();
                                        clientCallBackList.getBroadcastItem(i).updateUserPresence(1);
                                        clientCallBackList.finishBroadcast();
                                    } catch (RemoteException ex) {
                                        Logger.getLogger(SystemServiceAidl.class.getName()).log(Level.SEVERE,
                                                null, ex);
                                    }/* www.jav a 2s  .c o  m*/
                                }
                            });
                            localizationService.setHome(true);
                        } else {
                            localizationService.setHome(false);
                        }
                    }
                }
            } else if (networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                localizationService.setHome(false);
            }
        }
    }
}

From source file:org.zywx.wbpalmstar.platform.push.PushService.java

private void onReceive() {
    final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(CONNECTIVITY_CHANGE_ACTION);
    registerReceiver(new BroadcastReceiver() {

        @Override//from  ww w  . j a  v  a 2  s. com
        public void onReceive(Context context, Intent intent) {
            if ("android.intent.action.SCREEN_OFF".equals(intent.getAction())) {
                if (isTemporary) {
                    sleepTime = 1000 * 60 * 2;
                } else {
                    sleepTime = 1000 * 60 * 15;
                }

                notifiTimer();
            } else if ("android.intent.action.SCREEN_ON".equals(intent.getAction())) {
                if (isTemporary) {
                    sleepTime = 1000 * 30;
                } else {
                    sleepTime = 1000 * 60 * 2;
                }

                notifiTimer();
            }
            if (TextUtils.equals(intent.getAction(), CONNECTIVITY_CHANGE_ACTION)) {

                ConnectivityManager mConnMgr = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                if (mConnMgr != null) {

                    NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo(); // ??
                    if (aActiveInfo != null && aActiveInfo.isConnectedOrConnecting()) {

                        if (!isSend && aActiveInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            // udpReg();
                            // notifiUDPTimer();
                            isSend = true;
                        }
                    } else {
                        isSend = false;
                    }

                } else {
                    isSend = false;
                }

            }

        }
    }, filter);
}

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

@Kroll.getProperty
@Kroll.method//from ww w .  j a  v  a2 s.  com
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:org.eeiiaa.wifi.WifiConnector.java

@Override
    public void onReceive(Context context, Intent intent) {
        // handle stuff related to scanning requested when:
        // normal scan is issued
        // when forgetting a network and re-connecting to a previously configured
        // existing one
        // when connecting and need a scan to verify connection can be established
        Log.i(TAG, "action: " + intent.getAction());
        if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) && (mWaitingScan || mConnecting)) {
            // forgetting current and reconnecting to highest priority existing
            // network

            Log.i(TAG, "ACTION SCAN: mWaitingScan:" + mWaitingScan + " connecting " + mConnecting);

            // normal scan request
            if (mWaitingScan) {
                String json = new String();
                switch (scanResultOption) {
                case GET_ALL:
                    json = getScannedNetworksAllJSON();
                    break;
                case GET_BSSID_ONLY:
                    json = getScannedNetworksJSON();
                    break;
                }//  w ww . ja  v a 2  s  . c  o m
                mScanListener.scanResultsJSON(json);
                mWaitingScan = false;

                // scan is done - unregister
                mContext.unregisterReceiver(this);
                Log.i(TAG, "processing scan results as JSON");

            }

            if (mConnecting && !mWaitingConnection) {
                // look for the network we want to connect to in the scanned results
                ScanResult scannedNet = searchNetwork(mNetssid);
                if (scannedNet == null) {
                    Log.i(TAG, "ssid not found...: " + mNetssid);
                    mConnecting = false;
                    mContext.unregisterReceiver(this);
                    notifyConnectionFailed();
                    return; // didn't find requested network noting to connect
                }

                WifiConfiguration configuredNet = searchConfiguration(scannedNet);
                boolean result_ok = false;

                if (configuredNet != null) {
                    // configuration exits connect to a configured network
                    mWaitingConnection = true;
                    result_ok = Wifi.connectToConfiguredNetwork(mContext, mWifiMgr, configuredNet, false);
                    Log.i(TAG, "configuration exits connect to a configured network");
                } else {
                    // configure and connect to network
                    mWaitingConnection = true;
                    result_ok = Wifi.connectToNewNetwork(mContext, mWifiMgr, scannedNet, mPwd, MAX_OPEN_NETS);
                    Log.i(TAG, "configure and connect to network");
                }

                // failed to connect - unregister and notify
                if (!result_ok) {
                    mContext.unregisterReceiver(this);
                    mWaitingConnection = false;
                    mConnecting = false;
                    Log.e(TAG, "error connecting Wifi.connect returned error");
                    notifyConnectionFailed();
                }
            }
        }

        else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)
                && (mConnected || (mConnecting && mWaitingConnection))) {
            Log.i(TAG, "ACTION CONNECTIVITY: mWaitingScan:" + mWaitingScan + " forgetting: " + forgetting_
                    + " connecting " + mConnecting);

            NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

            if (!mConnected && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
                    && networkInfo.isConnected()) {

                if (mWifiMgr.getConnectionInfo().getSupplicantState() == SupplicantState.COMPLETED) {

                    Log.i(TAG, " getConnectionInfo: " + mWifiMgr.getConnectionInfo() + " getSSID: "
                            + mWifiMgr.getConnectionInfo().getSSID());
                    String connectionSsid = unQuote(mWifiMgr.getConnectionInfo().getSSID());
                    // when phone turns into AP mode, wifimgr returns null...
                    // fail protection for such cases...
                    if (connectionSsid != null) {
                        Log.i(TAG, "mNetssid: |" + mNetssid + "| connectionSsid |" + connectionSsid + "|");
                        if (connectionSsid.equals(mNetssid)) {
                            mConnected = true;
                            mConnecting = false;
                            mWaitingConnection = false;
                            forgetting_ = false;

                            Log.i(TAG, "VERIFIED SUCCESSFUL CONNECTION to: " + mNetssid);
                            // connection done notify - do not unregister to get disconnection detected
                            notifyConnectionListener();
                        }
                    }
                }
            } else if (mConnected && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
                    && !networkInfo.isConnected()) {

                Log.i(TAG, "network is disconnected...");

                // Wifi is disconnected
                mConnected = false;
                mWaitingConnection = false;
                if (mDataListener != null && used_ != null) {
                    used_.updateUsageCounters();
                    transmitted = used_.getWifiTransmitted();
                    received = used_.getWifiReceived();
                }
                // network lost was not expected (when forgetting we expect network to
                // be lost)
                if (!forgetting_) {
                    Log.i(TAG, "network lost " + networkInfo);
                    notifyNetworkLost(networkInfo);
                    mContext.unregisterReceiver(this);
                } else {
                    Log.i(TAG, "network lost when forgetting " + networkInfo);
                }
            }

            Log.i(TAG, "end of CONNECTIVITY_ACTION");
        }

    }

From source file:com.abcvoipsip.ui.SipHome.java

private void asyncSanityCheck() {
    // if(Compatibility.isCompatible(9)) {
    // // We check now if something is wrong with the gingerbread dialer
    // integration
    // Compatibility.getDialerIntegrationState(SipHome.this);
    // }/*w  ww . j av a2s .  c o  m*/

    PackageInfo pinfo = PreferencesProviderWrapper.getCurrentPackageInfos(this);
    if (pinfo != null) {
        if (pinfo.applicationInfo.icon == R.drawable.ic_launcher_nightly) {
            Log.d(THIS_FILE, "Sanity check : we have a nightly build here");
            ConnectivityManager connectivityService = (ConnectivityManager) getSystemService(
                    CONNECTIVITY_SERVICE);
            NetworkInfo ni = connectivityService.getActiveNetworkInfo();
            // Only do the process if we are on wifi
            if (ni != null && ni.isConnected() && ni.getType() == ConnectivityManager.TYPE_WIFI) {
                // Only do the process if we didn't dismissed previously
                NightlyUpdater nu = new NightlyUpdater(this);

                if (!nu.ignoreCheckByUser()) {
                    long lastCheck = nu.lastCheck();
                    long current = System.currentTimeMillis();
                    long oneDay = 43200000; // 12 hours
                    if (current - oneDay > lastCheck) {
                        if (onForeground) {
                            // We have to check for an update
                            UpdaterPopupLauncher ru = nu.getUpdaterPopup(false);
                            if (ru != null && asyncSanityCheker != null) {
                                runOnUiThread(ru);
                            }
                        }
                    }
                }
            }
        }
    }
}