You are getting it from LocationManager::getLastKnownLocation()

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Answer from azizbekian on Stack Overflow
Top answer
1 of 2
1

You are getting it from LocationManager::getLastKnownLocation()

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
2 of 2
1

This is my code its working for my App. You can try it to fetch the Location.

 ro_gps_icon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            if (ActivityCompat.checkSelfPermission(RODetailsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(RODetailsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }           locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, (LocationListener) RODetailsActivity.this);
            Criteria criteria = new Criteria();
            String bestProvider = locationManager.getBestProvider(criteria, true);
            Location location = locationManager.getLastKnownLocation(bestProvider);

            if (location == null) {
                Toast.makeText(getApplicationContext(), "GPS signal not found", Toast.LENGTH_SHORT).show();
            }
            if (location != null) {
                Log.e("locatin", "location--" + location);

                Log.e("latitude at beginning",
                        "@@@@@@@@@@@@@@@" + location.getLatitude());
                onLocationChanged(location);
            }
        }
    });

and method for getting the data.

public void onLocationChanged(Location location) {
    Geocoder geocoder;
    List<Address> addresses;
    geocoder = new Geocoder(this, Locale.getDefault());

    double latitude = location.getLatitude();
    double longitude = location.getLongitude();

    Log.e("latitude", "latitude--" + latitude);
    try {
        Log.e("latitude", "inside latitude--" + latitude);
        addresses = geocoder.getFromLocation(latitude, longitude, 1);
        if (addresses != null && addresses.size() > 0) {
            String address = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getLocality();
            String state = addresses.get(0).getAdminArea();
            String country = addresses.get(0).getCountryName();
            String postalCode = addresses.get(0).getPostalCode();
            String knownName = addresses.get(0).getFeatureName();

            ro_gps_location.setText(state + " , " + city + " , " + country);
            ro_address.setText(address + " , " + knownName + " , " + postalCode);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
🌐
Stack Overflow
stackoverflow.com › questions › 25496726 › getting-location-when-button-is-clicked
android - Getting location when button is clicked - Stack Overflow
March 30, 2017 - When I click on a button, it creates a locationManager and requestLocationUpdates and sends the web service with the GPS coordinates retrieved from the LocationManager and then removelistener in the AsyncTask. The problem is that when I click the button it's not able to get the location every time as the LocationManager is not able to get the GPS coordinates instantly, but only in the onLocationChanged callback.
🌐
Google
developers.google.com › google maps platform › android › maps sdk for android › select current place and show details on a map
Select Current Place and Show Details on a Map | Maps SDK for Android | Google for Developers
Use the Places SDK for Android to get a list of likely places at the device's current location. In this context, a place is a business or other point of interest. This tutorial gets the current place when the user clicks a Get Place button. It offers the user a list of likely places to choose from, then adds a marker on the map at the location of the selected place.
Top answer
1 of 3
12

Yogsma's answer addresses how to receive automatic updates. The link he references provides all you need, but here is the summarized version of how to do a manual update:

Assuming you've read the tutorials on how to make a button, then you simply need to add a listener for your button, and then have the listener call a function to query your location manager. The code below does it all inline to show you how, but I'd instantiate LocationManager somewhere else (eg your activity) and I'd create a separate method for the on click listener to call to perform the update.

// getLocationButton is the name of your button.  Not the best name, I know.
getLocationButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // instantiate the location manager, note you will need to request permissions in your manifest
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // get the last know location from your location manager.
        Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        // now get the lat/lon from the location and do something with it.
        nowDoSomethingWith(location.getLatitude(), location.getLongitude());
    }
});

Of course you will also need to register your activity with the location manager service in your manifest xml file:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2 of 3
7
LocationManager mLocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
                LocationListener mLocListener = new MyLocationListener();
                mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocListener);

public class MyLocationListener implements LocationListener{        

        public void onLocationChanged(Location loc) {           
            String message = String.format(
                        "New Location \n Longitude: %1$s \n Latitude: %2$s",
                        loc.getLongitude(), loc.getLatitude()
                );
                Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
        }
        public void onProviderDisabled(String arg0) {

        }
        public void onProviderEnabled(String provider) {

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

        }       
    }

Read this for detail http://www.javacodegeeks.com/2010/09/android-location-based-services.html

🌐
The Crazy Programmer
thecrazyprogrammer.com › home › how to get current location in android using location manager
How to Get Current Location in Android Using Location Manager
January 11, 2017 - locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Log.e(“Current Location”,”lat: “+location.getLatitude()+” Lon: “+location.getLongitude()); ... your code is not working just button is getting displayed when i clicked on that button,nothing got displayed
Top answer
1 of 3
4

this is what i am doing in my case :

MyLocation class :

import android.app.ProgressDialog;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

public class MyLocation {
   // Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;
    AsyncTask<Context, Void, Void> mtask;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
      //  timer1=new Timer();
       // timer1.schedule(new GetLastLocation(), 20000);
        mtask= new GetLastLocation().execute();
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
           // timer1.cancel();
             mtask.cancel(true);
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
           mtask.cancel(true);
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    private Context mContext;
    public MyLocation(Context c) { this.mContext = c; }


    class GetLastLocation extends AsyncTask<Context, Void, Void>
    {

    ProgressDialog dialog = new ProgressDialog(mContext);

