Java Code Examples for android.location.Criteria#setAccuracy()

The following examples show how to use android.location.Criteria#setAccuracy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocationUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取定位参数对象
 * @return {@link Criteria}
 */
private static Criteria getCriteria() {
    Criteria criteria = new Criteria();
    // 设置定位精确度 Criteria.ACCURACY_COARSE 比较粗略, Criteria.ACCURACY_FINE 则比较精细
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    // 设置是否要求速度
    criteria.setSpeedRequired(false);
    // 设置是否允许运营商收费
    criteria.setCostAllowed(false);
    // 设置是否需要方位信息
    criteria.setBearingRequired(false);
    // 设置是否需要海拔信息
    criteria.setAltitudeRequired(false);
    // 设置对电源的需求
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    return criteria;
}
 
Example 2
Source File: RawLocationProvider.java    From background-geolocation-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onStart() {
    if (isStarted) {
        return;
    }

    Criteria criteria = new Criteria();
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setSpeedRequired(true);
    criteria.setCostAllowed(true);
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setHorizontalAccuracy(translateDesiredAccuracy(mConfig.getDesiredAccuracy()));
    criteria.setPowerRequirement(Criteria.POWER_HIGH);

    try {
        locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), mConfig.getInterval(), mConfig.getDistanceFilter(), this);
        isStarted = true;
    } catch (SecurityException e) {
        logger.error("Security exception: {}", e.getMessage());
        this.handleSecurityException(e);
    }
}
 
Example 3
Source File: LocationUtils.java    From Android-UtilCode with Apache License 2.0 6 votes vote down vote up
/**
 * 设置定位参数
 *
 * @return {@link Criteria}
 */
private static Criteria getCriteria() {
    Criteria criteria = new Criteria();
    // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    // 设置是否要求速度
    criteria.setSpeedRequired(false);
    // 设置是否允许运营商收费
    criteria.setCostAllowed(false);
    // 设置是否需要方位信息
    criteria.setBearingRequired(false);
    // 设置是否需要海拔信息
    criteria.setAltitudeRequired(false);
    // 设置对电源的需求
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    return criteria;
}
 
Example 4
Source File: Util.java    From letv with Apache License 2.0 6 votes vote down vote up
public static String getLocation(Context context) {
    if (context == null) {
        return "";
    }
    try {
        LocationManager locationManager = (LocationManager) context.getSystemService(HOME_RECOMMEND_PARAMETERS.LOCATION);
        Criteria criteria = new Criteria();
        criteria.setCostAllowed(false);
        criteria.setAccuracy(2);
        String bestProvider = locationManager.getBestProvider(criteria, true);
        if (bestProvider != null) {
            Location lastKnownLocation = locationManager.getLastKnownLocation(bestProvider);
            if (lastKnownLocation == null) {
                return "";
            }
            double latitude = lastKnownLocation.getLatitude();
            g = latitude + "*" + lastKnownLocation.getLongitude();
            return g;
        }
    } catch (Throwable e) {
        f.b("getLocation", "getLocation>>>", e);
    }
    return "";
}
 
Example 5
Source File: LocationLogic.java    From redalert-android with Apache License 2.0 6 votes vote down vote up
public static Location GetLastKnownLocation(Context context) {
    // Get location manager
    LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);

    // Create location criteria
    Criteria criteria = new Criteria();

    // Set fine accuracy
    criteria.setAccuracy(criteria.ACCURACY_FINE);

    // Get best provider
    String bestProvider = locationManager.getBestProvider(criteria, false);

    // No provider?
    if (bestProvider == null) {
        // Return null
        return null;
    }

    // Return last location
    return locationManager.getLastKnownLocation(bestProvider);
}
 
Example 6
Source File: GpsTraceService.java    From MobileGuard with MIT License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // locate
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // check permission
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    // get best provider
    Criteria criteria = new Criteria();
    criteria.setCostAllowed(true);
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String bestProvider = locationManager.getBestProvider(criteria, true);
    System.out.println("best provider:" + bestProvider);
    // start listening
    listener = new MyLocationListener();
    locationManager.requestLocationUpdates(bestProvider, 0, 0, listener);
}
 
