android.location.Criteria

Here are the examples of the java api class android.location.Criteria taken from open source projects.

1. Util#createFineCriteria()

Project: Ushahidi_Android
File: Util.java
/** this criteria needs high accuracy, high power, and cost */
public static Criteria createFineCriteria() {
    Criteria c = new Criteria();
    c.setAccuracy(Criteria.ACCURACY_FINE);
    c.setAltitudeRequired(false);
    c.setBearingRequired(false);
    c.setSpeedRequired(false);
    c.setCostAllowed(true);
    c.setPowerRequirement(Criteria.POWER_HIGH);
    return c;
}

2. Util#createCoarseCriteria()

Project: Ushahidi_Android
File: Util.java
/** this criteria will settle for less accuracy, high power, and cost */
public static Criteria createCoarseCriteria() {
    Criteria c = new Criteria();
    c.setAccuracy(Criteria.ACCURACY_COARSE);
    c.setAltitudeRequired(false);
    c.setBearingRequired(false);
    c.setSpeedRequired(false);
    c.setCostAllowed(true);
    c.setPowerRequirement(Criteria.POWER_HIGH);
    return c;
}

3. LocationManagerActivity#getBestProvider()

Project: AndroidLife
File: LocationManagerActivity.java
/**
     * ????????????provider
     */
private void getBestProvider() {
    Criteria criteria = new Criteria();
    // ???
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    // ???
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    // ??
    criteria.setAltitudeRequired(true);
    // ??
    criteria.setSpeedRequired(true);
    // ??
    criteria.setCostAllowed(false);
    //false?????????????
    String provider = locationManager.getBestProvider(criteria, false);
    this.bestProviderTV.setText(provider);
}

4. ParseGeoPoint#getCurrentLocationInBackground()

Project: Parse-SDK-Android
File: ParseGeoPoint.java
/**
   * Asynchronously fetches the current location of the device.
   *
   * This will use a default {@link Criteria} with no accuracy or power requirements, which will
   * generally result in slower, but more accurate location fixes.
   * <p/>
   * <strong>Note:</strong> If GPS is the best provider, it might not be able to locate the device
   * at all and timeout.
   *
   * @param timeout
   *          The number of milliseconds to allow before timing out.
   * @return A Task that is resolved when a location is found.
   *
   * @see android.location.LocationManager#getBestProvider(android.location.Criteria, boolean)
   * @see android.location.LocationManager#requestLocationUpdates(String, long, float, android.location.LocationListener)
   */
public static Task<ParseGeoPoint> getCurrentLocationInBackground(long timeout) {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.NO_REQUIREMENT);
    criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
    return LocationNotifier.getCurrentLocationAsync(Parse.getApplicationContext(), timeout, criteria).onSuccess(new Continuation<Location, ParseGeoPoint>() {

        @Override
        public ParseGeoPoint then(Task<Location> task) throws Exception {
            Location location = task.getResult();
            return new ParseGeoPoint(location.getLatitude(), location.getLongitude());
        }
    });
}

5. IgnitedLocationManagerGingerbreadTest#shouldRequestUpdatesFromGpsIfBatteryOkay()

Project: ignition
File: IgnitedLocationManagerGingerbreadTest.java
@Test
public void shouldRequestUpdatesFromGpsIfBatteryOkay() {
    sendBatteryLevelChangedBroadcast(10);
    resume();
    Map<PendingIntent, Criteria> locationPendingIntents = shadowLocationManager.getRequestLocationUdpateCriteriaPendingIntents();
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    sendBatteryLevelChangedBroadcast(100);
    Intent intent = new Intent(Intent.ACTION_BATTERY_OKAY);
    shadowApp.sendBroadcast(intent);
    assertThat("Updates from " + LocationManager.GPS_PROVIDER + " provider should be requested when battery power is okay!", locationPendingIntents.containsValue(criteria));
}

6. AbstractIgnitedLocationManagerTest#shouldSwitchToNetworkProviderIfBatteryLow()

Project: ignition
File: AbstractIgnitedLocationManagerTest.java
@Test
public void shouldSwitchToNetworkProviderIfBatteryLow() {
    resume();
    Map<PendingIntent, Criteria> locationPendingIntents = shadowLocationManager.getRequestLocationUdpateCriteriaPendingIntents();
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    sendBatteryLevelChangedBroadcast(10);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_BATTERY_LOW);
    shadowApp.sendBroadcast(intent);
    sendBatteryLevelChangedBroadcast(100);
    assertThat("Updates from " + LocationManager.GPS_PROVIDER + " provider shouldn't be requested when battery power is low!", !locationPendingIntents.containsValue(criteria));
}

7. AbstractIgnitedLocationManagerTest#shouldNotRequestUpdatesFromGpsIfBatteryLow()

