【发布时间】:2021-11-20 21:18:20
【问题描述】:
我在MainActivity 的onCreate() 和onResume() 方法中调用了这个方法。
基本上,我使用它是为了获取当前位置的城市名称并将其设置为字符串,以便以后使用。 为了看看它是否有效,我只是将它设置为我的欢迎文本。
方法是:
private void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if (location != null) {
try {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
cityName = addresses.get(0).getLocality(); // sets the address here
Welcome.setText(cityName);
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, "Location null error", Toast.LENGTH_SHORT).show();
}
}
});
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},44);
}
}
问题是,当我在 android studio 模拟器上时,它在大多数情况下都可以正常工作。
但是当我在手机上运行应用程序时,我得到了我设置的“位置空错误”toast。 意思是位置为空。即使在设备设置中打开了位置信息。
我不知道是什么问题。
【问题讨论】:
标签: java android geolocation location android-gps