Example 7
Source File: LocationUtils.java    From AndroidUtilCode with Apache License 2.0 6 votes vote down vote up
/**
 * 设置定位参数
 *
 * @return {@link Criteria}
 */
private static Criteria getCriteria() {
    Criteria criteria = new Criteria();
    // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    // 设置是否要求速度
    criteria.setSpeedRequired(false);
    // 设置是否允许运营商收费
    criteria.setCostAllowed(false);
    // 设置是否需要方位信息
    criteria.setBearingRequired(false);
    // 设置是否需要海拔信息
    criteria.setAltitudeRequired(false);
    // 设置对电源的需求
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    return criteria;
}
 
Example 8
Source File: GeoLowResSucker.java    From CameraV with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public GeoLowResSucker(Context context) {
	super(context);
	setSucker(this);
	
	lm = (LocationManager) context.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
		
	criteria = new Criteria();
	criteria.setAccuracy(Criteria.ACCURACY_LOW);
	criteria.setPowerRequirement(Criteria.POWER_LOW);
	
	mBestProvider = lm.getBestProvider(criteria, true); //we only want providers that are on
	
	lm.requestLocationUpdates(mBestProvider, MIN_TIME, MIN_DISTANCE, this);
	
	setTask(new TimerTask() {

		@Override
		public void run() throws NullPointerException {
			if(getIsRunning()) {
				try {
					double[] loc = updateLocation();
					if (loc != null)
						sendToBuffer(new ILogPack(Geo.Keys.GPS_COORDS, "[" + loc[0] + "," + loc[1] + "]"));
				} catch(NullPointerException e) {
					Log.e(LOG, "location NPE", e);
				}
			}
		}
	});
	
	getTimer().schedule(getTask(), 0, Geo.LOG_RATE);
}
 
Example 9
Source File: LocationUtils.java    From iot-starter-for-android with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Helper method to create a criteria for location change listener
 *
 * @return criteria constructed for the listener
 */
private Criteria getCriteria() {
    Criteria criteria = new Criteria();
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(true);
    criteria.setCostAllowed(true);
    criteria.setSpeedRequired(true);
    return criteria;
}
 
Example 10
Source File: MainFragment.java    From AndroidSlidingUpPanel-foursquare-map-demo with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: LastLocationFinder.java    From Android-Next with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new Gingerbread Last Location Finder.
 *
 * @param context Context
 */
public LastLocationFinder(Context context) {
    this.context = context;
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    // Coarse accuracy is specified here to get the fastest possible result.
    // The calling Activity will likely (or have already) request ongoing
    // updates using the Fine location provider.
    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);

    // Construct the Pending Intent that will be broadcast by the oneshot
    // location update.
    Intent updateIntent = new Intent(SINGLE_LOCATION_UPDATE_ACTION);
    pendingIntent = PendingIntent.getBroadcast(context, 0, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
 
Example 12
Source File: LocationInfo.java    From batteryhub with Apache License 2.0 5 votes vote down vote up
public static String getBestProvider(Context context) {
    LocationManager manager = (LocationManager)
            context.getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);

    return manager.getBestProvider(criteria, true);
}
 
Example 13
Source File: OrientationManager.java    From PTVGlass with MIT License 5 votes vote down vote up
/**
 * Starts tracking the user's location and orientation. After calling this method, any
 * {@link OnChangedListener}s added to this object will be notified of these events.
 */
public void start() {
    if (!mTracking) {
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
                SensorManager.SENSOR_DELAY_UI);

        // The rotation vector sensor doesn't give us accuracy updates, so we observe the
        // magnetic field sensor solely for those.
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
                SensorManager.SENSOR_DELAY_UI);

        Location lastLocation = mLocationManager
                .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        if (lastLocation != null) {
            long locationAge = lastLocation.getTime() - System.currentTimeMillis();
            if (locationAge < MAX_LOCATION_AGE_MILLIS) {
                mLocation = lastLocation;
                updateGeomagneticField();
            }
        }

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(false);

        List<String> providers =
                mLocationManager.getProviders(criteria, true /* enabledOnly */);
        for (String provider : providers) {
            mLocationManager.requestLocationUpdates(provider,
                    MILLIS_BETWEEN_LOCATIONS, METERS_BETWEEN_LOCATIONS, mLocationListener,
                    Looper.getMainLooper());
        }

        mTracking = true;
    }
}
 