Project: ignition
File: AbstractIgnitedLocationManagerTest.java
@Test
public void shouldNotRequestUpdatesFromGpsIfBatteryLow() {
    sendBatteryLevelChangedBroadcast(10);
    resume();
    Map<PendingIntent, Criteria> locationPendingIntents = shadowLocationManager.getRequestLocationUdpateCriteriaPendingIntents();
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    assertThat("Updates from " + LocationManager.GPS_PROVIDER + " provider shouldn't be requested when battery power is low!", !locationPendingIntents.containsValue(criteria));
}

8. ShowLocationActivity#onCreate()

Project: codeexamples-android
File: ShowLocationActivity.java
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    latituteField = (TextView) findViewById(R.id.TextView02);
    longitudeField = (TextView) findViewById(R.id.TextView04);
    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    // Initialize the location fields
    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(location);
    } else {
        latituteField.setText("Location not available");
        longitudeField.setText("Location not available");
    }
}

9. LocationBinder#startListening()

Project: enroscar
File: LocationBinder.java
/**
   * Please call it from the main thread (with looper).
   * @param context context instance
   */
public void startListening(final Context context) {
    if (DEBUG) {
        Log.d(TAG, "Start location listening...");
    }
    try {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            return;
        }
    } catch (final Exception e) {
        return;
    }
    myHandler = myLooper != null ? new MyHandler(myLooper) : new MyHandler();
    if (listener != null) {
        listener.onLocationStart();
    }
    final Location last = getLastKnown(locationManager);
    if (last != null) {
        newLocation(last);
    }
    final Criteria c = new Criteria();
    c.setAltitudeRequired(false);
    c.setSpeedRequired(false);
    c.setBearingRequired(false);
    c.setCostAllowed(false);
    c.setPowerRequirement(Criteria.POWER_LOW);
    c.setAccuracy(Criteria.ACCURACY_COARSE);
    final String coarseProvider = locationManager.getBestProvider(c, false);
    c.setPowerRequirement(Criteria.NO_REQUIREMENT);
    c.setAccuracy(Criteria.ACCURACY_FINE);
    final String fineProvider = locationManager.getBestProvider(c, false);
    if (DEBUG) {
        Log.d(TAG, "Providers " + coarseProvider + "/" + fineProvider);
    }
    final long minTime = 60000;
    final int minDistance = 50;
    if (coarseProvider != null) {
        if (DEBUG) {
            Log.d(TAG, "Register for " + coarseProvider);
        }
        locationManager.requestLocationUpdates(coarseProvider, minTime, minDistance, coarseListener);
        myHandler.sendEmptyMessageDelayed(MSG_STOP_COARSE_PROVIDER, MAX_COARSE_PROVIDER_LISTEN_TIME);
    }
    if (fineProvider != null) {
        if (DEBUG) {
            Log.d(TAG, "Register for " + fineProvider);
        }
        locationManager.requestLocationUpdates(fineProvider, minTime, minDistance, fineListener);
        myHandler.sendEmptyMessageDelayed(MSG_STOP_FINE_PROVIDER, MAX_FINE_PROVIDER_LISTEN_TIME);
    }
}

10. PGPS#start()

Project: Protocoder
File: PGPS.java
@ProtoMethod(description = "Start the gps. Returns lat, lon, alt, speed, bearing", example = "")
@ProtoMethodParam(params = { "function(lat, lon, alt, speed, bearing)" })
public void start() {
    if (running) {
        return;
    }
    WhatIsRunning.getInstance().add(this);
    MLog.d(TAG, "starting GPS");
    // criteria.setSpeedRequired(true);
    locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false) {
        MLog.d(TAG, "GPS not enabled");
        showSettingsAlert();
    } else {
        MLog.d(TAG, "GPS enabled");
    }
    running = true;
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    // criteria.setBearingAccuracy(Criteria.ACCURACY_FINE);
    criteria.setCostAllowed(true);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setPowerRequirement(Criteria.POWER_HIGH);
    criteria.setSpeedRequired(false);
    provider = locationManager.getBestProvider(criteria, false);
    listener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            L.d(TAG, "the gps status is: " + status);
            // TODO add listener to see when the GPS is on or not
            switch(status) {
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    if (mLastLocation != null) {
                        isGPSFix = (SystemClock.elapsedRealtime() - mLastLocationMillis) < 3000;
                    }
                    if (isGPSFix) {
                    // A fix has been acquired.
                    // Do something.
                    } else {
                    // The fix has been lost.
                    // Do something.
                    }
                    break;
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    // Do something.
                    isGPSFix = true;
                    break;
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            c.startActivity(intent);
        }

        @Override
        public void onLocationChanged(Location location) {
            MLog.d(TAG, "updated ");
            mGPSListener.event(location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getSpeed(), location.getAccuracy());
            if (location == null) {
                return;
            }
            mLastLocationMillis = SystemClock.elapsedRealtime();
            mLastLocation = location;
        }
    };
    locationManager.requestLocationUpdates(provider, 100, 0.1f, listener);
}