        protected void onPreExecute()
        {
           dialog.setMessage("Searching....");
           dialog.show();
        }

        protected Void doInBackground(Context... params)
        {
          Handler mHandler = new Handler(Looper.getMainLooper());



                       // ...
                       mHandler.post(new Runnable() {
                         public void run() {
                         lm.removeUpdates(locationListenerGps);
                         lm.removeUpdates(locationListenerNetwork);

                         Location net_loc=null, gps_loc=null;
                         if(gps_enabled)
                             gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                         if(network_enabled)
                             net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                         //if there are both values use the latest one
                         if(gps_loc!=null && net_loc!=null){
                             if(gps_loc.getTime()>net_loc.getTime())
                                 locationResult.gotLocation(gps_loc);
                             else
                                 locationResult.gotLocation(net_loc);
                             return;
                         }

                         if(gps_loc!=null){
                             locationResult.gotLocation(gps_loc);
                             return;
                         }
                         if(net_loc!=null){
                             locationResult.gotLocation(net_loc);
                             return;
                         }
                         locationResult.gotLocation(null);
                    }
                       });
                       // ...


            return null;
        }

        protected void onPostExecute(final Void unused)
        {
            dialog.dismiss();
        }
    }





    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

and the method for button click :

MyLocation myLocation = new MyLocation();
private void locationClick() {
myLocation.getLocation(this, locationResult));
}

public LocationResult locationResult = new LocationResult(){
@Override
public void gotLocation(final Location location){
    //Got the location!
    });
}
};

I have found this from an older post in stackoverflow when i was looking solution for the similar issue......

2 of 3
1

You have use this method to check all enable providers

void requestLocationUpdates()
    {
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        List<String> enabledProviders = this.locationManager.getProviders(true);
        for (String provider:enabledProviders){
            Log.i(">>>>>>>", "Requesting location updates from provider " + provider);
            this.locationManager.requestLocationUpdates(provider, 10000l, 10, this);
        }
    }
Find elsewhere
🌐
findnerd
findnerd.com › list › view › How-to-get-Latitude-and-Longitude-On-a-button-click-using-GPS › 9195
How to get Latitude and Longitude On a button click using GPS?
October 28, 2015 - @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnMyLocation=(Button)findViewById(R.id.btnMyLocation); tvMyLocation=(TextView)findViewById(R.id.tvMyLocation); btnMyLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gps = new GPSTracker(MainActivity.this); // check if GPS enabled if(gps.canGetLocation()){ double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); // \n is for new line // Toast.makeText(getApplicationContext(), "Your Location
🌐
Stack Overflow
stackoverflow.com › questions › 10565365 › how-to-get-a-current-location-on-map-after-clicking-button-in-android-project
How to get a current location on map after clicking button in android project? - Stack Overflow
Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setPowerRequirement(Criteria.POWER_LOW); LocationManager locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if(locManager.getBestProvider(criteria,true) != null){ Location myLocation= locManager.getLastKnownLocation(locManager.getBestProvider(criteria, true)); String latitude = Double.toString(myLocation.getLatitude()); String longitude = Double.toString(myLocation.getLongitude()); String altitude = Double.toString(myLocation.getAltitude()); }
🌐
Google
developers.google.com › google play services › googlemap.onmylocationbuttonclicklistener
GoogleMap.OnMyLocationButtonClickListener | Google Play services | Google for Developers
April 27, 2021 - The GoogleMap.OnMyLocationButtonClickListener interface is used for callbacks when the My Location button is clicked · The onMyLocationButtonClick method is called on the Android UI thread when the my location button is clicked
🌐
GeeksforGeeks
geeksforgeeks.org › android › how-to-get-current-location-in-android
How to Get Current Location in Android? - GeeksforGeeks
{ super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initialize the TextView and Button from the layout locationText = findViewById(R.id.locationText) val getLocationBtn = findViewById<Button>(R.id.getLocationBtn) // Initialize the location provider client locationClient = LocationServices.getFusedLocationProviderClient(this) // Set a click listener for the button to get the current location getLocationBtn.setOnClickListener { getCurrentLocation() } } // Function to get the current location private fun getCurrentLocation() { // Check if the location permission is gran
Published   July 23, 2025
🌐
Stack Overflow
stackoverflow.com › questions › 37936693 › how-do-i-get-android-location-once-at-the-push-of-a-button
java - How do I get android location once at the push of a button? - Stack Overflow
June 21, 2016 - @Override public void onLocationChanged(Location location) { currentLattitude = location.getLatitude(); currentLongitude = location.getLongitude()); } @Override public void onProviderDisabled(String provider) { Log.d("Latitude","disable"); } @Override public void onProviderEnabled(String provider) { Log.d("Latitude","enable"); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("Latitude","status"); } With this, you can get your location via on click of your button.
🌐
Blogger
sccm11.blogspot.com › 2013 › 05 › android-get-current-gps-location-on.html
Android get current GPS location On Button Click
public class AndroidGPSTrackingActivity extends Activity { Button btnShowLocation; // GPSTracker class GPSTracker gps; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnShowLocation = (Button) findViewById(R.id.btnShowLocation); // show location button click event btnShowLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // create class object gps = new GPSTracker(AndroidGPSTrackingActivity.this); // check if GPS enabled if(gps.canGetLocation()){ double latitude = gp