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.mycard.net.network.RequestQueue.java

/***
 * Because our IntentReceiver can run within a different thread,
 * synchronize setting the proxy//from   w ww . ja v  a2s .c  om
 */
@SuppressWarnings("deprecation")
private synchronized void setProxyConfig() {
    NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
    if (info != null && info.getType() == ConnectivityManager.TYPE_WIFI) {
        mProxyHost = null;
    } else {
        String host = System.getProperty("http.proxyHost");
        String portStr = System.getProperty("http.proxyPort");
        int port = Integer.parseInt((portStr != null ? portStr : "-1"));

        if (TextUtils.isEmpty(host) || port <= 0) {
            host = android.net.Proxy.getHost(mContext);
            port = android.net.Proxy.getPort(mContext);
        }

        if (TextUtils.isEmpty(host) || port <= 0) {
            mProxyHost = null;
        } else {
            mActivePool.disablePersistence();
            mProxyHost = new HttpHost(host, port, "http");
        }
    }
}

From source file:syncthing.android.service.SyncthingInstance.java

boolean isConnectedToWifi() {
    NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIMAX;
}

From source file:com.heneryh.aquanotes.io.ApexExecutor.java

/**
 * Execute a {@link HttpGet} request, passing a valid response through
 * to the specified XML parser.  This common method can then be used to parse
 * various kinds of XML feeds./*ww w  . j av  a  2 s .c o m*/
 */
public void executeGet(Uri ctrlUri, DefaultHandler xmlParser) throws HandlerException {

    controllerUri = ctrlUri;
    Cursor cursor = null;

    String username = null;
    String password = null;
    String apexBaseURL = null;
    String apexWANURL = null;
    String apexWiFiURL = null;
    String apexWiFiSID = null;
    String controllerType = null;

    /**
     * Poll the database for facts about this controller
     */
    try {
        cursor = mDbResolver.query(controllerUri, ControllersQuery.PROJECTION, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            username = cursor.getString(ControllersQuery.USER);
            password = cursor.getString(ControllersQuery.PW);
            apexWANURL = cursor.getString(ControllersQuery.WAN_URL);
            apexWiFiURL = cursor.getString(ControllersQuery.LAN_URL);
            apexWiFiSID = cursor.getString(ControllersQuery.WIFI_SSID);
            controllerType = cursor.getString(ControllersQuery.MODEL);
        }
    } catch (SQLException e) {
        throw new HandlerException("Database error getting controller data.");
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    /**
     * Depending on whether or not we are on the 'Home' wifi network we want to use either the
     * WAN or LAN URL.
     * 
     * Uhg, WifiManager stuff below crashes if wifi not enabled so first we have to check if
     * on wifi.
     */
    ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
        /**
         * Get the currently connected SSID, if it matches the 'Home' one then use the local WiFi URL rather than the public one
         */
        WifiManager wm = (WifiManager) mActContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wInfo = wm.getConnectionInfo();

        // somewhere read this was a quoted string but appears not to be
        if (wInfo.getSSID().equalsIgnoreCase(apexWiFiSID)) {
            apexBaseURL = apexWiFiURL;
        } else {
            apexBaseURL = apexWANURL;
        }
    } else {
        apexBaseURL = apexWANURL;
    }

    /**
     * for this function we need to append to the URL.  To be safe we try to catch various
     * forms of URL that might be entered by the user:
     * 
     * check if the "/" was put on the end
     */
    if (!apexBaseURL.endsWith("/")) {
        String tmp = apexBaseURL + "/";
        apexBaseURL = tmp;
    }

    /**
     * check if it starts with an "http://"
     */
    if (!apexBaseURL.toLowerCase().startsWith("http://")) {
        String tmp = "http://" + apexBaseURL;
        apexBaseURL = tmp;
    }

    // oh, we should also check if it ends with an "status.sht" on the end and remove it.

    /**
     * When all cleaned up, add the xml portion of the url to grab the status.
     * 
     * TODO: we tried to make this call handle various xml feeds but this call is hardcoded
     * for the status feed.
     */
    String apexURL = apexBaseURL + "cgi-bin/status.xml";

    final HttpUriRequest request = new HttpGet(apexURL);
    executeWhySeparate(request, xmlParser, username, password);
}

