После того, как пользователь запросил разрешения на доступ и принимает его, он не находит местоположение, я должен вернуться назад и снова в приложение, чтобы показать свое местоположение. Как я могу достичь после предоставления разрешения на местоположение, чтобы получить свое местоположение мгновенно?
Это мой код
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
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.BitmapDescriptorFactory;
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 AppCompatActivity implements OnMapReadyCallback {
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 16f;
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//Gets the device's current location
getLocationPermission();
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// openGpsWindow();
//}
}
@Override
public void onMapReady(GoogleMap googleMap) {
//map is ready
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//mMap.setMyLocationEnabled(true);
}
}
private void getDeviceLocation() {
// getting the device's current location
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (mLocationPermissionsGranted) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
//onComplete: found location
Location currentLocation = (Location) task.getResult();
double latitude = currentLocation.getLatitude();
double longitude = currentLocation.getLongitude();
//Finding user's location
LatLng myCoordinates = new LatLng(latitude, longitude);
moveCamera(myCoordinates, DEFAULT_ZOOM);
//Adding an icon marker to display the user's location and the info window from above
MarkerOptions marker = new MarkerOptions();
mMap.addMarker(marker.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_mini))).showInfoWindow();
}else{
//unable to get current location
}
}
});
}
}
private void moveCamera(LatLng latLng, float zoom) {
//moveCamera: moving the camera to: lat: + latLng.latitude + lng: + latLng.longitude
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap() {
//initializing map
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission() {
//getting location permissions
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//onRequestPermissionsResult: called
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = false;
//onRequestPermissionsResult: permission failed
return;
}
}
//onRequestPermissionsResult: permission granted
mLocationPermissionsGranted = true;
//initialize the map
initMap();
}
}
}
}
public void openGpsWindow() {
Intent intent = new Intent(this, EnableGpsWindow.class);
startActivity(intent);
}
}
2) И затем, если я отключаю gps, когда я нахожусь в mapsacctivity, я хочу вызвать openGpsWindow (который предлагает пользователю снова открыть gps.) Заранее спасибо.