您好我已经阅读了很多内容并且我不知道为什么在检索我自己的位置时我得到null,我在Android Studio模拟器和我自己的手机中进行测试并得到相同的null值。 这是我正在进行的整个代码:
public class mapaFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
private boolean mLocationPermissionGranted;
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
private Location ultimaLocalizacion;
private MapFragment fragment;
protected LocationManager locationManager;
private Cliente cliente;
private GoogleMap mMap;
private CameraPosition mCameraPosition;
private TextView textoError;
private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
private LocationRequest mLocationRequest;
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
cliente = getArguments().getParcelable("clienteSeleccionado");
}
}
//Implementa este metodo que es al que se llama en las lineas anteriores si no tienes permisos
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
createLocationRequest();
if (requestCode == PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION && requestCode == PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION) {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
LatLng latitudLongitud = new LatLng(ultimaLocalizacion.getLatitude(), ultimaLocalizacion.getLongitude());
CameraUpdateFactory.newLatLngZoom(latitudLongitud, 16);
mMap.setMapStyle(new MapStyleOptions(""));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latitudLongitud, 16));
mMap.addMarker(new MarkerOptions().position(latitudLongitud).title("Usted está aquí"));
mMap.addMarker(new MarkerOptions().position(new LatLng(cliente.getLatitud(), cliente.getLongitud())).title(cliente.getNombre()));
} else {
getActivity().findViewById(R.id.textoErrorMapa).setVisibility(View.VISIBLE);
getActivity().findViewById(R.id.mapView).setVisibility(View.GONE);
}
return;
}
updateLocationUI();
// other 'case' lines to check for other
// permissions this app might request
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_mapa, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.mapView);
fragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//
if (mGoogleApiClient == null) {
generarInstanciaClienteAPI();
}
}
protected synchronized void generarInstanciaClienteAPI() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.create();
//
// /*
// * Sets the desired interval for active location updates. This interval is
// * inexact. You may not receive updates at all if no location sources are available, or
// * you may receive them slower than requested. You may also receive updates faster than
// * requested if other applications are requesting location at a faster interval.
// */
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
//
// /*
// * Sets the fastest rate for active location updates. This interval is exact, and your
// * application will never receive updates faster than this value.
// */
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
//
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
ultimaLocalizacion = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
int permissionCheckFINE = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
int permissionCheckCOARSE = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
if ((permissionCheckFINE == PackageManager.PERMISSION_DENIED) || (permissionCheckCOARSE == PackageManager.PERMISSION_DENIED)){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
} else {
createLocationRequest();
mMap.setMyLocationEnabled(true);
LatLng latitudLongitud = new LatLng(ultimaLocalizacion.getLatitude(), ultimaLocalizacion.getLongitude());
CameraUpdateFactory.newLatLngZoom(latitudLongitud, 16);
mMap.setMapStyle(new MapStyleOptions(""));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latitudLongitud, 16));
mMap.addMarker(new MarkerOptions().position(latitudLongitud).title("Usted está aquí"));
mMap.addMarker(new MarkerOptions().position(new LatLng(cliente.getLatitud(), cliente.getLongitud())).title(cliente.getNombre()));
}
updateLocationUI();
//createLocationRequest();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
@SuppressWarnings("MissingPermission")
private void updateLocationUI() {
if (mMap == null) {
return;
}
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
ultimaLocalizacion = null;
}
}
private void getDeviceLocation() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
* Also request regular updates about the device location.
*/
if (mLocationPermissionGranted) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
updateMarkers();
}
private void updateMarkers() {
if (mMap == null) {
return;
}else{
LatLng prueba = new LatLng(mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(prueba)
.title("Estás aquí"));
}
if (mLocationPermissionGranted) {
// Get the businesses and other points of interest located
// nearest to the device's current location.
@SuppressWarnings("MissingPermission")
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
@Override
public void onResult( PlaceLikelihoodBuffer likelyPlaces) {
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
// Add a marker for each place near the device's current location, with an
// info window showing place information.
String attributions = (String) placeLikelihood.getPlace().getAttributions();
String snippet = (String) placeLikelihood.getPlace().getAddress();
if (attributions != null) {
snippet = snippet + "\n" + attributions;
}
mMap.addMarker(new MarkerOptions()
.position(placeLikelihood.getPlace().getLatLng())
.title((String) placeLikelihood.getPlace().getName())
.snippet(snippet));
}
// Release the place likelihood buffer.
likelyPlaces.release();
}
});
} else {
mMap.addMarker(new MarkerOptions()
.position(mDefaultLocation)
.title("Por defecto")
.snippet(""));
}
}
}
我已经阅读了关于lyfecicle和一切的内容,但我不知道出了什么问题,希望有人可以帮助我。