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:etsii_upm.obdii.EnviarService.java

private void gestionThread() {

    NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    if (mNetworkInfo == null) {
        // Pruebas :
        // consolaUpdate("iReceive: sin conexion a internet");

        if (rThread) {
            enviarThread.interrupt();// ww w.j av  a  2 s.c  om
            rThread = false;
            consolaUpdate(this.getString(R.string.no_enviamos));
        }

        return;
    } else {

        if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            // Pruebas :
            // consolaUpdate("iReceive: conexion WIFI network");

            if (!rThread) {
                enviarThread = new EnviarThread(mHandler);
                enviarThread.start();
                rThread = true;
                consolaUpdate(this.getString(R.string.enviamos));
            }

        } else if (mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            // Pruebas :
            // consolaUpdate("iReceive: conexion MOBILE");

            if (enviarCon3g) {
                if (!rThread) {
                    enviarThread = new EnviarThread(mHandler);
                    enviarThread.start();
                    rThread = true;
                    consolaUpdate(this.getString(R.string.enviamos));
                }
            } else {
                if (rThread) {
                    enviarThread.interrupt();
                    rThread = false;
                    consolaUpdate(this.getString(R.string.no_enviamos));
                }
            }

        }
    }

}

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

private Boolean usingWifi() {
    final ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connMgr == null)
        return false;
    NetworkInfo activeNetwork = connMgr.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
}

From source file:org.mozilla.mozstumbler.client.mapview.MapFragment.java

public void mapNetworkConnectionChanged() {

    FragmentActivity activity = getActivity();

    if (activity == null) {
        return;// ww w. ja  v  a2 s  . c  o  m
    }

    if (activity.getFilesDir() == null) {
        // Not the ideal spot for this check perhaps, but there is no point in checking
        // the network when storage is not available.
        showMapNotAvailableMessage(NoMapAvailableMessage.eNoMapDueToNoAccessibleStorage);
        return;
    }

    mCoverageSetup.getUrlAndInit();

    final ConnectivityManager cm = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo info = cm.getActiveNetworkInfo();
    final boolean hasNetwork = (info != null) && info.isConnected();
    final boolean hasWifi = (info != null) && (info.getType() == ConnectivityManager.TYPE_WIFI);

    if (!hasNetwork) {
        showMapNotAvailableMessage(NoMapAvailableMessage.eNoMapDueToNoInternet);
        return;
    }

    showMapNotAvailableMessage(NoMapAvailableMessage.eHideNoMapMessage);
    setHighBandwidthMap(hasWifi);
}

From source file:com.cyanogenmod.settings.device.LtoDownloadService.java

private boolean shouldDownload(boolean forceDownload) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    boolean hasConnection = false;

    if (info == null || !info.isConnected()) {
        if (ALOGV)
            Log.v(TAG, "No network connection is available for LTO download");
    } else if (forceDownload) {
        if (ALOGV)
            Log.v(TAG, "Download was forced, overriding network type check");
        hasConnection = true;//from  w  w w .j av a2 s . c o m
    } else {
        boolean wifiOnly = prefs.getBoolean(KEY_WIFI_ONLY, WIFI_ONLY_DEFAULT);
        if (wifiOnly && info.getType() != ConnectivityManager.TYPE_WIFI) {
            if (ALOGV) {
                Log.v(TAG, "Active network is of type " + info.getTypeName() + ", but Wifi only was selected");
            }
        } else {
            hasConnection = true;
        }
    }

    if (!hasConnection) {
        return false;
    }
    if (forceDownload) {
        return true;
    }
    if (!prefs.getBoolean(KEY_ENABLED, false)) {
        return false;
    }

    long now = System.currentTimeMillis();
    long lastDownload = LtoDownloadUtils.getLastDownload(this);
    long due = lastDownload + LtoDownloadUtils.getDownloadInterval(this);

    if (ALOGV) {
        Log.v(TAG, "Now " + now + " due " + due + "(" + new Date(due) + ")");
    }

    if (lastDownload != 0 && now < due) {
        if (ALOGV)
            Log.v(TAG, "LTO download is not due yet");
        return false;
    }

    return true;
}

