Example usage for android.location LocationManager NETWORK_PROVIDER

List of usage examples for android.location LocationManager NETWORK_PROVIDER

Introduction

In this page you can find the example usage for android.location LocationManager NETWORK_PROVIDER.

Prototype

String NETWORK_PROVIDER

To view the source code for android.location LocationManager NETWORK_PROVIDER.

Click Source Link

Document

Name of the network location provider.

Usage

From source file:org.mariotaku.twidere.activity.ComposeActivity.java

/**
 * The Location Manager manages location providers. This code searches for
 * the best provider of data (GPS, WiFi/cell phone tower lookup, some other
 * mechanism) and finds the last known location.
 **///w ww.j ava2 s .  c o m
private boolean getLocation() {
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = mLocationManager.getBestProvider(criteria, true);

    if (provider != null) {
        final Location location;
        if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = mLocationManager.getLastKnownLocation(provider);
        }
        if (location == null) {
            mLocationManager.requestLocationUpdates(provider, 0, 0, this);
            setSupportProgressBarIndeterminateVisibility(true);
        }
        mRecentLocation = location != null ? new ParcelableLocation(location) : null;
    } else {
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }
    return provider != null;
}

From source file:org.mariotaku.twidere.activity.ComposeActivity.java

private void send() {
    final String text = mEditText != null ? parseString(mEditText.getText()) : null;
    if (isEmpty(text) || isFinishing())
        return;//  ww w .j av  a  2s  .  c  om
    final boolean has_media = (mIsImageAttached || mIsPhotoAttached) && mImageUri != null;
    final boolean attach_location = mPreferences.getBoolean(PREFERENCE_KEY_ATTACH_LOCATION, false);
    if (mRecentLocation == null && attach_location) {
        final Location location;
        if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = null;
        }
        mRecentLocation = location != null ? new ParcelableLocation(location) : null;
    }
    mTwitterWrapper.updateStatus(mAccountIds, text, attach_location ? mRecentLocation : null, mImageUri,
            mInReplyToStatusId, has_media && mIsPossiblySensitive, mIsPhotoAttached && !mIsImageAttached);
    setResult(Activity.RESULT_OK);
    finish();
}

From source file:org.getlantern.firetweet.activity.support.ComposeActivity.java

/**
 * The Location Manager manages location providers. This code searches for
 * the best provider of data (GPS, WiFi/cell phone tower lookup, some other
 * mechanism) and finds the last known location.
 *//*from  w  w w .j a  va 2s  .  com*/
private boolean startLocationUpdateIfEnabled() {
    final LocationManager lm = mLocationManager;
    final boolean attachLocation = mPreferences.getBoolean(KEY_ATTACH_LOCATION, false);
    if (!attachLocation) {
        lm.removeUpdates(this);
        return false;
    }
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = lm.getBestProvider(criteria, true);
    if (provider != null) {
        mLocationText.setText(R.string.getting_location);
        lm.requestLocationUpdates(provider, 0, 0, this);
        final Location location;
        if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = lm.getLastKnownLocation(provider);
        }
        if (location != null) {
            onLocationChanged(location);
        }
    } else {
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }
    return provider != null;
}

From source file:com.crearo.gpslogger.GpsLoggingService.java

private boolean isFromValidListener(Location loc) {

    if (!preferenceHelper.getChosenListeners().contains(LocationManager.GPS_PROVIDER)
            && !preferenceHelper.getChosenListeners().contains(LocationManager.NETWORK_PROVIDER)) {
        return true;
    }/*from ww w  .j a  va2  s.  c o  m*/

    if (!preferenceHelper.getChosenListeners().contains(LocationManager.NETWORK_PROVIDER)) {
        return loc.getProvider().equalsIgnoreCase(LocationManager.GPS_PROVIDER);
    }

    if (!preferenceHelper.getChosenListeners().contains(LocationManager.GPS_PROVIDER)) {
        return !loc.getProvider().equalsIgnoreCase(LocationManager.GPS_PROVIDER);
    }

    return true;
}

From source file:com.barkside.travellocblog.LocationUpdates.java

/**
 * Check if user has turned on location services. If not, then we'll never get
 * onConnected or onLocationChanged events.
 * Google Play services does not catch this condition, so have to manually check it.
http://stackoverflow.com/questions/16862987/android-check-location-services-enabled-with-play-services-location-api
 *//*from w ww .ja  v  a  2s.  com*/
