Android LocationManager obtains longitude and latitude information

Article directory

I. positioning introduction

You can also use Android without using the third-party map SDK
Its own positioning API can realize the relevant geographic location functions. For the official introduction, see here (need to climb the wall):

The following pits need to be noted when using LocationManager:
(1) if the location is only based on the time, it is found that the minimum allowable time is 20 seconds after testing. If the time is lower than this time set in the code, 20 seconds will be used as the location interval.
(2) when acquiring the number of satellites, try to be in an open place outdoors, and at the same time, add the signal-to-noise ratio judgment, otherwise it is easy to acquire more satellites
(3) add relevant permissions in the Manifest and have done the runtime permission processing code. If the requestLocationUpdates method is still red, only add comments to solve the problem


Two, code

1. Instantiate LocationManager

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

2. Processing runtime permissions

 if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    new String[]{
                    }, 100);
        } else {

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // Camera permissions
            case 100:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //The user clicks agree to authorize
                } else {
                    //User denied authorization
                    Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();

3. Start request location

 		long minSecond = 15 * 1000;
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minSecond, 0, listener);//LocationManager.GPS_PROVIDER
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minSecond, 0, listener);//LocationManager.NETWORK_PROVIDER

4. Positioning monitor

 public final LocationListener listener = new LocationListener() {
        public void onLocationChanged(Location location) {

        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                // When GPS status is visible
                case LocationProvider.AVAILABLE:
                    Log.i("xml", "current GPS Status is visible");
                // When GPS status is outside the service area
                case LocationProvider.OUT_OF_SERVICE:
                    Log.i("xml", "current GPS Status is out of service area");
                // When GPS status is out of service
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    Log.i("xml", "current GPS Status is suspended");

        public void onProviderEnabled(String provider) {


        public void onProviderDisabled(String provider) {

5. Update positioning

Key core code, show the results on textview

private Location updateLocation(Location location) {
        String result;
        double lat = 0;
        double lon = 0;
        double speed = 0;
        int stars = 0;

        if (location != null) {
            lat = location.getLatitude();
            lon = location.getLongitude();
            speed = location.getSpeed();
            GpsStatus gpsStatus = locationManager.getGpsStatus(null);
            int maxSatellites = gpsStatus.getMaxSatellites();
            //Create an iterator to hold all satellites
            Iterator<GpsSatellite> satelliteIterator = gpsStatus.getSatellites().iterator();
            int count = 0;
            while (satelliteIterator.hasNext() && count <= maxSatellites) {
                GpsSatellite s =;
                // Only when the signal-to-noise ratio is not 0, the satellite is qualified
                if (s.getSnr() != 0) {

            stars = count;

            result = "Latitude:" + lat + "\n Longitude:" + lon + "\n Speed:" + speed + "\n Number of satellites:" + stars;
            Log.i("xml", "Display result = " + result);
        } else {
            result = "Unable to get longitude and latitude information";
        if (lat != 0) {
            Log.i("xml", "---feedback information---" + String.valueOf(lat));
        Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
        return location;

III. Demo download

Download address here (to be provided later)

Keywords: xml Android SDK Permission denied

Added by bunner bob on Sun, 03 Nov 2019 02:22:17 +0200