Hello
Please help me get a location for a weather query. I get that in most cases the LocationManager returns null .
Either geolocation is always on, or the application heavily loads the system and consumes the battery.
The getLocation method returns null in 90% of cases, sometimes the correct coordinates. The getCoordinates method returns default coordinates, despite the fact that updated data is output to the log from the onLocationChanged method.
The essence of the question: just get one-time coordinates at the user's request and immediately disable the geolocation request.
Here is the root of evil
public class Locator { private static final int UPD_PERIOD = 1000 * 3600; private static final String TAG = Locator.class.getSimpleName(); private LocationManager locationManager; private LocationListener locationListener; private double mAltitude; private double mLatitude; private double mLongitude; private Location location; private Location defaultLocation; private Context context; public Locator(Context context) { mAltitude = 0d; mLatitude = 0d; this.context = context; defaultLocation = new Location(LocationManager.PASSIVE_PROVIDER); defaultLocation.setLongitude(-118.21d); defaultLocation.setLatitude(34.03d); mLatitude = 34.03d; mLongitude = -118.21d; locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { mAltitude = location.getAltitude(); mLatitude = location.getLatitude(); mLongitude = location.getLongitude(); Log.d(TAG, location.toString()); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { Log.d(TAG, "onStatusChanged"); } @Override public void onProviderEnabled(String s) { Log.d(TAG, "onProviderEnabled"); } @Override public void onProviderDisabled(String s) { Log.d(TAG, "onProviderDisabled"); } }; locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE); try { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, UPD_PERIOD, 0, locationListener); } catch (SecurityException se) { Log.e("__security_exception__", se.getMessage()); } } public Location getLocation() throws SecurityException { /* locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener); */ location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); return location; } public double[] getCoordinates() { return new double[] { mLatitude, mLongitude }; } }
removeLocationUpdates, but how to call it? As soon as theLocationis notnull? .. - Skotinin