Get current location (gps / wifi)

I am trying to set up my location like this:

LocationManager myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

Criteria criteria = new Criteria(); 
criteria.setAccuracy(Criteria.ACCURACY_FINE); 
criteria.setAltitudeRequired(false); 
criteria.setBearingRequired(false); 
criteria.setCostAllowed(true); 
criteria.setPowerRequirement(Criteria.POWER_LOW); 

String provider = myLocationManager.getBestProvider(criteria,true); 

if (provider != null) { 
    //there is a provider
    myLocationManager.requestLocationUpdates(provider, 10L, 500.0f, (LocationListener) mainContext);
    Location myCurLocation = myLocationManager.getLastKnownLocation(provider); 
            //here i'm trying to get some data from the
            //myCurLocation but 
            //myCurLocation == NULL
}

but myCurLocation is always == NULL

What am I doing wrong?

+3
source share
1 answer

The call is getLastKnownLocation()not blocked - this means that it will return nullif there is currently no position, so you probably want to look at the transfer LocationListenerinstead of the requestLocationUpdates()method , which will give you asynchronous updates of your location.

See this question for an example useLocationListener .

+8
source

Source: https://habr.com/ru/post/1742468/


All Articles