我正在尝试使用地址解析器检测用户的位置,但是它仅检测位置的区域而不是城市。还有其他方法可以对用户所在城市进行地理位置定位,因为使用数组和自动填充文本是一个繁琐的过程。
这是我用于定位用户城市的代码
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]
{Manifest.permission.ACCESS_COARSE_LOCATION}, 1000);
} else {
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
assert locationManager != null;
Location location =
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
try {
assert location != null;
String city = hereLocation(location.getLatitude(),
location.getLongitude());
b.setText(city);
Toast.makeText(MainActivity.this, "Awesome you're
in " + city, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Please check if
your GPS is turned on", Toast.LENGTH_SHORT).show();
}
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1000: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
assert locationManager != null;
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
try {
assert location != null;
String city = hereLocation(location.getLatitude(),location.getLongitude());
b.setText(city);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,"Please check if your GPS is turned on ",Toast.LENGTH_SHORT).show();
}
}
else {
Toast t = Toast.makeText(this,"Permission not Granted",Toast.LENGTH_SHORT);
t.show();
}
break;
}
}
}
private String hereLocation(double lat, double lon)
{
String cityName = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(lat,lon,10);
if (addresses.size() > 0){
for(Address adr: addresses){
if (adr.getLocality() != null && adr.getLocality().length() > 0){
cityName = adr.getLocality();
break;
}
}
}
}catch (IOException e){
e.printStackTrace();
}
return cityName;
}
它在我的位置正常工作,但是如果我移到另一个地方,它会改变。