问题的标题几乎概括了我想问的内容。所以我有代码来获取当前城市的名称,LocationManager.NETWORK_PROVIDER
它就像一个魅力。但是出现了一个问题:“如果手机无法获取城市名称会怎样LocationManager.NETWORK_PROVIDER
?”。当然,我找到了那部手机:由于某些原因,联想手机无法使用LocationManager.NETWORK_PROVIDER
. 所以我的问题是如何让我的应用程序首先查找坐标以获取城市名称,LocationManager.NETWORK_PROVIDER
如果结果为 null 以获取坐标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);
}
我得到了这个城市的名字:
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();
}
}