在Android中获取用户当前城市

时间:2014-09-21 04:53:05

标签: android reverse-geocoding

我想在我的Android应用中获取用户当前的城市名称,但根据我的一些研究(thisthisthis),这是一个非常漂亮的复杂的任务,需要在网络提供商之间切换,并在一段时间后获取位置更新。

我的应用程序不是某些基于位置的应用程序,需要使用该应用程序的用户的准确和最新位置。我只需要NETWORK_PROVIDER(或任何其他提供商)的城市名称,但如果它无法获取城市名称,那也很好。它只是应用程序中的一个功能,如果无法在某些情况下获取城市名称,则无关紧要。

我使用了以下代码,但它始终显示latitudelongitude为0.0。

Location location = new Location(LocationManager.NETWORK_PROVIDER);
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
    Log.d("Lat-Lng", location.getLatitude()+","+location.getLongitude());
    // Doesn't really return anything as both latitude and longitude is 0.0.
    List<Address> address = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch(Exception e) {

}

1 个答案:

答案 0 :(得分:0)

你在这里所做的就是创建一个新的Location对象,其默认情况下纬度和经度的初始值为零。

您需要做的是将该位置连接到用户的GPS信息。

// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();

// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);

// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);

if(location != null) {
    Log.d("Lat-Lng", location.getLatitude()+","+location.getLongitude());
    getUserGeoInfo(location.getLatitude(), location.getLongitude());
}

// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.d("Lat-Lng", location.getLatitude()+","+location.getLongitude());
        getUserGeoInfo(location.getLatitude(), location.getLongitude());  
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}
};

// Set how often you want to request location updates and where you want to receive them
locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);

// ...

void getUserGeoInfo(double lat, double lon) {
    Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
    if (Geocoder.isPresent()) {
        List<Address> addresses = geoCoder.getFromLocation(lat, lon, 1);
        if (addresses.size() > 0) {
            // obtain all information from addresses.get(0)
        }
    }
}
例如,LocationListener接口也可以由保存此代码的Activity实现,然后您只将该活动的上下文作为{{1中的第三个参数传递}}。当然,与任何接口实现一样,您必须以与上述代码相同的方式覆盖所有方法。

locationManager.requestLocationUpdates(provider, 20000, 0, context);方法而言,您可以read more about it here

至于在Android上获取用户位置的一般技巧,this is a definite read