From source file:org.smap.smapTask.android.receivers.NetworkReceiver.java

private boolean interfaceIsEnabled(Context context, NetworkInfo currentNetworkInfo) {
    // make sure autosend is enabled on the given connected interface
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    boolean sendwifi = sharedPreferences.getBoolean(PreferencesActivity.KEY_AUTOSEND_WIFI, false);
    boolean sendnetwork = sharedPreferences.getBoolean(PreferencesActivity.KEY_AUTOSEND_NETWORK, false);

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

From source file:com.heneryh.aquanotes.io.ApexExecutor.java

public void feedCycle(Cursor cursor, int cycleNumber) throws HandlerException {

    /**/*from w w  w  . j  a  va  2  s. co  m*/
     * The cursor contains all of the controller details.
     */
    String lanUri = cursor.getString(ControllersQuery.LAN_URL);
    String wanUri = cursor.getString(ControllersQuery.WAN_URL);
    String user = cursor.getString(ControllersQuery.USER);
    String pw = cursor.getString(ControllersQuery.PW);
    String ssid = cursor.getString(ControllersQuery.WIFI_SSID);
    String model = cursor.getString(ControllersQuery.MODEL);

    String apexBaseURL;

    // Determine if we are on the LAN or WAN and then use appropriate URL

    // Uhg, WifiManager stuff below crashes if wifi not enabled so first we have to check if on wifi
    ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nInfo = cm.getActiveNetworkInfo();

    if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) {
        // Get the currently connected SSID, if it matches the 'Home' one then use the local WiFi URL rather than the public one
        WifiManager wm = (WifiManager) mActContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wInfo = wm.getConnectionInfo();

        // somewhere read this was a quoted string but appears not to be
        if (wInfo.getSSID().equalsIgnoreCase(ssid)) { // the ssid will be quoted in the info class
            apexBaseURL = lanUri;
        } else {
            apexBaseURL = wanUri;
        }
    } else {
        apexBaseURL = wanUri;

    }

    // for this function we need to append to the URL.  I should really
    // check if the "/" was put on the end by the user here to avoid 
    // possible errors.
    if (!apexBaseURL.endsWith("/")) {
        String tmp = apexBaseURL + "/";
        apexBaseURL = tmp;
    }

    // oh, we should also check if it starts with an "http://"
    if (!apexBaseURL.toLowerCase().startsWith("http://")) {
        String tmp = "http://" + apexBaseURL;
        apexBaseURL = tmp;
    }

    // we should also check if it ends with an "status.sht" on the end and remove it.

    // This used to be common for both the Apex and ACiii but during
    // the 4.04 beta Apex release it seemed to have broke and forced
    // me to use status.sht for the Apex.  Maybe it was fixed but I 
    // haven't checked it.
    // edit - this was not needed for the longest while but now that we are pushing just one
    // outlet, the different methods seem to be needed again.  Really not sure why.
    String apexURL;
    if (model.equalsIgnoreCase("AC4")) {
        apexURL = apexBaseURL + "status.sht";
    } else {
        apexURL = apexBaseURL + "cgi-bin/status.cgi";
    }

    //Create credentials for basic auth
    // create a basic credentials provider and pass the credentials
    // Set credentials provider for our default http client so it will use those credentials
    UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw);
    BasicCredentialsProvider cP = new BasicCredentialsProvider();
    cP.setCredentials(AuthScope.ANY, c);
    ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP);

    // Build the POST update which looks like this:
    // form="status"
    // method="post"
    // action="status.sht"
    //
    // name="T5s_state", value="0"   (0=Auto, 1=Man Off, 2=Man On)
    // submit -> name="Update", value="Update"
    // -- or
    // name="FeedSel", value="0"   (0=A, 1=B)
    // submit -> name="FeedCycle", value="Feed"
    // -- or
    // submit -> name="FeedCycle", value="Feed Cancel"

    HttpPost httppost = new HttpPost(apexURL);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

    // Add your data  
    nameValuePairs.add(new BasicNameValuePair("name", "status"));
    nameValuePairs.add(new BasicNameValuePair("method", "post"));
    if (model.equalsIgnoreCase("AC4")) {
        nameValuePairs.add(new BasicNameValuePair("action", "status.sht"));
    } else {
        nameValuePairs.add(new BasicNameValuePair("action", "/cgi-bin/status.cgi"));
    }

    String cycleNumberString = Integer.toString(cycleNumber).trim();
    if (cycleNumber < 4) {
        nameValuePairs.add(new BasicNameValuePair("FeedSel", cycleNumberString));
        nameValuePairs.add(new BasicNameValuePair("FeedCycle", "Feed"));
    } else {
        nameValuePairs.add(new BasicNameValuePair("FeedCycle", "Feed Cancel"));
    }

    nameValuePairs.add(new BasicNameValuePair("Update", "Update"));
    try {

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse resp = mHttpClient.execute(httppost);
        final int status = resp.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            throw new HandlerException(
                    "Unexpected server response " + resp.getStatusLine() + " for " + httppost.getRequestLine());
        }
    } catch (HandlerException e) {
        throw e;
    } catch (ClientProtocolException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    } catch (IOException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    }

}

