我一直在寻找堆栈溢出和搜索网站,并找到了很多不同的答案或过时的答案,所以我不知道如何回答这个问题。我试图获得用于我的应用程序的经度和经度。我已经知道要使用位置管理器然后它需要调用权限。我已经尝试找到如何使用它的解决方案但是有很多不同观点的答案是关于这些答案是否是正确。这是我的代码,有些可以帮助我找到解决方案,将什么放入位置管理器的呼叫权限以及这段代码是否能获得经度和纬度?结果将用于片段中。
这些是我的清单文件中的权限: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;
}
}
要检查应用程序对ACCESS_FINE_LOCATION
的权限,您可以像以前一样运行checkSelfPermission
:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { }
正如您的TODO所述,您需要调用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
}
}
}