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:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java

/**
 * @return true if the current connected network is wifi
 *///from   w w w .j  a v  a  2 s. c om
protected boolean isNetworkWifi() {
    ConnectivityManager connectivityManager = (ConnectivityManager) mContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            int wifiState = networkInfo.getType();
            return (wifiState == ConnectivityManager.TYPE_WIFI);
        }
    }
    return false;
}

From source file:com.vonglasow.michael.satstat.RadioSectionFragment.java

/**
 * Updates all cell data.//from  ww  w .j  a  v  a  2 s .c  o  m
 * 
 * This method is called whenever any change in the cell environment (cells in view or signal
 * strengths) is signaled, e.g. by a call to a {@link android.telephony.PhoneStateListener}. The
 * arguments of this method should be filled with the data passed to the
 * {@link android.telephony.PhoneStateListener} where possible, and null passed for all others.
 * 
 * To force an update of all cell data, simply call this method with each argument set to null.
 * 
 * If any of the arguments is null, this method will try to obtain that data by querying
 * {@link android.telephony.TelephonyManager}. The only exception is {@code signalStrength}, which
 * will not be explicitly queried if missing.
 * 
 * It will first process {@code aCellInfo}, then {@code aLocation}, querying current values from
 * {@link android.telephony.TelephonyManager} if one of these arguments is null. Next it will process
 * {@code signalStrength}, if supplied, and eventually obtain neighboring cells by calling
 * {@link android.telephony.TelephonyManager#getNeighboringCellInfo()} and process these. Eventually
 * it will refresh the list of cells.
 * 
 * @param aLocation The {@link android.telephony.CellLocation} reported by a
 * {@link android.telephony.PhoneStateListener}. If null, the current value will be queried.
 * @param aSignalStrength The {@link android.telephony.SignalStrength} reported by a
 * {@link android.telephony.PhoneStateListener}. If null, the signal strength of the serving cell
 * will either be taken from {@code aCellInfo}, if available, or not be updated at all.
 * @param aCellInfo A list of {@link android.telephony.CellInfo} instances reported by a
 * {@link android.telephony.PhoneStateListener}. If null, the current value will be queried.
 */