From source file:ch.ethz.coss.nervousnet.vm.sensors.ConnectivitySensor.java

public void runConnectivitySensor() {
    Log.d(LOG_TAG, "Inside runConnectivitySensor");
    if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(context,
            android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;//from ww  w  .  j  a v a2s .c o  m
    }
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    int networkType = -1;
    boolean isRoaming = false;
    if (isConnected) {
        networkType = activeNetwork.getType();
        isRoaming = activeNetwork.isRoaming();
    }

    String wifiHashId = "";
    int wifiStrength = Integer.MIN_VALUE;

    if (networkType == ConnectivityManager.TYPE_WIFI) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wi = wm.getConnectionInfo();
        StringBuilder wifiInfoBuilder = new StringBuilder();
        wifiInfoBuilder.append(wi.getBSSID());
        wifiInfoBuilder.append(wi.getSSID());
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(wifiInfoBuilder.toString().getBytes());
            wifiHashId = new String(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
        }
        wifiStrength = wi.getRssi();
    }

    byte[] cdmaHashId = new byte[32];
    byte[] lteHashId = new byte[32];
    byte[] gsmHashId = new byte[32];
    byte[] wcdmaHashId = new byte[32];

    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    List<CellInfo> cis = tm.getAllCellInfo();
    if (cis != null) {
        // New method
        for (CellInfo ci : cis) {
            if (ci.isRegistered()) {
                if (ci instanceof CellInfoCdma) {
                    CellInfoCdma cic = (CellInfoCdma) ci;
                    cdmaHashId = generateMobileDigestId(cic.getCellIdentity().getSystemId(),
                            cic.getCellIdentity().getNetworkId(), cic.getCellIdentity().getBasestationId());
                }
                if (ci instanceof CellInfoGsm) {
                    CellInfoGsm cic = (CellInfoGsm) ci;
                    gsmHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(),
                            cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCid());
                }
                if (ci instanceof CellInfoLte) {
                    CellInfoLte cic = (CellInfoLte) ci;
                    lteHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(),
                            cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCi());
                }
                if (ci instanceof CellInfoWcdma) {
                    CellInfoWcdma cic = (CellInfoWcdma) ci;
                    wcdmaHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(),
                            cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCid());
                }
            }
        }
    } else {
        // Legacy method
        CellLocation cl = tm.getCellLocation();
        if (cl instanceof CdmaCellLocation) {
            CdmaCellLocation cic = (CdmaCellLocation) cl;
            cdmaHashId = generateMobileDigestId(cic.getSystemId(), cic.getNetworkId(), cic.getBaseStationId());
        }
        if (cl instanceof GsmCellLocation) {
            GsmCellLocation cic = (GsmCellLocation) cl;
            gsmHashId = generateMobileDigestId(cic.getLac(), 0, cic.getCid());
        }
    }

    StringBuilder mobileHashBuilder = new StringBuilder();
    mobileHashBuilder.append(new String(cdmaHashId));
    mobileHashBuilder.append(new String(lteHashId));
    mobileHashBuilder.append(new String(gsmHashId));
    mobileHashBuilder.append(new String(wcdmaHashId));

    dataReady(new ConnectivityReading(System.currentTimeMillis(), isConnected, networkType, isRoaming,
            wifiHashId, wifiStrength, mobileHashBuilder.toString()));

}

