I am having trouble understanding the whole obtain user locations. I followed a tutorial for LocationManager. It gets the last known location from the GPS provider. From what I can tell is some user do not have a last know location and it returns NULL.
I assumed that this code below would if NULL would use the GPS and attempt to obtain a user location. But it does not. How can I force android to retrieve a user location? And not just display my NULL message and not work?
setContentView(R.layout.beer_location_list);
String title = "Nearby Breweries";
TextView topTitle = (TextView) findViewById(R.id.beerLocationTitle);
topTitle.setText(title);
//get user location
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
double longitude = location.getLongitude();
double latitude = location.getLatitude();
//construct url
String url = "myURl";
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
else{
//pop toast saying cant get location
Toast.makeText(getApplicationContext(), "Can not get your location at this time", Toast.LENGTH_LONG).show();
}
Update:
after looking at some of the responses, why can I not doing something like this to just get the users location each time he opens this activity:
final LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
LocationListener listener = new LocationListener();
manager.requestSingleUpdate(criteria, listener, null);
and I override location listener with
@Override
public void onLocationChanged(Location lastKnownLocation) {
if (lastKnownLocation != null) {
// whatever needs to be done
}
}
But I am getting the error: LocationListener is abstract cannot be instantiated on the line new LocationListener();