androidlocationmanager

Android LocationManager locationManager.requestLocationUpdates() not working


hi guys i am trying to get current location with location manager, i am using this below code

LocationManager locationManager = (LocationManager) 
getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider =locationManager.getBestProvider(criteria,true);

        Location location = 
locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0,this);

But i am not getting any response for this line

locationManager.requestLocationUpdates(bestProvider, 20000, 0,this);

and also getting lastknown location as null, i have added all permissions in manifest as well as dynamic, but this above line is not giving any response, i searched for it but dint get and relevant answer , please help.


Solution

  • For the getLastKnownLocation method, it is said in the documentation :

    If the provider is currently disabled, null is returned.

    Which means your GPS is disabled.

    For the requestLocationUpdates, you are requesting a location every 20 seconds, try to decrease this number so you know at least if your program is working.

    You can try this :

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    

    Also I really advise you to use the new API to request location updates : https://developer.android.com/training/location/receive-location-updates.html

    It is very fast and accurate, but you need to create a google developer account (for free) and create an api key. All needed information should be in the link.