这个问题的标题很好地概括了我想问的问题。因此,我有使用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();
}
}发布于 2014-02-24 17:34:34
使用此参数:
3.getSubLocality();
If you want in detail you should prefer
发布于 2014-02-24 17:50:11
当提供者请求位置更新时,不保证返回位置更新。仅当位置更改时才调用方法onLocationChanged()。如果你将使用Network_provider来获取位置更新,那么返回位置更新将需要很长时间。在这种情况下,u可以启动定时器,并且当定时器到期时,u可以从GPS_provider获得位置更新。否则,只需简单地执行下面的操作
myLocObj = new MyLocationListener();
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
nw = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if( nw ){
Toast.makeText(BasicArchitectActivity.this, "fetching from NW", Toast.LENGTH_LONG).show();
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, myLocObj);
}
gps = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if( gps ){
Toast.makeText(BasicArchitectActivity.this, "fetching from GPS", Toast.LENGTH_LONG).show();
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLocObj);
}
if(!gps && !nw){
Toast.makeText( MainActivity.this, "Please enable GPS and Network positioning in your Settings ", Toast.LENGTH_LONG ).show();
}这是location监听器
class MyLocationListener implements LocationListener{
double currentlat, currentlng;
@Override
public void onLocationChanged(Location location) {
if(location != null){
currentlat = location.getLatitude();
currentlng = location.getLongitude();
Toast.makeText(BasicArchitectActivity.this, "Current location \nlat= " +currentlat+", lng= " + currentlng , Toast.LENGTH_SHORT).show();
}
}https://stackoverflow.com/questions/21983567
复制相似问题