2

I'm developing an android application which is supposed to get the location of the android device when the activity is created (onCreate). But it returns 0 longitude and 0 latitude when activity is created. When I click the button, the location is then fetched.

How can I get the location when the activity starts, instead of getting the location after clicking on the button?

-All permissions are granted

-I'm calling the same functions in onCreate() and onClick() to get the location.

-I'm using googleAPI to get the location of the device

Payal Sorathiya
  • 756
  • 1
  • 8
  • 23
Ali Haider
  • 374
  • 2
  • 3
  • 14
  • What you are trying to achieve maybe will work with LastKnownLocation that you will get from LocationManager. Location is not something instant, you should register to location listener and get the location in the Callback. Do not expect it synchronously – matrix Nov 24 '17 at 08:00
  • https://stackoverflow.com/questions/16981238/do-something-before-oncreate – jakir hussain Nov 24 '17 at 08:09

2 Answers2

1

try using the function in onStart() or onResume(), it can work

Dheeraj Joshi
  • 1,522
  • 14
  • 23
  • I have tried it, but It does not show the location unless I minimize my application and then open it again. – Ali Haider Nov 24 '17 at 08:05
1

It should work, try something like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

and to get the location and update the UI, use onLocationChanged

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        //your code here (update UI, etc.)
    }
};
jorjSB
  • 610
  • 4
  • 12