问题的标题几乎总结了我想问的问题。所以我有代码使用LocationManager.NETWORK_PROVIDER
获取当前城市的名称,它就像一个魅力。然而,出现了一个问题:“如果手机无法使用LocationManager.NETWORK_PROVIDER
获取城市名称,会发生什么?”。当然我发现手机:由于某些原因,LENOVO手机无法使用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();
}
}
答案 0 :(得分:0)
使用此参数:
答案 1 :(得分:0)
如果提供商请求位置更新,则无法保证返回位置更新。只有在更改位置时才会调用onLocationChanged()方法。如果您将使用Network_provider获取位置更新,则返回位置更新将花费很多时间。在这种情况下,你可以启动一个计时器,当它到期时你可以从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();
}
这是位置监听器
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();
}
}