public boolean isLocationServiceOn() {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Was checking for non-empty list locationManager.getProviders(true) but
    // that also contains the PASSIVE provider, which may not return
    // any location in some cases.
    // For best performance, need both GPS and NETWORK, but for this call,
    // will accept either one being on.
    return (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
}

From source file:com.RSMSA.policeApp.OffenceReportForm.java

/**
 * try to get the 'best' location selected from all providers
 *//*  w  w  w  .ja v a  2  s  . c om*/
private Location getBestLocation() {
    Location gpslocation = getLocationByProvider(LocationManager.GPS_PROVIDER);
    Location networkLocation = getLocationByProvider(LocationManager.NETWORK_PROVIDER);
    // if we have only one location available, the choice is easy
    if (gpslocation == null) {
        Log.d(TAG, "No GPS Location available.");
        return networkLocation;
    }
    if (networkLocation == null) {
        Log.d(TAG, "No Network Location available");
        return gpslocation;
    }
    // a locationupdate is considered 'old' if its older than the configured
    // update interval. this means, we didn't get a
    // update from this provider since the last check
    long old = System.currentTimeMillis() - 1 * 60 * 60 * 1000;
    boolean gpsIsOld = (gpslocation.getTime() < old);
    boolean networkIsOld = (networkLocation.getTime() < old);
    // gps is current and available, gps is better than network
    if (!gpsIsOld) {
        Log.d(TAG, "Returning current GPS Location");
        return gpslocation;
    }
    // gps is old, we can't trust it. use network location
    if (!networkIsOld) {
        Log.d(TAG, "GPS is old, Network is current, returning network");
        return networkLocation;
    }
    // both are old return the newer of those two
    if (gpslocation.getTime() > networkLocation.getTime()) {
        Log.d(TAG, "Both are old, returning gps(newer)");
        return gpslocation;
    } else {
        Log.d(TAG, "Both are old, returning network(newer)");
        return networkLocation;
    }
}

From source file:org.planetmono.dcuploader.ActivityUploader.java

private void queryLocation(boolean enabled) {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (enabled) {
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationTracker);
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationTracker);
        ((Button) findViewById(R.id.upload_ok)).setEnabled(false);
        findViewById(R.id.upload_location_progress).setVisibility(View.VISIBLE);
    } else {//from  w w  w .j av  a2  s.c  om
        lm.removeUpdates(locationTracker);
        ((Button) findViewById(R.id.upload_ok)).setEnabled(true);
        findViewById(R.id.upload_location_progress).setVisibility(View.INVISIBLE);
    }
}

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

/**
 * Registers for updates with selected location providers.
 *///from  w  w w  . j av a2 s .co m
protected void registerLocationProviders() {
    Set<String> providers = new HashSet<String>(
            mSharedPreferences.getStringSet(Const.KEY_PREF_LOC_PROV, new HashSet<String>(Arrays
                    .asList(new String[] { LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER }))));
    locationManager.removeUpdates(this);

    if (mapSectionFragment != null)
        mapSectionFragment.onLocationProvidersChanged(providers);

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        requestLocationUpdates();
    else
        permsRequested[Const.PERM_REQUEST_LOCATION_UPDATES] = true;
}

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

/**
 * Requests location updates from the selected location providers.
 * // w  w w  . ja  va  2 s  . c o m
 * This method is intended to be called by {@link #registerLocationProviders(Context)} or by
 * {@link #onRequestPermissionsResult(int, String[], int[])}, depending on whether permissions need to be
 * requested.
 */
private void requestLocationUpdates() {
    Set<String> providers = new HashSet<String>(
            mSharedPreferences.getStringSet(Const.KEY_PREF_LOC_PROV, new HashSet<String>(Arrays
                    .asList(new String[] { LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER }))));
    List<String> allProviders = locationManager.getAllProviders();

    if (!isStopped) {
        for (String pr : providers) {
            if (allProviders.indexOf(pr) >= 0) {
                try {
                    locationManager.requestLocationUpdates(pr, 0, 0, this);
                    Log.d(TAG, "Registered with provider: " + pr);
                } catch (SecurityException e) {
                    Log.w(TAG, "Permission not granted for " + pr
                            + " location provider. Data display will not be available for this provider.");
                }
            } else {
                Log.w(TAG, "No " + pr
                        + " location provider found. Data display will not be available for this provider.");
            }
        }
    }

    try {
        // if GPS is not selected, request location updates but don't store location
        if ((!providers.contains(LocationManager.GPS_PROVIDER)) && (!isStopped)
                && (allProviders.indexOf(LocationManager.GPS_PROVIDER) >= 0))
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

        locationManager.addGpsStatusListener(this);
    } catch (SecurityException e) {
        Log.w(TAG, "Permission not granted for " + LocationManager.GPS_PROVIDER
                + " location provider. Data display will not be available for this provider.");
    }
}

