我在 LocationManager 调用权限中放入什么 if 语句

What do I put into LocationManager call permission if statement

我一直在查看 Whosebug 和搜索网站,发现了很多不同的答案或过时的答案,所以我不确定如何回答这个问题。我正在尝试获取用于我的应用程序的纬度和经度。我已经到了我知道使用位置管理器的地步,但随后它需要调用 permission.I 我试图找到关于如何使用它的解决方案,但有太多的答案,关于是否这些答案是正确的。这是我的代码,有人能帮我找到解决方案吗?在位置管理器的调用权限中放什么?这段代码是否能给我经度和纬度?结果将在片段中使用。

这些是我的清单 file:ACCESS_FINE_LOCATION、互联网和 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
        }
    }
}