我有这个代码,要求您获取用户所在位置的权限,但是当用户接受时,它不会转到函数" onRequestPermissionsResult",我已经检查了它" logi",我希望当用户接受请求时," onRequestPermissionsResult"被称为该功能,谢谢大家!
public class PerdidosMapa_Fragment extends Fragment {
// BitmapDescriptor pin = BitmapDescriptorFactory.fromResource(R.drawable.pin);
public PerdidosMapa_Fragment() {
// Required empty public constructor
}
MapView mMapView;
private GoogleMap googleMap;
ArrayList<LatLng> markerPoints;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_perdidosmap, container, false);
mMapView= (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
if (checkLocationPermission()) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
googleMap.setMyLocationEnabled(true);
}
}
markerPoints = new ArrayList<LatLng>();
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
//PER CRIDAR BASE DE DADES FIREBASE PERDIDOS BASE DADES FIREBASE
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference perdidosUbiRef = rootRef.child("Perdidos");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
LatLng ubicacion;//ubicacion va canviant a mesurea recorrent base de dades
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String descripcion = ds.child("descripción").getValue(String.class);
Float Lat = ds.child("ubicación").child("lat").getValue(Float.class);
Float Long = ds.child("ubicación").child("long").getValue(Float.class);
ubicacion = new LatLng(Float.parseFloat(String.valueOf(Lat)), Float.parseFloat(String.valueOf(Long)));//crea markers
googleMap.addMarker(new MarkerOptions()
.position(ubicacion).
title(name)
.snippet(descripcion)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.icomap))
);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
perdidosUbiRef.addListenerForSingleValueEvent(eventListener);
//AGAFA UBICACIÓ INICIAL USUARI I DIRECCIONA CAMARA
LocationManager mgr = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = mgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location location;
if(network_enabled) {//si internet va
if (checkLocationPermission()) {
location = mgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);// i permis concedit et pilla ultima ubicacio
if (location != null) { //agafa posició de location que agafa ubicació per la xarxa no pel GPS. al carregar el mapa i posa la camara
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition
(cameraPosition));
}
mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1f, new LocationListener() {
@Override
public void onLocationChanged(Location location) {//cada vegada qe es canvia ubicació crida aquesta funció
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
});
}
}
}
});
return rootView;
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(getActivity())
.setTitle("")
.setMessage("")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1);
}
return false;
} else {
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.i("locationPermission", "onRequestPermissionsResult: Entra a la funció ");
switch (requestCode) {
case 1:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
Log.i("locationPermission", "onRequestPermissionsResult: Dóna localització al permetre el permis ");
}
} else {
}
return;
}
}
}
}
onRequestPermissionsResult方法:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.i("locationPermission", "onRequestPermissionsResult: Entra a la funció ");
switch (requestCode) {
case 1:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
Log.i("locationPermission", "onRequestPermissionsResult: Dóna localització al permetre el permis ");
}
} else {
}
return;
}
}
}
答案 0 :(得分:1)
在“片段”中,当您请求用户许可时,应使用requestPermissions()
而不是ActivityCompat.requestPermissions()
答案 1 :(得分:0)
尝试覆盖片段的父Activity而不是片段中的onRequestPermissionResult。