【发布时间】:2014-02-24 09:25:37
【问题描述】:
问题的标题几乎概括了我想问的问题。所以我有使用LocationManager.NETWORK_PROVIDER 获取当前城市名称的代码,它就像一个魅力。然而,出现了一个问题:“如果手机无法使用LocationManager.NETWORK_PROVIDER 获取城市名称会怎样?”。当然,我找到了那部手机:由于某些原因,联想手机无法使用LocationManager.NETWORK_PROVIDER 获取坐标。所以我的问题是如何让我的应用程序首先查找坐标以使用LocationManager.NETWORK_PROVIDER 获取城市名称,如果结果为空,则使用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();
}
}
【问题讨论】:
-
This link 可能对您有所帮助。尝试使用
GPSTracker获取lat和lng而不是位置管理器 -
但我想要的是在 GPS 和 NETWORK 提供商之间切换
标签: android localization gps provider city