Example usage for android.net ConnectivityManager TYPE_MOBILE

List of usage examples for android.net ConnectivityManager TYPE_MOBILE

Introduction

In this page you can find the example usage for android.net ConnectivityManager TYPE_MOBILE.

Prototype

int TYPE_MOBILE

To view the source code for android.net ConnectivityManager TYPE_MOBILE.

Click Source Link

Document

A Mobile data connection.

Usage

From source file:org.wso2.iot.agent.services.NetworkInfoService.java

/**
 * Network data such as  connection type and signal details can be fetched with this method.
 *
 * @return String representing network details.
 * @throws AndroidAgentException//w w w  . j a  va  2 s. co m
 */
public static String getNetworkStatus() throws AndroidAgentException {
    if (thisInstance == null) {
        Log.e(TAG, "Service not instantiated");
        throw new AndroidAgentException(TAG + " is not started.");
    }
    info = thisInstance.getNetworkInfo();
    String payload = null;
    if (info != null) {
        List<Device.Property> properties = new ArrayList<>();
        Device.Property property = new Device.Property();
        property.setName(Constants.Device.CONNECTION_TYPE);
        property.setValue(info.getTypeName());
        properties.add(property);

        if ((info.isConnected())) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                property = new Device.Property();
                property.setName(Constants.Device.MOBILE_CONNECTION_TYPE);
                property.setValue(info.getSubtypeName());
                properties.add(property);
            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                property = new Device.Property();
                property.setName(Constants.Device.WIFI_SSID);
                // NetworkInfo API of Android seem to add extra "" to SSID, therefore escaping it.
                property.setValue(String.valueOf(thisInstance.getWifiSSID()).replaceAll("\"", ""));
                properties.add(property);

                property = new Device.Property();
                property.setName(Constants.Device.WIFI_SIGNAL_STRENGTH);
                property.setValue(String.valueOf(thisInstance.getWifiSignalStrength()));
                properties.add(property);
            }
        }

        property = new Device.Property();
        property.setName(Constants.Device.MOBILE_SIGNAL_STRENGTH);
        property.setValue(String.valueOf(getCellSignalStrength()));
        properties.add(property);

        try {
            payload = mapper.writeValueAsString(properties);
        } catch (JsonProcessingException e) {
            String errorMsg = "Error occurred while parsing " + "network property property object to json.";
            Log.e(TAG, errorMsg, e);
            throw new AndroidAgentException(errorMsg, e);
        }
    }
    return payload;
}

From source file:android.net.http.cts.ApacheHttpClientTest.java

private void disconnectWifiToConnectToMobile() throws InterruptedException {
    if (mHasWifi && mWifiManager.isWifiEnabled()) {
        ConnectivityActionReceiver connectMobileReceiver = new ConnectivityActionReceiver(
                ConnectivityManager.TYPE_MOBILE, State.CONNECTED);
        ConnectivityActionReceiver disconnectWifiReceiver = new ConnectivityActionReceiver(
                ConnectivityManager.TYPE_WIFI, State.DISCONNECTED);
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        mContext.registerReceiver(connectMobileReceiver, filter);
        mContext.registerReceiver(disconnectWifiReceiver, filter);

        assertTrue(mWifiManager.setWifiEnabled(false));
        assertTrue(disconnectWifiReceiver.waitForStateChange());
        assertTrue(connectMobileReceiver.waitForStateChange());

        mContext.unregisterReceiver(connectMobileReceiver);
        mContext.unregisterReceiver(disconnectWifiReceiver);
    }//from  w w  w  .j a va  2s  .c om
}

From source file:dev.ukanth.ufirewall.InterfaceTracker.java