@SuppressLint("NewApi")
public void updateCellData(CellLocation aLocation, SignalStrength signalStrength, List<CellInfo> aCellInfo) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        try {
            /*
             * CellInfo requires API 17+ and should in theory return all cells in view. In practice,
             * some devices do not implement it or return only a partial list. On some devices,
             * PhoneStateListener#onCellInfoChanged() will fire but always receive a null argument.
             */
            List<CellInfo> cellInfo = (aCellInfo != null) ? aCellInfo
                    : mainActivity.telephonyManager.getAllCellInfo();
            mCellsGsm.updateAll(cellInfo);
            mCellsCdma.updateAll(cellInfo);
            mCellsLte.updateAll(cellInfo);
        } catch (SecurityException e) {
            // Permission not granted, can't retrieve cell data
        }
    }

    try {
        /*
         * CellLocation should return the serving cell, unless it is LTE (in which case it should
         * return null). In practice, however, some devices do return LTE cells. The approach of
         * this method does not work well for devices with multiple radios.
         */
        CellLocation location = (aLocation != null) ? aLocation
                : mainActivity.telephonyManager.getCellLocation();
        String networkOperator = mainActivity.telephonyManager.getNetworkOperator();
        mCellsGsm.removeSource(CellTower.SOURCE_CELL_LOCATION);
        mCellsCdma.removeSource(CellTower.SOURCE_CELL_LOCATION);
        mCellsLte.removeSource(CellTower.SOURCE_CELL_LOCATION);
        if (location instanceof GsmCellLocation) {
            if (mLastNetworkGen < 4) {
                mServingCell = mCellsGsm.update(networkOperator, (GsmCellLocation) location);
                if ((mServingCell.getDbm() == CellTower.DBM_UNKNOWN) && (mServingCell instanceof CellTowerGsm))
                    ((CellTowerGsm) mServingCell).setAsu(mLastCellAsu);
            } else {
                mServingCell = mCellsLte.update(networkOperator, (GsmCellLocation) location);
                if (mServingCell.getDbm() == CellTower.DBM_UNKNOWN)
                    ((CellTowerLte) mServingCell).setAsu(mLastCellAsu);
            }
        } else if (location instanceof CdmaCellLocation) {
            mServingCell = mCellsCdma.update((CdmaCellLocation) location);
            if (mServingCell.getDbm() == CellTower.DBM_UNKNOWN)
                ((CellTowerCdma) mServingCell).setDbm(mLastCellDbm);
        }
        networkTimehandler.removeCallbacks(networkTimeRunnable);
    } catch (SecurityException e) {
        // Permission not granted, can't retrieve cell data
    }

    if ((mServingCell == null) || (mServingCell.getGeneration() <= 0)) {
        if ((mLastNetworkGen != 0) && (mServingCell != null))
            mServingCell.setGeneration(mLastNetworkGen);
        NetworkInfo netinfo = mainActivity.connectivityManager.getActiveNetworkInfo();
        if ((netinfo == null) || (netinfo.getType() < ConnectivityManager.TYPE_MOBILE_MMS)
                || (netinfo.getType() > ConnectivityManager.TYPE_MOBILE_HIPRI)) {
            networkTimehandler.postDelayed(networkTimeRunnable, NETWORK_REFRESH_DELAY);
        }
    } else if (mServingCell != null) {
        mLastNetworkGen = mServingCell.getGeneration();
    }

    if ((signalStrength != null) && (mServingCell != null)) {
        int pt = mainActivity.telephonyManager.getPhoneType();
        if (pt == PHONE_TYPE_GSM) {
            mLastCellAsu = signalStrength.getGsmSignalStrength();
            updateNeighboringCellInfo();
            if (mServingCell instanceof CellTowerGsm)
                ((CellTowerGsm) mServingCell).setAsu(mLastCellAsu);
            else
                Log.w(MainActivity.class.getSimpleName(),
                        "Got SignalStrength for PHONE_TYPE_GSM but serving cell is not GSM");
        } else if (pt == PHONE_TYPE_CDMA) {
            mLastCellDbm = signalStrength.getCdmaDbm();
            if ((mServingCell != null) && (mServingCell instanceof CellTowerCdma))
                mServingCell.setDbm(mLastCellDbm);
            else
                Log.w(MainActivity.class.getSimpleName(),
                        "Got SignalStrength for PHONE_TYPE_CDMA but serving cell is not CDMA");
        } else
            Log.w(MainActivity.class.getSimpleName(),
                    String.format("Got SignalStrength for unknown phone type (%d)", pt));
    } else if (mServingCell == null) {
        Log.w(MainActivity.class.getSimpleName(), "Got SignalStrength but serving cell is null");
    }

    try {
        /*
         * NeighboringCellInfo is not supported on some devices and will return no data. It lists
         * only GSM and successors' cells, but not CDMA cells.
         */
        List<NeighboringCellInfo> neighboringCells = mainActivity.telephonyManager.getNeighboringCellInfo();
        String networkOperator = mainActivity.telephonyManager.getNetworkOperator();
        mCellsGsm.updateAll(networkOperator, neighboringCells);
        mCellsLte.updateAll(networkOperator, neighboringCells);
    } catch (SecurityException e) {
        // Permission not granted, can't retrieve cell data
    }

    showCells();
}

