The title of the question pretty much sums up what I want to ask. So I have the code to get the name of the current city using LocationManager.NETWORK_PROVIDER
and it works like a charm. However a question popped up: "What will happen if the phone cant get the name of the city using LocationManager.NETWORK_PROVIDER
?". And of course I found that phone: for some reasons LENOVO phones cant get the coordinates using LocationManager.NETWORK_PROVIDER
. So my question how can I make my app first to look for the coordinates to get the name of the city using LocationManager.NETWORK_PROVIDER
and if the result is null to get the coordinates using LocationManager.GPS_PROVIDER
?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_where_am_i);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
and I get the name of the city with:
public void onLocationChanged(Location location)
{
curLatitude = location.getLatitude();
curLongitude = location.getLongitude();
try{
//Get the name of the city the user is currently in base on the current latitude and Longitude
Geocoder gcd = new Geocoder(this, Locale.UK);
List<Address> addresses = gcd.getFromLocation(curLatitude, curLongitude,1);
if (addresses.size() > 0)
{
StringBuilder cityName = new StringBuilder();
cityName.append(addresses.get(0).getLocality());
CityName = cityName.toString();
//Check if the user is in allowed cities
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}