private static InterfaceDetails getInterfaceDetails(Context context) {
    InterfaceDetails ret = new InterfaceDetails();

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();

    if (info == null || info.isConnected() == false) {
        return ret;
    }//www.  ja  v  a 2s .c o m

    switch (info.getType()) {
    case ConnectivityManager.TYPE_MOBILE:
    case ConnectivityManager.TYPE_MOBILE_DUN:
    case ConnectivityManager.TYPE_MOBILE_HIPRI:
    case ConnectivityManager.TYPE_MOBILE_MMS:
    case ConnectivityManager.TYPE_MOBILE_SUPL:
    case ConnectivityManager.TYPE_WIMAX:
        ret.isRoaming = info.isRoaming();
        ret.netType = ConnectivityManager.TYPE_MOBILE;
        ret.netEnabled = true;
        break;
    case ConnectivityManager.TYPE_WIFI:
    case ConnectivityManager.TYPE_BLUETOOTH:
    case ConnectivityManager.TYPE_ETHERNET:
        ret.netType = ConnectivityManager.TYPE_WIFI;
        ret.netEnabled = true;
        break;
    }
    getTetherStatus(context, ret);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
        OldInterfaceScanner.populateLanMasks(context, ITFS_WIFI, ret);
    } else {
        NewInterfaceScanner.populateLanMasks(context, ITFS_WIFI, ret);
    }

    return ret;
}

From source file:com.just.agentweb.AgentWebUtils.java

public static int checkNetworkType(Context context) {

    int netType = 0;
    //?/* w  w  w .  j  a va2  s .c  o m*/
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    //?NetworkInfo
    @SuppressLint("MissingPermission")
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    if (networkInfo == null) {
        return netType;
    }
    switch (networkInfo.getType()) {
    case ConnectivityManager.TYPE_WIFI:
    case ConnectivityManager.TYPE_WIMAX:
    case ConnectivityManager.TYPE_ETHERNET:
        return 1;

    case ConnectivityManager.TYPE_MOBILE:
        switch (networkInfo.getSubtype()) {
        case TelephonyManager.NETWORK_TYPE_LTE: // 4G
        case TelephonyManager.NETWORK_TYPE_HSPAP:
        case TelephonyManager.NETWORK_TYPE_EHRPD:
            return 2;
        case TelephonyManager.NETWORK_TYPE_UMTS: // 3G
        case TelephonyManager.NETWORK_TYPE_CDMA:
        case TelephonyManager.NETWORK_TYPE_EVDO_0:
        case TelephonyManager.NETWORK_TYPE_EVDO_A:
        case TelephonyManager.NETWORK_TYPE_EVDO_B:
            return 3;

        case TelephonyManager.NETWORK_TYPE_GPRS: // 2G
        case TelephonyManager.NETWORK_TYPE_EDGE:
            return 4;

        default:
            return netType;
        }

    default:

        return netType;
    }

}

From source file:android_network.hetnet.vpn_service.Util.java

public static String getNetworkGeneration(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    return (ni != null && ni.getType() == ConnectivityManager.TYPE_MOBILE
            ? getNetworkGeneration(ni.getSubtype())
            : null);/*w w  w .  jav a2 s.c om*/
}

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

/**
 * {@inheritDoc}//from w w w.j av a  2s  .  co 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:io.lqd.sdk.model.LQDevice.java

private static String getInternetConnectivity(Context context) {
    if (LiquidTools.checkForPermission(permission.ACCESS_NETWORK_STATE, context)) {
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mNetwork = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mWifi != null && mWifi.isConnected()) {
            return "WiFi";
        } else if (mNetwork != null && mNetwork.isConnected()) {
            return "Cellular";
        } else {/*from  w  w w .  j  av a  2 s  .  c o m*/
            return "No Connectivity";
        }
    } else {
        return "No ACCESS_NETWORK_STATE permission";
    }
}

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();//from w  w  w. j  a  va  2  s . co  m
            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.example.qrpoll.MainActivity.java

/**
 * sprawdzenie danych pakietowych//from ww w .  j av  a2  s . co m
 * @return
 */
public boolean checkNetwork() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    return ni.isConnected();
}

From source file:com.ota.updates.utils.Utils.java

public static boolean isMobileNetwork(Context context) {
    boolean isMobileNetwork = false;
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm != null) {
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) {
            isMobileNetwork = activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;
        }/* www  .jav a 2 s.co m*/
    }
    return isMobileNetwork;
}