我一直在寻找stackoverflow和搜索站点,发现了很多不同的答案或过时的答案,所以我不确定如何回答这个问题。我正在尝试获取要用于我的应用的纬度和经度。我已经知道要使用位置管理器了,但是它要求调用权限。我试图找到如何使用它的解决方案,但是答案很多,对于这些答案是否有很多不同的看法。正确。这是我的代码,是否可以帮助我找到解决方案,以解决位置管理器的呼叫权限中的内容以及此代码是否可以使我获得经度和纬度?结果将用于片段中。
这些是清单文件中的权限:ACCESS_FINE_LOCATION,INTERNET和 ACCESS_COARSE_LOCATION。
public class LocationFinder extends TestFragment implements LocationListener {
private static final String TAG = "LocationFragment";
private LocationManager mLocationManager;
private static double latitude;
private static double longitude;
public LocationFinder() {
mLocationManager =(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
@Override
public void onStatusChanged(String s) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
public static double getLatitude(){
return latitude;
}
public static double getLongitude(){
return longitude;
}
}
答案 0 :(得分:0)
要检查应用程序对ACCESS_FINE_LOCATION
的权限,请像执行操作一样运行checkSelfPermission
:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { }
如您的待办事项所述,您需要调用requestPermissions:
ActivityCompat.requestPermissions(this, new String[{Manifest.permission.ACCESS_FINE_LOCATION}, 378);
其中378
是您喜欢的任何整数(用于检查请求结果):
接下来,必须通过覆盖方法来处理请求的结果:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 378) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// do whatever you need with permissions
} else {
// display a message or request again
}
}
}