From source file:com.android.settings.cyanogenmod.LtoService.java

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

    if (info == null || !info.isConnected()) {
        if (ALOGV)
            Log.v(TAG, "No network connection is available for LTO download");
    } else {/* w ww.  j  ava 2 s. co  m*/
        boolean wifiOnly = prefs.getBoolean(LocationSettings.KEY_GPS_DOWNLOAD_DATA_WIFI_ONLY, true);
        if (wifiOnly && info.getType() != ConnectivityManager.TYPE_WIFI) {
            if (ALOGV) {
                Log.v(TAG, "Active network is of type " + info.getTypeName() + ", but Wifi only was selected");
            }
            return false;
        }
    }

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

    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:com.heneryh.aquanotes.io.ApexExecutor.java

public void updateOutlet(Cursor cursor, String outletName, int position) throws HandlerException {

    /**//from w  w  w  .  j  a v  a 2 s.c  om
     * The cursor contains all of the controller details.
     */
    String lanUri = cursor.getString(ControllersQuery.LAN_URL);
    String wanUri = cursor.getString(ControllersQuery.WAN_URL);
    String user = cursor.getString(ControllersQuery.USER);
    String pw = cursor.getString(ControllersQuery.PW);
    String ssid = cursor.getString(ControllersQuery.WIFI_SSID);
    String model = cursor.getString(ControllersQuery.MODEL);

    // Uhg, WifiManager stuff below crashes in AVD if wifi not enabled so first we have to check if on wifi
    ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nInfo = cm.getActiveNetworkInfo();
    String apexBaseURL;

    if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) {
        // Get the currently connected SSID, if it matches the 'Home' one then use the local WiFi URL rather than the public one
        WifiManager wm = (WifiManager) mActContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wInfo = wm.getConnectionInfo();

        // somewhere read this was a quoted string but appears not to be
        if (wInfo.getSSID().equalsIgnoreCase(ssid)) { // the ssid will be quoted in the info class
            apexBaseURL = lanUri;
        } else {
            apexBaseURL = wanUri;
        }
    } else {
        apexBaseURL = wanUri;

    }

    // for this function we need to append to the URL.  I should really
    // check if the "/" was put on the end by the user here to avoid 
    // possible errors.
    if (!apexBaseURL.endsWith("/")) {
        String tmp = apexBaseURL + "/";
        apexBaseURL = tmp;
    }

    // oh, we should also check if it starts with an "http://"
    if (!apexBaseURL.toLowerCase().startsWith("http://")) {
        String tmp = "http://" + apexBaseURL;
        apexBaseURL = tmp;
    }

    // oh, we should also check if it ends with an "status.sht" on the end and remove it.

    // This used to be common for both the Apex and ACiii but during
    // the 4.04 beta Apex release it seemed to have broke and forced
    // me to use status.sht for the Apex.  Maybe it was fixed but I 
    // haven't checked it.
    // edit - this was not needed for the longest while but now that we are pushing just one
    // outlet, the different methods seem to be needed again.  Really not sure why.
    String apexURL;
    if (model.equalsIgnoreCase("AC4")) {
        apexURL = apexBaseURL + "status.sht";
    } else {
        apexURL = apexBaseURL + "cgi-bin/status.cgi";
    }

    //Create credentials for basic auth
    // create a basic credentials provider and pass the credentials
    // Set credentials provider for our default http client so it will use those credentials
    UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw);
    BasicCredentialsProvider cP = new BasicCredentialsProvider();
    cP.setCredentials(AuthScope.ANY, c);
    ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP);

    // Build the POST update which looks like this:
    // form="status"
    // method="post"
    // action="status.sht"
    //
    // name="T5s_state", value="0"   (0=Auto, 1=Man Off, 2=Man On)
    // submit -> name="Update", value="Update"
    // -- or
    // name="FeedSel", value="0"   (0=A, 1=B)
    // submit -> name="FeedCycle", value="Feed"
    // -- or
    // submit -> name="FeedCycle", value="Feed Cancel"

    HttpPost httppost = new HttpPost(apexURL);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

    // Add your data  
    nameValuePairs.add(new BasicNameValuePair("name", "status"));
    nameValuePairs.add(new BasicNameValuePair("method", "post"));
    if (model.equalsIgnoreCase("AC4")) {
        nameValuePairs.add(new BasicNameValuePair("action", "status.sht"));
    } else {
        nameValuePairs.add(new BasicNameValuePair("action", "/cgi-bin/status.cgi"));
    }

    String pendingStateS = String.valueOf(position);
    nameValuePairs.add(new BasicNameValuePair(outletName + "_state", pendingStateS));

    nameValuePairs.add(new BasicNameValuePair("Update", "Update"));
    try {

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse resp = mHttpClient.execute(httppost);
        final int status = resp.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            throw new HandlerException(
                    "Unexpected server response " + resp.getStatusLine() + " for " + httppost.getRequestLine());
        }
    } catch (HandlerException e) {
        throw e;
    } catch (ClientProtocolException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    } catch (IOException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    }

}

