I can not access the location of android device in onCreate() function

Viewed 40

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

2 Answers

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

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.)
    }
};
Related