From source file:com.drinviewer.droiddrinviewer.DrinViewerBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if (networkInfo.isConnected()) {
            /**/*from w  w  w .j a  va  2s.  c  o  m*/
             * WiFi is connected, get its broadcast 
             * address and start the discovery process
             * repeated at a fixed time interval
             */
            wifiBroadcastAddress = getWiFiBroadcastAddress(context);
            startAlarmRepeater(context);
        } else {
            wifiBroadcastAddress = null;
        }
    } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && !networkInfo.isConnected()) {
            /**
             * WiFi is disconnected, stop the discovery
             * process repeating, it would be a waste of resources
             */
            wifiBroadcastAddress = null;
            stopAlarmRepeater(context);
        }
    } else if (intent.getAction().equals(context.getResources().getString(R.string.broadcast_startdiscovery))
            || intent.getAction()
                    .equals(context.getResources().getString(R.string.broadcast_cleanhostcollection))) {

        boolean startService = true;
        /**
         * Calls the DiscoverServerService asking to do a discovery
         * or a clean host collection by simply forwarding the received action
         */
        Intent service = new Intent(context, DiscoverServerService.class);
        service.setAction(intent.getAction());

        if (intent.getAction().equals(context.getResources().getString(R.string.broadcast_startdiscovery))) {

            ConnectivityManager connManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            wifiBroadcastAddress = (mWifi.isConnected()) ? getWiFiBroadcastAddress(context) : null;
            startService = wifiBroadcastAddress != null;
            service.putExtra("wifiBroadcastAddress", wifiBroadcastAddress);
        }

        if (startService)
            startWakefulService(context, service);

        if (intent.getBooleanExtra("stopservice", false)) {
            context.stopService(service);
        }
    } else if (intent.getAction()
            .equals(context.getResources().getString(R.string.broadcast_startalarmrepeater))) {
        /**
         * start the alarm repeater only if WiFi is connected already
         * used by ServerListFragment.onServiceConnected method to start the discovery
         * if the application is launched being already connected to a WiFi network
         */
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mWifi.isConnected()) {
            // if we're called from the activity, try to get a broadcast address
            if (intent.getBooleanExtra("forcegetbroadcast", false))
                wifiBroadcastAddress = getWiFiBroadcastAddress(context);
            startAlarmRepeater(context);
        } else {
            wifiBroadcastAddress = null;
        }
    } else if (intent.getAction()
            .equals(context.getResources().getString(R.string.broadcast_stopalarmrepeater))) {
        /**
         *  stop the alarm repeater. period.
         *  used by DrinViewerApplication.onTerminate method
         */
        wifiBroadcastAddress = null;
        stopAlarmRepeater(context);
    }
}

From source file:com.sip.pwc.sipphone.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);
    // }//from  w  w  w  .  j  a v a 2s. c o m

    // Nightly build check
    if (NightlyUpdater.isNightlyBuild(this)) {
        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
                        NightlyUpdater.UpdaterPopupLauncher ru = nu.getUpdaterPopup(false);
                        if (ru != null && asyncSanityChecker != null) {
                            runOnUiThread(ru);
                        }
                    }
                }
            }
        }
    }

    applyWarning(WarningUtils.WARNING_PRIVILEGED_INTENT,
            WarningUtils.shouldWarnPrivilegedIntent(this, prefProviderWrapper));
    applyWarning(WarningUtils.WARNING_NO_STUN, WarningUtils.shouldWarnNoStun(prefProviderWrapper));
    applyWarning(WarningUtils.WARNING_VPN_ICS, WarningUtils.shouldWarnVpnIcs(prefProviderWrapper));
    applyWarning(WarningUtils.WARNING_SDCARD, WarningUtils.shouldWarnSDCard(this, prefProviderWrapper));
}

From source file:org.awesomeapp.messenger.service.RemoteImService.java

void networkStateChanged(NetworkInfo networkInfo, NetworkConnectivityReceiver.State networkState) {

    int networkType = networkInfo != null ? networkInfo.getType() : -1;

    debug("networkStateChanged: type=" + networkInfo + " state=" + networkState);

    boolean networkChanged = false;

    if (mNetworkType != networkType || mNetworkState != networkState) {

        mNetworkState = networkState;//from w  ww .  ja va 2  s.  c o  m
        mNetworkType = networkType;

        networkChanged = true;

        for (ImConnectionAdapter conn : mConnections.values())
            conn.networkTypeChanged();

        //update the notification
        if (mNotifyBuilder != null) {
            String message = "";

            if (!isNetworkAvailable()) {
                message = getString(R.string.error_suspended_connection);
                mNotifyBuilder.setSmallIcon(R.drawable.notify_zom);
            } else {
                message = getString(R.string.app_unlocked);
                mNotifyBuilder.setSmallIcon(R.drawable.notify_zom);
            }

            mNotifyBuilder.setContentText(message);
            // Because the ID remains unchanged, the existing notification is
            // updated.
            mNotifyManager.notify(notifyId, mNotifyBuilder.build());

        }

    }

    if (isNetworkAvailable()) {
        boolean reConnd = reestablishConnections();

        if (!reConnd) {
            if (mNeedCheckAutoLogin) {
                mNeedCheckAutoLogin = !autoLogin();
            }
        }

    } else {
        suspendConnections();
    }
}