From source file:de.stadtrallye.rallyesoft.services.UploadService.java

private void updateNetworkStatus() {
    NetworkInfo activeNetwork = connection.getActiveNetworkInfo();
    conn_available = activeNetwork.isConnected();

    switch (activeNetwork.getType()) {
    case (ConnectivityManager.TYPE_WIFI):
        conn_metered = false;//from ww w. java2  s. c  om
        conn_slow = false;
        break;
    case (ConnectivityManager.TYPE_MOBILE): {
        conn_metered = true;
        switch (telephony.getNetworkType()) {
        case (TelephonyManager.NETWORK_TYPE_LTE | TelephonyManager.NETWORK_TYPE_HSPAP
                | TelephonyManager.NETWORK_TYPE_HSPA)://TODO more + check
            conn_slow = false;
            break;
        case (TelephonyManager.NETWORK_TYPE_EDGE | TelephonyManager.NETWORK_TYPE_GPRS):
            conn_slow = true;
            break;
        default:
            conn_slow = false;
            break;
        }
        break;
    }
    default:
        conn_metered = false;
        conn_slow = false;
        break;
    }
    Log.d(THIS,
            "Network: available: " + conn_available + ", metered: " + conn_metered + ", slow: " + conn_slow);
}

From source file:org.ocs.android.agent.service.OCSAgentService.java

private boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        if (mOcssetting.getAutoModeNetwork() == AUTOMODE_NOROAMING && !netInfo.isRoaming()) {
            return true; // no roaming
        }/*ww w  . ja  v a  2  s .co  m*/
        if (mOcssetting.getAutoModeNetwork() == AUTOMODE_ANY) {
            return true; // any network (including roaming)
        }
        if (mOcssetting.getAutoModeNetwork() == AUTOMODE_WIFI
                && netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true; // wifi only
        }
    }
    return false;
}