user1301428
user1301428

Reputation: 1783

GPS stays always on after launching Android app

In an app I am working on I am getting the GPS coordinates of the device inside the activity's onCreate() method. However, even after launching the app, I see the location services icon that keeps flashing in the notifications bar of the device, it this expected or should it go away after getting the position of the device?

This is my code at the moment:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_DENIED)
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        1);
            Criteria criteria = new Criteria();
            LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            lm.requestLocationUpdates(lm.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                }

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

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            });
            // Get latitude and longitude
            Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            longitude = location.getLongitude();
            latitude = location.getLatitude();

Upvotes: 1

Views: 335

Answers (1)

1615903
1615903

Reputation: 34733

You are never telling LocationManager to stop providing location updates. To do that, call LocationManager.removeUpdates() with the correct listener as argument.

Alternatively, you can use LocationManager.requestSingleUpdate(...) which automatically stops providing updates after the first location.

Upvotes: 1

Related Questions