From source file:info.guardianproject.otr.app.im.service.RemoteImService.java

void networkStateChanged(NetworkInfo networkInfo, NetworkConnectivityListener.State networkState) {

    mNetworkType = networkInfo != null ? networkInfo.getType() : -1;

    debug("networkStateChanged: type=" + networkInfo + " state=" + networkState);

    if (mNetworkState != networkState) {

        mNetworkState = networkState;//from   w  ww . j a va  2  s  . co  m

        for (ImConnectionAdapter conn : mConnections.values())
            conn.networkTypeChanged();

        //update the notification
        if (mNotifyBuilder != null) {
            String message = "";

            if (!isNetworkAvailable()) {
                message = getString(R.string.error_suspended_connection);
                mNotifyBuilder.setSmallIcon(R.drawable.notify_chatsecure_offline);
            } else {
                message = getString(R.string.app_unlocked);
                mNotifyBuilder.setSmallIcon(R.drawable.notify_chatsecure);
            }

            mNotifyBuilder.setContentText(message);
            // Because the ID remains unchanged, the existing notification is
            // updated.
            mNotifyManager.notify(notifyId, mNotifyBuilder.build());

        }

    }

    if (isNetworkAvailable()) {
        boolean reConnd = reestablishConnections();

        if (!reConnd) {
            if (mNeedCheckAutoLogin) {
                mNeedCheckAutoLogin = false;
                autoLogin();
            }
        }

    } else {
        suspendConnections();
    }

}

From source file:com.zhongsou.souyue.activity.SplashActivity.java

protected boolean parseNetStatus(NetworkInfo ni) {
    if (ni == null)
        throw new RuntimeException("ni can not be null");
    if (highSpeed.contains(ni.getSubtype()) || ni.getType() == ConnectivityManager.TYPE_WIFI)
        return true;
    return false;
}

From source file:org.qeo.android.service.QeoService.java

private void configureNetworkSettings(NetworkInfo activeNetworkInfo) {
    if (activeNetworkInfo != null) {
        switch (activeNetworkInfo.getType()) {
        case ConnectivityManager.TYPE_ETHERNET:
        case ConnectivityManager.TYPE_WIFI:
            // only enable UDP on WIFI or ETHERNET
            LOG.fine("enable UDP");
            NativeQeo.setUdpMode(true);/*from w  w  w.  j ava2s  .c om*/
            break;
        default:
            // disable UDP
            LOG.fine("disable UDP");
            NativeQeo.setUdpMode(false);
            break;
        }
    }
}

From source file:com.csipsimple.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);
    // }/*from w ww.  j av  a 2s. com*/

    // Nightly build check
    if (NightlyUpdater.isNightlyBuild(this)) {
        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 && asyncSanityChecker != null) {
                            runOnUiThread(ru);
                        }
                    }
                }
            }
        }
    }

    applyWarning(WarningUtils.WARNING_PRIVILEGED_INTENT,
            WarningUtils.shouldWarnPrivilegedIntent(this, prefProviderWrapper));
    applyWarning(WarningUtils.WARNING_NO_STUN, WarningUtils.shouldWarnNoStun(prefProviderWrapper));
    applyWarning(WarningUtils.WARNING_VPN_ICS, WarningUtils.shouldWarnVpnIcs(prefProviderWrapper));
    applyWarning(WarningUtils.WARNING_SDCARD, WarningUtils.shouldWarnSDCard(this, prefProviderWrapper));
}

From source file:tree.love.providers.downloads.DownloadThread.java