11. AndroidLocationManager#findProvider()

Project: CodenameOne
File: AndroidLocationManager.java
private String findProvider(boolean includeNetwork) {
    String providerName = null;
    Criteria criteria = new Criteria();
    criteria.setSpeedRequired(true);
    criteria.setAltitudeRequired(true);
    LocationProvider provider;
    boolean enabled;
    if (includeNetwork) {
        provider = locationManager.getProvider(LocationManager.NETWORK_PROVIDER);
        enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (provider != null && enabled) {
            providerName = provider.getName();
        } else {
            providerName = locationManager.getBestProvider(criteria, true);
        }
    }
    if (providerName == null) {
        // If GPS provider, then create and start GPS listener
        provider = locationManager.getProvider(LocationManager.GPS_PROVIDER);
        enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (provider != null && enabled) {
            providerName = provider.getName();
        }
    }
    return providerName;
}

12. SocializeLocationManagerTest#testSocializeLocationManager()

Project: socialize-sdk-android
File: SocializeLocationManagerTest.java
// Can't mock location manager, so just do a full integration test
public void testSocializeLocationManager() {
    AppUtils appUtils = Mockito.mock(AppUtils.class);
    Mockito.when(appUtils.hasPermission((Context) Mockito.anyObject(), Mockito.eq("android.permission.ACCESS_FINE_LOCATION"))).thenReturn(false);
    Mockito.when(appUtils.hasPermission((Context) Mockito.anyObject(), Mockito.eq("android.permission.ACCESS_COARSE_LOCATION"))).thenReturn(true);
    SocializeLocationManager manager = new SocializeLocationManager(appUtils);
    manager.init(TestUtils.getActivity(this));
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    String bestProvider = manager.getBestProvider(criteria, true);
    assertNotNull(bestProvider);
    // May be null, so don't assert result
    manager.getLastKnownLocation(bestProvider);
    manager.isProviderEnabled(bestProvider);
    LocationListener listener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
        }
    };
    manager.requestLocationUpdates(TestUtils.getActivity(this), bestProvider, 0, 0, listener);
    manager.removeUpdates(listener);
}

13. DefaultLocationProvider#requestLocation()

Project: socialize-sdk-android
File: DefaultLocationProvider.java
protected void requestLocation(Context context, int accuracy) {
    if (logger != null && logger.isDebugEnabled()) {
        logger.debug("LocationProvider Requesting location...");
    }
    Criteria criteria = new Criteria();
    criteria.setAccuracy(accuracy);
    String provider = locationManager.getBestProvider(criteria, true);
    if (!StringUtils.isEmpty(provider)) {
        Location mostRecentLocation = locationManager.getLastKnownLocation(provider);
        if (mostRecentLocation != null) {
            if (logger != null && logger.isDebugEnabled()) {
                logger.debug("Got location from last known provider");
            }
            location = mostRecentLocation;
            locationManager.removeUpdates(listener);
        } else if (locationManager.isProviderEnabled(provider)) {
            if (listener != null) {
                if (logger != null && logger.isDebugEnabled()) {
                    logger.debug("No last known location, requesting from device...");
                }
                if (context instanceof Activity) {
                    locationManager.requestLocationUpdates((Activity) context, provider, 1, 0, listener);
                } else {
                    if (logger != null && logger.isWarnEnabled()) {
                        logger.warn("Cannot request location using a non-activity context");
                    }
                }
            } else {
                if (logger != null && logger.isWarnEnabled()) {
                    logger.warn("No listener specified for location callback");
                }
            }
        } else {
            if (logger != null && logger.isWarnEnabled()) {
                logger.warn("Location provider [" + provider + "] is not enabled");
            }
        }
    } else {
        if (logger != null && logger.isWarnEnabled()) {
            logger.warn("No provider found to determine location based on accuracy [" + accuracy + "].  Check that location is enabled in the device and location permissions set on the app");
        }
    }
}

14. Tools#accessLocation()

Project: Nammu
File: Tools.java
public static boolean accessLocation(Context context) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String bestProvider = locationManager.getBestProvider(criteria, false);
    if (bestProvider == null) {
        //No android.permission-group.LOCATION
        return false;
    }
    return true;
}

15. SetUpActivity#setUpLocationMonitoring()

