我想在我的 Android 应用程序中获取用户当前的城市名称,但根据我的一些研究( this 、 this 和 this ),这是一项非常复杂的任务,需要在网络提供商和获取之间切换一段时间后位置更新。
我的应用程序不是一些基于位置的应用程序,需要使用该应用程序的用户提供准确且最新的位置。我只需要 NETWORK_PROVIDER(或任何其他提供商)提供的城市名称,但如果无法获取城市名称,也没关系。这只是应用程序中的一项功能,如果在某些情况下无法获取城市名称也没关系。
我正在使用以下代码,但它始终显示纬度
和经度
均为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) {
}
最佳答案
您在这里所做的就是创建一个新的 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
接口(interface)也可以由保存此代码的 Activity
实现,然后您只需将该 Activity 的上下文作为 locationManager.requestLocationUpdates(provider, 20000, 0, context);
。当然,与任何接口(interface)实现一样,您必须以与上面代码相同的方式重写所有方法。
就requestLocationUpdates()
方法而言,您可以read more about it here
就 Android 上获取用户位置的一般技术而言,this is a definite read
关于android - Android 中获取用户当前所在城市,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25955940/