List of usage examples for android.location LocationManager getBestProvider
public String getBestProvider(Criteria criteria, boolean enabledOnly)
From source file:fiser.Activities.MainActivity.java
private void listaRecargar(boolean cercanos) { SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); sitioList.clear();/*from w ww .j a va 2 s . c om*/ if (!cercanos) { for (Sitio sitio : Sitio.getSitio(this)) sitioList.add(sitio); } else { LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = locationManager.getBestProvider(criteria, true); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { for (Sitio sitio : Sitio.getSitio(this)) sitioList.add(sitio); } else { Location location = locationManager.getLastKnownLocation(provider); for (Sitio sitio : Sitio.getSitio(this)) { Location loc = new Location("temp"); loc.setLatitude(sitio.latitud); loc.setLongitude(sitio.longitud); float distance = location.distanceTo(loc); int cercaniaMinimaInt = sharedPref.getInt(getString(R.string.cercaniaMinima), getResources().getInteger(R.integer.cercaniaMinimaDefault)); if (cercaniaMinimaInt * 1000 > distance) sitioList.add(sitio); } } } adapter.notifyDataSetChanged(); }
From source file:com.gsma.rcs.ri.messaging.geoloc.EditGeoloc.java
/** * Set the location of the device//from w w w.j av a 2 s .com */ protected void setMyLocation() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); String bestProvider = lm.getBestProvider(criteria, false); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } Location lastKnownLoc = lm.getLastKnownLocation(bestProvider); if (lastKnownLoc != null) { mLatitudeEdit.setText(String.valueOf(lastKnownLoc.getLatitude())); mLongitudeEdit.setText(String.valueOf(lastKnownLoc.getLongitude())); mAccuracyEdit.setText(String.valueOf(lastKnownLoc.getAccuracy())); } super.onResume(); }
From source file:de.madvertise.android.sdk.MadvertiseUtil.java
/** * Try to update current location. Non blocking call. * //from ww w . j a va2 s. c o m * @param context * application context */ public static void refreshCoordinates(final Context context) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Trying to refresh location"); if (context == null) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Context not set - quit location refresh"); return; } // check if we need a regular update if ((sLocationUpdateTimestamp + MadvertiseUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System .currentTimeMillis()) { MadvertiseUtil.logMessage(null, Log.DEBUG, "It's not time yet for refreshing the location"); return; } synchronized (context) { // recheck, if location was updated by another thread while we // paused if ((sLocationUpdateTimestamp + MadvertiseUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System .currentTimeMillis()) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Another thread updated the loation already"); return; } boolean permissionCoarseLocation = MadvertiseUtil .checkPermissionGranted(android.Manifest.permission.ACCESS_COARSE_LOCATION, context); boolean permissionFineLocation = MadvertiseUtil .checkPermissionGranted(android.Manifest.permission.ACCESS_FINE_LOCATION, context); // return (null) if we do not have any permissions if (!permissionCoarseLocation && !permissionFineLocation) { MadvertiseUtil.logMessage(null, Log.DEBUG, "No permissions for requesting the location"); return; } // return (null) if we can't get a location manager LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if (locationManager == null) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Unable to fetch a location manger"); return; } String provider = null; Criteria criteria = new Criteria(); criteria.setCostAllowed(false); // try to get coarse location first if (permissionCoarseLocation) { criteria.setAccuracy(Criteria.ACCURACY_COARSE); provider = locationManager.getBestProvider(criteria, true); } // try to get gps location if coarse locatio did not work if (provider == null && permissionFineLocation) { criteria.setAccuracy(Criteria.ACCURACY_FINE); provider = locationManager.getBestProvider(criteria, true); } // still no provider, return (null) if (provider == null) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Unable to fetch a location provider"); return; } // create a finalized reference to the location manager, in order to // access it in the inner class final LocationManager finalizedLocationManager = locationManager; sLocationUpdateTimestamp = System.currentTimeMillis(); locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() { @Override public void onLocationChanged(Location location) { MadvertiseUtil.logMessage(null, Log.DEBUG, "Refreshing location"); sCurrentLocation = location; sLocationUpdateTimestamp = System.currentTimeMillis(); // stop draining battery life finalizedLocationManager.removeUpdates(this); } // not used yet @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }, context.getMainLooper()); } }
From source file:com.dwdesign.tweetings.activity.MapViewerActivity.java
protected void getLocationAndCenterMap() { LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); final Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); final String provider = mLocationManager.getBestProvider(criteria, true); Location mRecentLocation = null; if (provider != null) { mRecentLocation = mLocationManager.getLastKnownLocation(provider); } else {/*from w ww .j a v a2 s . c o m*/ Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show(); } if (mRecentLocation != null && isNativeMapSupported()) { NativeMapFragment aFragment = (NativeMapFragment) mFragment; aFragment.setCenter(mRecentLocation); } }
From source file:nodomain.freeyourgadget.gadgetbridge.externalevents.AlarmReceiver.java
@Override public void onReceive(Context context, Intent intent) { if (!GBApplication.getPrefs().getBoolean("send_sunrise_sunset", false)) { LOG.info("won't send sunrise and sunset events (disabled in preferences)"); return;/*from w w w. j a va 2 s . c om*/ } LOG.info("will resend sunrise and sunset events"); final GregorianCalendar dateTimeTomorrow = new GregorianCalendar(TimeZone.getTimeZone("UTC")); dateTimeTomorrow.set(Calendar.HOUR, 0); dateTimeTomorrow.set(Calendar.MINUTE, 0); dateTimeTomorrow.set(Calendar.SECOND, 0); dateTimeTomorrow.set(Calendar.MILLISECOND, 0); dateTimeTomorrow.add(GregorianCalendar.DAY_OF_MONTH, 1); /* * rotate ids ud reuse the id from two days ago for tomorrow, this way we will have * sunrise /sunset for 3 days while sending only sunrise/sunset per day */ byte id_tomorrow = (byte) ((dateTimeTomorrow.getTimeInMillis() / (1000L * 60L * 60L * 24L)) % 3); GBApplication.deviceService().onDeleteCalendarEvent(CalendarEventSpec.TYPE_SUNRISE, id_tomorrow); GBApplication.deviceService().onDeleteCalendarEvent(CalendarEventSpec.TYPE_SUNSET, id_tomorrow); Prefs prefs = GBApplication.getPrefs(); float latitude = prefs.getFloat("location_latitude", 0); float longitude = prefs.getFloat("location_longitude", 0); LOG.info("got longitude/latitude from preferences: " + latitude + "/" + longitude); if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && prefs.getBoolean("use_updated_location_if_available", false)) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = locationManager.getBestProvider(criteria, false); if (provider != null) { Location lastKnownLocation = locationManager.getLastKnownLocation(provider); if (lastKnownLocation != null) { latitude = (float) lastKnownLocation.getLatitude(); longitude = (float) lastKnownLocation.getLongitude(); LOG.info("got longitude/latitude from last known location: " + latitude + "/" + longitude); } } } GregorianCalendar[] sunriseTransitSetTomorrow = SPA.calculateSunriseTransitSet(dateTimeTomorrow, latitude, longitude, DeltaT.estimate(dateTimeTomorrow)); CalendarEventSpec calendarEventSpec = new CalendarEventSpec(); calendarEventSpec.durationInSeconds = 0; calendarEventSpec.description = null; calendarEventSpec.type = CalendarEventSpec.TYPE_SUNRISE; calendarEventSpec.title = "Sunrise"; if (sunriseTransitSetTomorrow[0] != null) { calendarEventSpec.id = id_tomorrow; calendarEventSpec.timestamp = (int) (sunriseTransitSetTomorrow[0].getTimeInMillis() / 1000); GBApplication.deviceService().onAddCalendarEvent(calendarEventSpec); } calendarEventSpec.type = CalendarEventSpec.TYPE_SUNSET; calendarEventSpec.title = "Sunset"; if (sunriseTransitSetTomorrow[2] != null) { calendarEventSpec.id = id_tomorrow; calendarEventSpec.timestamp = (int) (sunriseTransitSetTomorrow[2].getTimeInMillis() / 1000); GBApplication.deviceService().onAddCalendarEvent(calendarEventSpec); } }
From source file:com.njlabs.amrita.aid.about.Amrita.java
public void directions_cbe(View view) { LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); String bestProvider = locationManager.getBestProvider(criteria, false); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return;/* ww w .j a v a 2 s .c o m*/ } LocationListener loc_listener = new LocationListener() { public void onLocationChanged(Location l) { } public void onProviderEnabled(String p) { } public void onProviderDisabled(String p) { } public void onStatusChanged(String p, int status, Bundle extras) { } }; locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener); Location location = locationManager.getLastKnownLocation(bestProvider); double lat; double lon; try { lat = location.getLatitude(); lon = location.getLongitude(); } catch (NullPointerException e) { lat = -1.0; lon = -1.0; } Uri uri = Uri.parse( "http://maps.google.com/maps?f=d&saddr=" + lat + "," + lon + "&daddr=10.900539,76.902806&hl=en"); Intent it = new Intent(Intent.ACTION_VIEW, uri); startActivity(it); }
From source file:com.jeremy.tripcord.main.TripcordFragment.java
private CameraUpdate getLastKnownLocation() { LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_LOW); String provider = lm.getBestProvider(criteria, true); if (provider == null) { return null; }//from w w w.ja va 2 s .c om Location loc = lm.getLastKnownLocation(provider); if (loc != null) { return CameraUpdateFactory.newCameraPosition( CameraPosition.fromLatLngZoom(new LatLng(loc.getLatitude(), loc.getLongitude()), 14.0f)); } return null; }
From source file:com.example.scrumptious.PickerActivity.java
@Override protected void onStart() { super.onStart(); if (FRIEND_PICKER.equals(getIntent().getData())) { try {/*from ww w.j a va 2s. c o m*/ friendPickerFragment.loadData(false); } catch (Exception ex) { onError(ex); } } else if (PLACE_PICKER.equals(getIntent().getData())) { try { Location location = null; Criteria criteria = new Criteria(); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String bestProvider = locationManager.getBestProvider(criteria, false); if (bestProvider != null) { location = locationManager.getLastKnownLocation(bestProvider); if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) { locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { boolean updateLocation = true; Location prevLocation = placePickerFragment.getLocation(); if (prevLocation != null) { updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD; } if (updateLocation) { placePickerFragment.setLocation(location); placePickerFragment.loadData(true); } } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD, locationListener, Looper.getMainLooper()); } } if (location != null) { placePickerFragment.setLocation(location); placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS); placePickerFragment.setSearchText(SEARCH_TEXT); placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT); placePickerFragment.loadData(false); } } catch (Exception ex) { onError(ex); } } }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.webview.CurrentPosition.java
public CurrentPosition() { Prefs prefs = GBApplication.getPrefs(); this.latitude = prefs.getFloat("location_latitude", 0); this.longitude = prefs.getFloat("location_longitude", 0); lastKnownLocation = new Location("preferences"); lastKnownLocation.setLatitude(this.latitude); lastKnownLocation.setLongitude(this.longitude); LOG.info("got longitude/latitude from preferences: " + latitude + "/" + longitude); this.timestamp = System.currentTimeMillis() - 86400000; //let accessor know this value is really old if (ActivityCompat.checkSelfPermission(GBApplication.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && prefs.getBoolean("use_updated_location_if_available", false)) { LocationManager locationManager = (LocationManager) GBApplication.getContext() .getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = null;//from ww w . j ava2 s .c om if (locationManager != null) { provider = locationManager.getBestProvider(criteria, false); } if (provider != null) { Location lastKnownLocation = locationManager.getLastKnownLocation(provider); if (lastKnownLocation != null) { this.lastKnownLocation = lastKnownLocation; this.timestamp = lastKnownLocation.getTime(); this.timestamp = System.currentTimeMillis() - 1000; //TODO: request updating the location and don't fake its age this.latitude = (float) lastKnownLocation.getLatitude(); this.longitude = (float) lastKnownLocation.getLongitude(); this.accuracy = lastKnownLocation.getAccuracy(); this.altitude = (float) lastKnownLocation.getAltitude(); this.speed = lastKnownLocation.getSpeed(); } } } }
From source file:com.example.snapcacheexample.PickerActivity.java
@Override protected void onStart() { super.onStart(); if (FRIEND_PICKER.equals(getIntent().getData())) { try {//from ww w . j a v a 2 s .c o m friendPickerFragment.loadData(false); } catch (Exception ex) { onError(ex); } } else if (PLACE_PICKER.equals(getIntent().getData())) { try { Location location = null; Criteria criteria = new Criteria(); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String bestProvider = locationManager.getBestProvider(criteria, false); if (bestProvider != null) { location = locationManager.getLastKnownLocation(bestProvider); if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) { locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { float distance = location.distanceTo(placePickerFragment.getLocation()); if (distance >= LOCATION_CHANGE_THRESHOLD) { placePickerFragment.setLocation(location); placePickerFragment.loadData(true); } } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD, locationListener, Looper.getMainLooper()); } } if (location == null) { String model = Build.MODEL; if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) { // this may be the emulator, pretend we're in an exotic place location = SAN_FRANCISCO_LOCATION; } } if (location != null) { placePickerFragment.setLocation(location); placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS); placePickerFragment.setSearchText(SEARCH_TEXT); placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT); placePickerFragment.loadData(false); } else { onError(getResources().getString(R.string.no_location_error), true); } } catch (Exception ex) { onError(ex); } } }