Project: HomeMirror
File: SetUpActivity.java
private void setUpLocationMonitoring() {
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    String provider = mLocationManager.getBestProvider(criteria, true);
    try {
        mLocation = mLocationManager.getLastKnownLocation(provider);
        if (mLocation == null) {
            mLocationView.setVisibility(View.VISIBLE);
            mLocationListener = new LocationListener() {

                @Override
                public void onLocationChanged(Location location) {
                    if (location != null) {
                        Toast.makeText(SetUpActivity.this, R.string.found_location, Toast.LENGTH_SHORT).show();
                        mLocation = location;
                        mConfigSettings.setLatLon(String.valueOf(mLocation.getLatitude()), String.valueOf(mLocation.getLongitude()));
                        mLocationManager.removeUpdates(this);
                        if (mLocationView != null) {
                            mLocationView.setVisibility(View.GONE);
                        }
                    }
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                }

                @Override
                public void onProviderEnabled(String provider) {
                }

                @Override
                public void onProviderDisabled(String provider) {
                }
            };
            mLocationManager.requestLocationUpdates(provider, HOUR_MILLIS, METERS_MIN, mLocationListener);
        } else {
            mLocationView.setVisibility(View.GONE);
        }
    } catch (IllegalArgumentException e) {
        Log.e("SetUpActivity", "Location manager could not use provider", e);
    }
}

16. CurrentLocationActivity#onResume()

Project: gast-lib
File: CurrentLocationActivity.java
@Override
protected void onResume() {
    super.onResume();
    StringBuffer stringBuffer = new StringBuffer();
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    enabledProviders = locationManager.getProviders(criteria, true);
    if (enabledProviders.isEmpty()) {
        enabledProvidersValue.setText("");
    } else {
        for (String enabledProvider : enabledProviders) {
            stringBuffer.append(enabledProvider).append(" ");
            locationManager.requestSingleUpdate(enabledProvider, this, null);
        }
        enabledProvidersValue.setText(stringBuffer);
    }
    uptimeAtResume = SystemClock.uptimeMillis();
    latitudeValue.setText("");
    longitudeValue.setText("");
    providerValue.setText("");
    accuracyValue.setText("");
    timeToFixValue.setText("");
    findViewById(R.id.timeToFixUnits).setVisibility(View.GONE);
    findViewById(R.id.accuracyUnits).setVisibility(View.GONE);
}

17. SimpleLocationManager#findBestLocationProvider()

Project: droidar
File: SimpleLocationManager.java
public String findBestLocationProvider() {
    LocationManager locationManager = getLocationManager();
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Log.i(LOG_TAG, "GPS was enabled so this method should " + "come to the conclusion to use GPS as " + "the location source!");
    }
    /*
		 * To register the EventManager in the LocationManager a Criteria object
		 * has to be created and as the primary attribute accuracy should be
		 * used to get as accurate position data as possible:
		 */
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String provider = locationManager.getBestProvider(criteria, true);
    if (provider == null) {
        Log.w(LOG_TAG, "No location-provider with the " + "specified requierments found.. Trying to find " + "an alternative.");
        List<String> providerList = locationManager.getProviders(true);
        for (String possibleProvider : providerList) {
            if (possibleProvider != null) {
                Log.w(LOG_TAG, "Location-provider alternative " + "found: " + possibleProvider);
                provider = possibleProvider;
            }
        }
        if (provider == null) {
            Log.w(LOG_TAG, "No location-provider alternative " + "found!");
        }
    }
    if (!provider.equals(LocationManager.GPS_PROVIDER)) {
        Log.w(LOG_TAG, "The best location provider was not " + LocationManager.GPS_PROVIDER + ", it was " + provider);
    }
    return provider;
}

18. MainFragment#getLastKnownLocation()

Project: AndroidSlidingUpPanel-foursquare-map-demo
File: MainFragment.java
private LatLng getLastKnownLocation(boolean isMoveMarker) {
    LocationManager lm = (LocationManager) TheApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    String provider = lm.getBestProvider(criteria, true);
    if (provider == null) {
        return null;
    }
    Activity activity = getActivity();
    if (activity == null) {
        return null;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (activity.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
    }
    Location loc = lm.getLastKnownLocation(provider);
    if (loc != null) {
        LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
        if (isMoveMarker) {
            moveMarker(latLng);
        }
        return latLng;
    }
    return null;
}

19. LocationManagerTest#shouldStoreBestProviderCriteriaAndEnabledOnlyFlag()

Project: robolectric
File: LocationManagerTest.java
@Test
public void shouldStoreBestProviderCriteriaAndEnabledOnlyFlag() throws Exception {
    Criteria criteria = new Criteria();
    assertNull(locationManager.getBestProvider(criteria, true));
    assertSame(criteria, shadowLocationManager.getLastBestProviderCriteria());
    assertTrue(shadowLocationManager.getLastBestProviderEnabledOnly());
}

20. MapActivity#initLocationManager()

Project: quickblox-android-sdk
File: MapActivity.java
private void initLocationManager() {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        onLocationChanged(location);
    }
    locationManager.requestLocationUpdates(provider, Consts.LOCATION_MIN_TIME, 0, this);
}