Если я начну занятие с включенными службами определения местоположения, приложение сможет получить мои последние координаты местоположения. Однако, если действие запускается без включенных служб определения местоположения, и я нажимаю кнопку «Получить текущее местоположение», появляется диалоговое окно, в котором можно включить службы определения местоположения. Как только он включен, я все еще не могу получить свои последние координаты местоположения - мне возвращается «Текущее местоположение является нулевым» согласно Тосту в моем коде. Я видел другие потоки, но решения кажутся слишком навязчивыми для моего существующего кода. Я очень надеюсь, что небольшая настройка в моем существующем коде решит мою проблему.
public class ExploreFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mapView;
private Location currentLocation;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
private String apiKey = "[KEY REMOVED]";
private PlacesClient placesClient;
private LatLng userLocation;
FloatingActionButton buttonCurrentLocation;
private LocationManager locationManager;
public View onCreateView(@NonNull final LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_explore, null, false);
locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
lastLocation();
buttonCurrentLocation = view.findViewById(R.id.buttonCurrentLocation);
buttonCurrentLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationDialog();
} else {
if (currentLocation != null) {
userLocation = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
mapView.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15.0f));
} else {
Toast.makeText(getContext(), "Current location is null", Toast.LENGTH_SHORT).show();
}
}
}
});
return view;
}
public void onMapReady(final GoogleMap googleMap) {
mapView = googleMap;
if (currentLocation != null) {
userLocation = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
mapView.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15.0f));
}
}
private void locationDialog() {
new AlertDialog.Builder(getContext())
.setTitle("No GPS signal found") // GPS not found
.setMessage("To continue, turn on device location") // Want to enable?
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No, thanks", null)
.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
lastLocation();
}
break;
}
}
private void lastLocation() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(ExploreFragment.this);
if (location != null) {
currentLocation = location;
}
}
});
}
}
Всего 1 ответ
Объект местоположения может быть null
в следующих ситуациях:
Расположение отключено в настройках устройства. Результат может быть нулевым, даже если последнее местоположение было получено ранее, поскольку отключение расположения также очищает кэш.
Устройство никогда не записывало свое местоположение, что может быть в случае нового устройства или устройства, которое было восстановлено до заводских настроек.
Службы Google Play на устройстве были перезапущены, и нет активного клиента провайдера Fused Location Provider, который запросил местоположение после перезапуска служб. Чтобы избежать этой ситуации, вы можете создать нового клиента и запросить обновления местоположения самостоятельно. Для получения дополнительной информации см. Получение обновлений местоположения.
Кажется, вы поймали третью ситуацию :)
Подробнее об этом в документации