private void runInternal() {
    // Skip when download already marked as finished; this download was
    // probably started again while racing with UpdateThread.
    if (DownloadInfo.queryDownloadStatus(mContext.getContentResolver(),
            mInfo.mId) == Downloads.Impl.STATUS_SUCCESS) {
        Log.d(TAG, "Download " + mInfo.mId + " already finished; skipping");
        return;/*  w w w  .jav  a 2  s  . c om*/
    }

    State state = new State(mInfo);
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
    int numFailed = mInfo.mNumFailed;
    String errorMsg = null;

    // final NetworkPolicyManager netPolicy =
    // NetworkPolicyManager.from(mContext);
    final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);

    try {
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
        // wakeLock.setWorkSource(new WorkSource(mInfo.mUid));
        wakeLock.acquire();

        // while performing download, register for rules updates
        // netPolicy.registerListener(mPolicyListener);

        Log.i(Constants.TAG, "Download " + mInfo.mId + " starting");

        // Remember which network this download started on; used to
        // determine if errors were due to network changes.
        final NetworkInfo info = mSystemFacade.getActiveNetworkInfo(mInfo.mUid);
        if (info != null) {
            state.mNetworkType = info.getType();
        }

        // Network traffic on this thread should be counted against the
        // requesting UID, and is tagged with well-known value.
        TrafficStatsCompat.setThreadStatsTag(TrafficStatsCompat.getThreadStatsTag());
        // TrafficStatsCompat.setThreadStatsUid(mInfo.mUid);

        try {
            // TODO: migrate URL sanity checking into client side of API
            state.mUrl = new URL(state.mRequestUri);
        } catch (MalformedURLException e) {
            throw new StopRequestException(STATUS_BAD_REQUEST, e);
        }

        executeDownload(state);

        finalizeDestinationFile(state);
        finalStatus = Downloads.Impl.STATUS_SUCCESS;
    } catch (StopRequestException error) {
        // remove the cause before printing, in case it contains PII
        errorMsg = error.getMessage();
        String msg = "Aborting request for download " + mInfo.mId + ": " + errorMsg;
        Log.w(Constants.TAG, msg);
        if (Constants.LOGV) {
            Log.w(Constants.TAG, msg, error);
        }
        finalStatus = error.getFinalStatus();

        // Nobody below our level should request retries, since we handle
        // failure counts at this level.
        if (finalStatus == STATUS_WAITING_TO_RETRY) {
            throw new IllegalStateException("Execution should always throw final error codes");
        }

        // Some errors should be retryable, unless we fail too many times.
        if (isStatusRetryable(finalStatus)) {
            if (state.mGotData) {
                numFailed = 1;
            } else {
                numFailed += 1;
            }

            if (numFailed < Constants.MAX_RETRIES) {
                final NetworkInfo info = mSystemFacade.getActiveNetworkInfo(mInfo.mUid);
                if (info != null && info.getType() == state.mNetworkType && info.isConnected()) {
                    // Underlying network is still intact, use normal backoff
                    finalStatus = STATUS_WAITING_TO_RETRY;
                } else {
                    // Network changed, retry on any next available
                    finalStatus = STATUS_WAITING_FOR_NETWORK;
                }
            }
        }

        // fall through to finally block
    } catch (Throwable ex) {
        errorMsg = ex.getMessage();
        String msg = "Exception for id " + mInfo.mId + ": " + errorMsg;
        Log.w(Constants.TAG, msg, ex);
        finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (finalStatus == STATUS_SUCCESS) {
            TrafficStatsCompat.incrementOperationCount(1);
        }

        TrafficStatsCompat.clearThreadStatsTag();
        //            TrafficStatsCompat.clearThreadStatsUid();

        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(state, finalStatus, errorMsg, numFailed);

        Log.i(Constants.TAG, "Download " + mInfo.mId + " finished with status "
                + Downloads.Impl.statusToString(finalStatus));

        //            netPolicy.unregisterListener(mPolicyListener);

        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
    }
    mStorageManager.incrementNumDownloadsSoFar();
}