From source file:plugin.google.maps.GoogleMaps.java

@SuppressWarnings("unused")
private void getMyLocation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {

    LocationManager locationManager = (LocationManager) this.activity
            .getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getAllProviders();
    if (providers.size() == 0) {
        JSONObject result = new JSONObject();
        result.put("status", false);
        result.put("error_code", "not_available");
        result.put("error_message",
                "Since this device does not have any location provider, this app can not detect your location.");
        callbackContext.error(result);// w ww . j  av a2  s . co m
        return;
    }

    // enableHighAccuracy = true -> PRIORITY_HIGH_ACCURACY
    // enableHighAccuracy = false -> PRIORITY_BALANCED_POWER_ACCURACY

    JSONObject params = args.getJSONObject(0);
    boolean isHigh = false;
    if (params.has("enableHighAccuracy")) {
        isHigh = params.getBoolean("enableHighAccuracy");
    }
    final boolean enableHighAccuracy = isHigh;

    String provider = null;
    if (enableHighAccuracy == true) {
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
            provider = LocationManager.PASSIVE_PROVIDER;
        }
    } else {
        if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
            provider = LocationManager.PASSIVE_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        }
    }
    if (provider == null) {
        //Ask the user to turn on the location services.
        AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
        builder.setTitle("Improve location accuracy");
        builder.setMessage("To enhance your Maps experience:\n\n" + " - Enable Google apps location access\n\n"
                + " - Turn on GPS and mobile network location");
        builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Launch settings, allowing user to make a change
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                activity.startActivity(intent);

                JSONObject result = new JSONObject();
                try {
                    result.put("status", false);
                    result.put("error_code", "open_settings");
                    result.put("error_message", "User opened the settings of location service. So try again.");
                } catch (JSONException e) {
                }
                callbackContext.error(result);
            }
        });
        builder.setNegativeButton("Skip", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //No location service, no Activity
                dialog.dismiss();

                JSONObject result = new JSONObject();
                try {
                    result.put("status", false);
                    result.put("error_code", "service_denied");
                    result.put("error_message", "This app has rejected to use Location Services.");
                } catch (JSONException e) {
                }
                callbackContext.error(result);
            }
        });
        builder.create().show();
        return;
    }

    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        JSONObject result = PluginUtil.location2Json(location);
        result.put("status", true);
        callbackContext.success(result);
        return;
    }

    PluginResult tmpResult = new PluginResult(PluginResult.Status.NO_RESULT);
    tmpResult.setKeepCallback(true);
    callbackContext.sendPluginResult(tmpResult);

    locationClient = new LocationClient(this.activity, new ConnectionCallbacks() {

        @Override
        public void onConnected(Bundle bundle) {
            LocationRequest request = new LocationRequest();
            int priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
            if (enableHighAccuracy) {
                priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
            }
            request.setPriority(priority);
            locationClient.requestLocationUpdates(request, new LocationListener() {

                @Override
                public void onLocationChanged(Location location) {
                    JSONObject result;
                    try {
                        result = PluginUtil.location2Json(location);
                        result.put("status", true);
                        callbackContext.success(result);
                    } catch (JSONException e) {
                    }
                    locationClient.disconnect();
                }

            });
        }

        @Override
        public void onDisconnected() {
        }

    }, new OnConnectionFailedListener() {

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            int errorCode = connectionResult.getErrorCode();
            String errorMsg = GooglePlayServicesUtil.getErrorString(errorCode);
            PluginResult result = new PluginResult(PluginResult.Status.ERROR, errorMsg);
            callbackContext.sendPluginResult(result);
        }

    });
    locationClient.connect();
}