Я сделал проект с картой для отображения моего текущего местоположения в моем приложении, и когда я запускаю свое приложение, он отображает карту, но он не отображает мое текущее местоположение на моем эмуляторе, затем я отладил mLastKnownLocation, и он возвращает нуль , тогда я хотел бы знать, если что-то отсутствует в моем проекте, зная, что мой Wi-Fi включен, разрешение предоставляется с:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
и у меня включен сервис google play
Моя картаДействие
package com.example.tibdev.maps;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean mLocationPermissionGranted;
private Location mLastKnownLocation;
private FusedLocationProviderClient mFusedLocationProviderClient;
private GoogleMap mMap;
private LatLng mDefaultLocation;
public static float DEFAULT_ZOOM = 19;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}
/**
*
* @param googleMap
* start the map in the view
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
/**
*
* @param requestCode
* @param permissions
* @param grantResults
* Callback for the result from requesting permissions.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
this.mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION : {
//si le tableau pour les permission est vide
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
this.mLocationPermissionGranted = true;
}
}
}
this.updateLocationUI();
}
/**
* for get the permission for the location of user
*/
private void getLocationPermission() {
if(ContextCompat.checkSelfPermission(this.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
this.mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
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.
*/
public void getDeviceLocation() {
try {
if(mLocationPermissionGranted) {
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if(task.isSuccessful()) {
mLastKnownLocation = (Location) task.getResult();
Log.d("MapsDebug", "Result : " + mLastKnownLocation);
if(mLastKnownLocation != null) {
// Add a marker and move the camera
LatLng location = new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, DEFAULT_ZOOM));
mMap.addMarker(new MarkerOptions().position(location).title("Your Position"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
}
} else {
Log.d("MapsError", "Current location is null. Using defaults.");
Log.e("MapsError", "Exception: %s", task.getException());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}
} catch(SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
this.mLastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
}