From source file:fr.kwiatkowski.apktrack.service.WebService.java

/**
 * Checks whether the check should be aborted.
 * This may happen depending on user preferences (i.e. WiFi only)
 * @return True if the check should be cancelled.
 *//*www .  j  a v  a  2s .c  om*/
private boolean _check_cancellation() {
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    // If the background checks are not allowed, abort.
    if (!pref.getBoolean(SettingsFragment.KEY_PREF_BACKGROUND_CHECKS, false)) {
        return true;
    }

    // If the user requested it, verify that we are using WiFi before each request.
    if (pref.getBoolean(SettingsFragment.KEY_PREF_WIFI_ONLY, true)) {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info == null) {
            Log.v(MainActivity.TAG, "Aborting automatic checks because no network is currently active.");
            return true;
        } else if (info.getType() != ConnectivityManager.TYPE_WIFI) {
            Log.v(MainActivity.TAG, "Aborting automatic checks over data due to user preferences.");
            return true;
        }
    }
    return false;
}

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

/**
 * Updates all cell data.//w ww  .jav a  2s.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
            Log.w(TAG, "Permission not granted, TelephonyManager#getAllCellInfo() failed");
        }
    }

    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
        Log.w(TAG, "Permission not granted, cannot retrieve cell location");
    }

    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");
    }

    updateNeighboringCellInfo();

    showCells();
}

From source file:at.alladin.rmbt.android.main.RMBTMainActivity.java

/**
 * /*from www.j  ava 2 s  .  c  o m*/
 * @param context
 * @return
 */
public static boolean isNetworkAvailable(Context context) {
    boolean isMobile = false, isWifi = false;

    try {
        NetworkInfo[] infoAvailableNetworks = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getAllNetworkInfo();

        if (infoAvailableNetworks != null) {
            for (NetworkInfo network : infoAvailableNetworks) {

                if (network.getType() == ConnectivityManager.TYPE_WIFI) {
                    if (network.isConnected() && network.isAvailable())
                        isWifi = true;
                }
                if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
                    if (network.isConnected() && network.isAvailable())
                        isMobile = true;
                }
            }
        }

        return isMobile || isWifi;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.mozilla.gecko.updater.UpdateService.java

private File downloadUpdatePackage(UpdateInfo info, boolean overwriteExisting) {
    URL url = null;/* w  w  w .  jav a2 s. c  o  m*/
    try {
        url = info.uri.toURL();
    } catch (java.net.MalformedURLException e) {
        Log.e(LOGTAG, "failed to read URL: ", e);
        return null;
    }

    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    path.mkdirs();
    String fileName = new File(url.getFile()).getName();
    File downloadFile = new File(path, fileName);

    if (!overwriteExisting && info.buildID.equals(getLastBuildID()) && downloadFile.exists()) {
        // The last saved buildID is the same as the one for the current update. We also have a file
        // already downloaded, so it's probably the package we want. Verify it to be sure and just
        // return that if it matches.

        if (verifyDownloadedPackage(downloadFile)) {
            Log.i(LOGTAG, "using existing update package");
            return downloadFile;
        } else {
            // Didn't match, so we're going to download a new one.
            downloadFile.delete();
        }
    }

    if (!info.buildID.equals(getLastBuildID())) {
        // Delete the previous package when a new version becomes available.
        deleteUpdatePackage(getLastFileName());
    }

    Log.i(LOGTAG, "downloading update package");
    sendCheckUpdateResult(CheckUpdateResult.DOWNLOADING);

    OutputStream output = null;
    InputStream input = null;

    mDownloading = true;
    mCancelDownload = false;
    showDownloadNotification(downloadFile);

    try {
        NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected() && netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            mWifiLock.acquire();
        }

        URLConnection conn = openConnectionWithProxy(info.uri);
        int length = conn.getContentLength();

        output = new BufferedOutputStream(new FileOutputStream(downloadFile));
        input = new BufferedInputStream(conn.getInputStream());

        byte[] buf = new byte[BUFSIZE];
        int len = 0;

        int bytesRead = 0;
        int lastNotify = 0;

        while ((len = input.read(buf, 0, BUFSIZE)) > 0 && !mCancelDownload) {
            output.write(buf, 0, len);
            bytesRead += len;
            // Updating the notification takes time so only do it every 1MB
            if (bytesRead - lastNotify > 1048576) {
                mBuilder.setProgress(length, bytesRead, false);
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                lastNotify = bytesRead;
            }
        }

        mNotificationManager.cancel(NOTIFICATION_ID);

        // if the download was canceled by the user
        // delete the update package
        if (mCancelDownload) {
            Log.i(LOGTAG, "download canceled by user!");
            downloadFile.delete();

            return null;
        } else {
            Log.i(LOGTAG, "completed update download!");
            return downloadFile;
        }
    } catch (Exception e) {
        downloadFile.delete();
        showDownloadFailure();

        Log.e(LOGTAG, "failed to download update: ", e);
        return null;
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (java.io.IOException e) {
        }

        try {
            if (output != null)
                output.close();
        } catch (java.io.IOException e) {
        }

        mDownloading = false;

        if (mWifiLock.isHeld()) {
            mWifiLock.release();
        }
    }
}

