It turned out to make the definition of coordinates:

public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { private LocationManager locationManagerGPS; locationManagerGPS.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListenerGPS); }; public static LocationListener locationListenerGPS = new LocationListener() { @Override public void onLocationChanged(Location locationGPS) { System.out.println(Double.toString(locationGPS.getLongitude())); System.out.println(Double.toString(locationGPS.getLatitude())); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; } 

But coordinates are determined only when the location changes. Is it possible to determine the current location by clicking a button?

Ie, for example, there was some kind of movement, coordinates were determined, arrived at the scene, you need to know the location of the stop, clicked on the "finish" button and the current coordinate is determined.

  • In general, your data is updated not only when the location changes, but every 5 seconds. It is better to use (LocationManager.NETWORK_PROVIDER, 0,0, locationListenerGPS) in order to immediately find out the coordinates. - iFr0z

1 answer 1

Just in onLocationChanged, save the last received coordinates, and when you click on the button, use them.

To increase the frequency of determining the coordinates and accuracy, set the parameters LOCATION_REFRESH_TIME and LOCATION_REFRESH_DISTANCE.

 locationManagerGPS.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, locationListenerGPS); 

Or you can use the last coordinates that the system remembered (but this is not the best option)

  if (locationManager != null) { location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } 
  • I didn’t use the last coordinates at all. I tried to set the minimum update time to 0, but this only works when GPS is activated when activating, but it eats charging, and when enabled by click, the coordinates are not determined - Miwqa
  • Do you fundamentally use only GPS? - Lex Hobbit
  • @Miwqa Do you need to receive data once or sometime? - iFr0z
  • @LexHobbit, at the moment yes - Miwqa
  • @ iFr0z, once, I made a service that runs once in a while and determines the coordinates, now I need, as it were, to complete the movement on a click - Miwqa