我可以在我的片段中授予或拒绝权限,但我在尝试授予权限时尝试调用某个方法,但它似乎无法调用。
public final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 1;
我 n onCreateView():(这有效)
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
retrieveGyms();
} else {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_COARSE_LOCATION);
}
从对话框授予权限时,不会调用retrieveGyms(),但会授予权限。
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_COARSE_LOCATION: {
if (permissions.length == 1 && permissions[0] == Manifest.permission.ACCESS_COARSE_LOCATION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
retrieveGyms();
} else {
// Location permission denied.
}
}
}
}
显示retrieveGyms()只是为了展示它的作用和我期待的内容
public void retrieveGyms() {
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://gyminyapp.azurewebsites.net/api/Gym", null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
gymsArray = response;
// HashMap<String, Object> returnedGyms = new HashMap<String, Object>();
for (int i = 0; i < gymsArray.length(); i++) {
try {
// TODO: check distance from current user location and remove if not within search radius
String latitude = gymsArray.getJSONObject(i).getString("latitude");
String longitude = gymsArray.getJSONObject(i).getString("longitude");
Double doubleLat = Double.parseDouble(latitude);
Double doubleLong = Double.parseDouble(longitude);
LatLng gymCoord = new LatLng(doubleLat, doubleLong);
String name = gymsArray.getJSONObject(i).getString("name");
Object gymAddress = gymsArray.getJSONObject(i).get("address");
JSONObject gymAddressJSONObj = (JSONObject)gymAddress;
String streetAddress = gymAddressJSONObj.getString("streetAddress");
String city = gymAddressJSONObj.getString("city");
String state = gymAddressJSONObj.getString("state");
int zipCode = gymAddressJSONObj.getInt("zipCode");
String zipCodeString = Integer.toString(zipCode);
String addressString = streetAddress + " " + city + ", " + state + " " + zipCodeString;
Marker marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker))
.flat(false)
.title(name)
.snippet(addressString)
.position(gymCoord));
// Add marker to markers array
markers.add(marker);
} catch (JSONException e) {
e.printStackTrace();
}
// Zoom map to fit all markers
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
int padding = 75;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cameraUpdate);
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable e) {
}
});
}