我有一个应用程序可以获取位置并获取用户所在城市的天气。天气是从城市名称中获取的(应该是特定的)。我使用以下代码获取位置:
LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locLis = new MyLocationListener();
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locLis);
Location location = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
response.setText("Last Known Location Is " + location);
try {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder geocoder = new Geocoder(MainActivity.this,Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude,longitude, 1);
address = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getAddressLine(1);
country = addresses.get(0).getCountryName();
String text = "Location from Last: " + address + " ," + city + " ," + country;
response.setText(text);
} catch (Exception e) {
response.setText("Location Exception : " + e);
}
返回“Tanta,Qesm 2”我只想要“Tanta”,我也尝试使用addresses.get(0).getLocality()但它返回null,因为位置未知..
那么,有什么想法吗?:)