In real life you can never be sure to receive a location. User could have disabled location services so you first check if location services are enabled in onResume() (better than onCreate() since App can be created, sent to background, location services disabled, App back to foreground).
Then you can get LocationManager.getLastKownLocation for a provider BUT this can be null!
A better approach would be to use LocationManagers requestSingleUpdate() or requestLocationUpdates() on a background thread and update your UI once you received a location update.
Again, if the device has just booted and might not be connected to a network and might not be able to receive gps, then getLastKnownLocation() will return null!
Heres what I did to receive my location:
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestSingleUpdate(new Criteria(), new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.d(Constants.LOG_TAG, "Received single location update");
mainThreadHandler.post(new Runnable(){updateUI(location);});
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(Constants.LOG_TAG, "Status changed for single location update");
}
@Override
public void onProviderEnabled(String provider) {
Log.d(Constants.LOG_TAG, "Provider enabled for single location update");
}
@Override
public void onProviderDisabled(String provider) {
Log.d(Constants.LOG_TAG, "Provider disabled for single location update");
}
}, locationHandler.getLooper());