Example 14
Source File: MyLocationOverlay.java    From WhereYouGo with GNU General Public License v3.0 5 votes vote down vote up
private synchronized boolean enableBestAvailableProvider() {
    disableMyLocation();

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String bestAvailableProvider = this.locationManager.getBestProvider(criteria, true);
    if (bestAvailableProvider == null) {
        return false;
    }
    this.lastLocation = this.locationManager.getLastKnownLocation(bestAvailableProvider);
    this.locationManager.requestLocationUpdates(bestAvailableProvider, UPDATE_INTERVAL,
            UPDATE_DISTANCE, this);
    this.myLocationEnabled = true;
    return true;
}
 
Example 15
Source File: ShareUtil.java    From Huochexing12306 with Apache License 2.0 5 votes vote down vote up
public Location getLocation(Activity activity)
{
    LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
    // 查找到服务信息
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗

    String provider = locationManager.getBestProvider(criteria, false); // 获取GPS信息
    Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
    return location;
}
 
Example 16
Source File: AndroidLocationEngineImpl.java    From mapbox-events-android with MIT License 5 votes vote down vote up
@VisibleForTesting
static Criteria getCriteria(int priority) {
  Criteria criteria = new Criteria();
  criteria.setAccuracy(priorityToAccuracy(priority));
  criteria.setCostAllowed(true);
  criteria.setPowerRequirement(priorityToPowerRequirement(priority));
  return criteria;
}
 
Example 17
Source File: OrientationManager.java    From SpeedHud with Apache License 2.0 5 votes vote down vote up
/**
 * Starts tracking the user's location and orientation. After calling this method, any
 * {@link OnChangedListener}s added to this object will be notified of these events.
 */
public void start() {
    if (!mTracking) {
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
                SensorManager.SENSOR_DELAY_UI);

        // The rotation vector sensor doesn't give us accuracy updates, so we observe the
        // magnetic field sensor solely for those.
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
                SensorManager.SENSOR_DELAY_UI);

        Location lastLocation = mLocationManager
                .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        if (lastLocation != null) {
            long locationAge = lastLocation.getTime() - System.currentTimeMillis();
            if (locationAge < MAX_LOCATION_AGE_MILLIS) {
                mLocation = lastLocation;
                updateGeomagneticField();
            }
        }

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(false);

        List<String> providers =
                mLocationManager.getProviders(criteria, true /* enabledOnly */);
        for (String provider : providers) {
            mLocationManager.requestLocationUpdates(provider,                        MILLIS_BETWEEN_LOCATIONS, METERS_BETWEEN_LOCATIONS, mLocationListener,
            Looper.getMainLooper());
        }

        mTracking = true;
    }
}
 
Example 18
Source File: DalvikPositionService.java    From attach with GNU General Public License v3.0 5 votes vote down vote up
private Criteria getLocationProvider() {
    final Criteria criteria = new Criteria();
    if (timeInterval <= 1000 && distanceFilter <= 1.0f) {
        // Parameters HIGH/HIGHEST
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
    } else if (timeInterval >= 30000 && distanceFilter >= 100.0f) {
        // Parameters LOW/LOWEST
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setHorizontalAccuracy(Criteria.ACCURACY_LOW);
        criteria.setVerticalAccuracy(Criteria.ACCURACY_LOW);
        criteria.setBearingAccuracy(Criteria.ACCURACY_LOW);
        criteria.setSpeedAccuracy(Criteria.ACCURACY_LOW);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
    } else {
        // Parameter MEDIUM
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setHorizontalAccuracy(Criteria.ACCURACY_MEDIUM);
        criteria.setVerticalAccuracy(Criteria.ACCURACY_MEDIUM);
        criteria.setBearingAccuracy(Criteria.ACCURACY_MEDIUM);
        criteria.setSpeedAccuracy(Criteria.ACCURACY_MEDIUM);
        criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
    }
    return criteria;
}
 
