1

i'm new in java/android app and i'm creating an app that uses user-location. I want the location to be updated at the begining of the app. The problem is that my location class is an activity and i don't want to show another contentview for this class. Actually, i want the location thing to be done in background, without changing the UI, in a separated class.

Is it possible? How?

Thanks :P

Quentin DOMMERC
  • 876
  • 1
  • 8
  • 24
  • In Android O above code is not work. Check my comments in https://stackoverflow.com/questions/51187231/get-locationupdates-in-background-service-countinuously/51188196#51188196. – KetanD Jul 05 '18 at 10:03
  • In Android O above code is not work. Check my comments in https://stackoverflow.com/questions/51187231/get-locationupdates-in-background-service-countinuously/51188196#51188196 – KetanD Jul 05 '18 at 10:04

2 Answers2

4

There is no need to put the location in a different activity, the LocationManager already does it in the background:

public void getLocation(){
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    gpsLocationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLocationChanged(Location location) {
                    //do something with the new location
        if (location != null)
            gpsLocation = location;

        }
    };

      gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);


      lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 0, gpsLocationListener);



}
eladrich
  • 755
  • 1
  • 5
  • 15
3

Using the LocationManager you should be able to use what ever kind of activity (or service) you want.

Marcin Gil
  • 68,043
  • 8
  • 59
  • 60
Fredrik Leijon
  • 2,792
  • 18
  • 20