From source file:de.tap.easy_xkcd.utils.PrefHelper.java

public boolean isWifi(Context context) {
    if (context == null) {
        Log.e("error", "context null");
        return true;
    }//from  w  ww .j ava  2  s .c  om
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}

From source file:layout.FragmentBoardItemList.java

private void getThumbnail(final BoardItem bi) {
    bi.downloadingThumb = true;//from   ww w.  j  ava2 s. co  m
    ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    boolean usingWifi = (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);

    ContextWrapper cw = new ContextWrapper(getActivity().getApplicationContext());
    File directory = cw.getDir("thumbs", Context.MODE_PRIVATE);
    if (!directory.exists()) {
        directory.mkdir();
    }
    final File mypath;
    if (bi.youtubeLink) {
        mypath = new File(directory, currentBoard.getBoardDir() + "_" + bi.youtubeID);
    } else {
        mypath = new File(directory, currentBoard.getBoardDir() + "_" + bi.getThumb());
    }

    if (mypath.exists()) {
        try {
            Bitmap b = BitmapFactory.decodeStream(new FileInputStream(mypath));
            bi.setThumbBitmap(Bitmap.createScaledBitmap(b, 128, 128, false));
            listViewAdapter.notifyDataSetChanged();
            Log.i("getThumb", bi.getThumb() + " from cache");
            return;
        } catch (Exception e) {
            e.printStackTrace();
            displayError(e.getMessage());
        }
    }
    if (settings.getBoolean("setting_downloadOnlyWithWifi", false) == true && !usingWifi) {
        Log.i("getThumb", "Not using wifi");
        return;
    }
    String imgURL = "http://bienvenidoainternet.org/" + bi.getParentBoard().getBoardDir() + "/thumb/"
            + bi.getThumb();
    if (bi.getThumb().startsWith("http")) {
        imgURL = bi.getThumb();
    }
    Ion.with(getContext()).load(imgURL).setLogging("getThumbnail", Log.INFO).asBitmap()
            .setCallback(new FutureCallback<Bitmap>() {
                @Override
                public void onCompleted(Exception e, Bitmap result) {
                    if (e != null) {
                        displayError(e.getMessage());
                        e.printStackTrace();
                    } else {
                        bi.setThumbBitmap(Bitmap.createScaledBitmap(result, 128, 128, false));
                        listViewAdapter.notifyDataSetChanged();
                        FileOutputStream out;
                        try {
                            out = new FileOutputStream(mypath);
                            result.compress(Bitmap.CompressFormat.PNG, 100, out);
                            if (out != null) {
                                out.close();
                            }
                            Log.v("getThumb", bi.getThumb() + " saved.");
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            });
}