Example 19
Source File: GeoLocation.java    From open-rmbt with Apache License 2.0 4 votes vote down vote up
/** Load Listeners */
public void start()
{
    if (!started)
    {
        started = true;
        
        final Criteria criteriaCoarse = new Criteria();
        /* "Coarse" accuracy means "no need to use GPS". */
        criteriaCoarse.setAccuracy(Criteria.ACCURACY_COARSE);
        criteriaCoarse.setPowerRequirement(Criteria.POWER_LOW);
        final String coarseProviderName = locationManager.getBestProvider(criteriaCoarse, true);
        
        if (coarseProviderName != null)
        {
            isBetterLocation(locationManager.getLastKnownLocation(coarseProviderName));
            
            coarseLocationListener = new LocListener();
            locationManager.requestLocationUpdates(coarseProviderName,
            minTime,
            minDistance, coarseLocationListener);
        }
        
        if (gpsEnabled)
        {
            final Criteria criteriaFine = new Criteria();
            /* "Fine" accuracy means "use GPS". */
            criteriaFine.setAccuracy(Criteria.ACCURACY_FINE);
            criteriaFine.setPowerRequirement(Criteria.POWER_HIGH);
            final String fineProviderName = locationManager.getBestProvider(criteriaFine, true);
            
            if (fineProviderName != null)
            {
                isBetterLocation(locationManager.getLastKnownLocation(fineProviderName));
                
                fineLocationListener = new LocListener();
                locationManager.requestLocationUpdates(fineProviderName,
                minTime,
                minDistance, fineLocationListener);
            }
        }
    }
}
 
Example 20
Source File: MapActivity.java    From PocketMaps with MIT License 4 votes vote down vote up
public void ensureLocationListener(boolean showMsgEverytime)
{
  if (locationListenerStatus == PermissionStatus.Disabled) { return; }
  if (locationListenerStatus != PermissionStatus.Enabled)
  {
    boolean f_loc = Permission.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION, this);
    if (!f_loc)
    {
      if (locationListenerStatus == PermissionStatus.Requesting)
      {
        locationListenerStatus = PermissionStatus.Disabled;
        return;
      }
      locationListenerStatus = PermissionStatus.Requesting;
      String[] permissions = new String[2];
      permissions[0] = android.Manifest.permission.ACCESS_FINE_LOCATION;
      permissions[1] = android.Manifest.permission.ACCESS_COARSE_LOCATION;
      Permission.startRequest(permissions, false, this);
      return;
    }
  }
  try
  {
    if (Variable.getVariable().isSmoothON()) {
      locationManager.removeUpdates(this);
      kalmanLocationManager.requestLocationUpdates(UseProvider.GPS, FILTER_TIME, GPS_TIME, NET_TIME, this, false);
      lastProvider = KalmanLocationManager.KALMAN_PROVIDER;
      logUser("LocationProvider: " + lastProvider);
    } else {
      kalmanLocationManager.removeUpdates(this);
      Criteria criteria = new Criteria();
      criteria.setAccuracy(Criteria.ACCURACY_FINE);
      String provider = locationManager.getBestProvider(criteria, true);
      if (provider == null) {
        lastProvider = null;
        locationManager.removeUpdates(this);
        logUser("LocationProvider is off!");
        return;
      } else if (provider.equals(lastProvider)) {
        if (showMsgEverytime) {
          logUser("LocationProvider: " + provider);
        }
        return;
      }
      locationManager.removeUpdates(this);
      lastProvider = provider;
      locationManager.requestLocationUpdates(provider, 3000, 5, this);
      logUser("LocationProvider: " + provider);
    }
    locationListenerStatus = PermissionStatus.Enabled;
  }
  catch (SecurityException ex)
  {
    logUser("Location_Service not allowed by user!");
  }
}