I am trying to locate the user's location once, so I am using the merged location provider. The problem I have is that when I use it for the first time I locate the location but then if I turn off the GPS and press the text to locate again, it does not locate me again. What could be the problem that makes it work the first time? Many thanks.
public class DatosUbicacion extends Fragment {
private TextView tvLocalizar;
private FusedLocationProviderClient proveedor;
private LocationManager locationManager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View vista = inflater.inflate(R.layout.fragment_ubicacion, container, false);
ids(vista);
locationManager=()requireActivity().getSystemService(Context.Location_Service);
proveedor = LocationServices.getFusedLocationProviderClient(getActivity());
tvLocalizar.setOnClickListener(v -> permiso);
return vista;
private void permiso() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
obtenerUbicacion();
} else if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
dialogo();
} else if (!shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
dialogoConfiguracion();
} else {
dialogo();
}
} else {
obtenerUbicacion();
}
}
@SuppressLint("MissingPermission")
public void obtenerUbicacion() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(1000);
locationRequest.setWaitForAccurateLocation(true);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
proveedor.getLastLocation().addOnSuccessListener(location -> {
if (location != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
Log.d("UBICACION", location.getLatitude() + "" + location.getLongitude());
} else {
proveedor.requestLocationUpdates(locationRequest, miUbicacionCallback, Looper.myLooper());
}
}).addOnFailureListener(e -> {
Toast.makeText(requireContext(), "error" + e.getMessage(), Toast.LENGTH_SHORT).show();
});
} else {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
Task<LocationSettingsResponse> tarea = LocationServices.getSettingsClient(requireContext()).checkLocationSettings(builder.build());
tarea.addOnFailureListener(e -> {
if (e instanceof ResolvableApiException) {
try {
IntentSenderRequest intentSenderRequest = new IntentSenderRequest.Builder(((ResolvableApiException) e).getResolution()).build();
contratoGps.launch(intentSenderRequest);
} catch (Throwable trowable) {
Log.e("gps", trowable.getMessage());
}
}
});
}
}
private LocationCallback miUbicacionCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult resultado) {
if (resultado == null) {
return;
}
Log.d("UBICACION", resultado.getLastLocation().getLatitude() + “ ” + resultado.getLastLocation().getLongitude());
};
private void dialogo(){
Dialog dialog = new Dialog(requireContext(), R.style.Theme_AppCompat_Light_Dialog_Alert);
dialog.setContentView(R.layout.dialog_camara);
Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
Button btnOk = dialog.findViewById(R.id.btn_ok);
Button btnCancelar = dialog.findViewById(R.id.btn_cancelar);
TextView permiso = dialog.findViewById(R.id.tv_permiso);
dialog.show();
btnOk.setOnClickListener(v -> {
this.contratoUbicacion.launch(Manifest.permission.ACCESS_FINE_LOCATION);
dialog.dismiss();
});
btnCancelar.setOnClickListener(v -> dialog.dismiss());
dialog.setCancelable(false);
}
private void dialogoConfiguracion() {
Dialog dialog = new Dialog(requireContext(), R.style.Theme_AppCompat_Light_Dialog_Alert);
dialog.setContentView(R.layout.dialog_ubicacion);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
Button ok = dialog.findViewById(R.id.btn_ok);
Button cancel = dialog.findViewById(R.id.btn_cancelar);
TextView permiso = dialog.findViewById(R.id.tv_permiso);
dialog.show();
ok.setOnClickListener(v -> {
configuracion();
});
cancel.setOnClickListener(v -> dialog.dismiss());
dialog.setCancelable(false);
}
private void configuracion() {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", requireActivity().getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
ActivityResultLauncher<String> contratoUbicacion = registerForActivityResult(new ActivityResultContracts.RequestPermission(), resultado -> {
if (resultado) {
obtenerUbicacion();
} else {
Toast.makeText(requireContext(), "se necesitan permisos de ubicacion", Toast.LENGTH_SHORT).show();
}
});
ActivityResultLauncher<IntentSenderRequest> contratoGps = registerForActivityResult(new ActivityResultContracts.StartIntentSenderForResult(), resultado -> {
if (result.getResultCode() == Activity.RESULT_OK) {
obtenerUbicacion();
}
});
private void ids(View vista){
tvLocalizar = vista.findViewById(R.id.tv_localizar);
}
}
Xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cl_ubicacion"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="@color/plataforma"
tools:context=".preusuario.registro2.DatosUbicacion">
<TextView
android:id="@+id/tv_localizar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Obtener mi ubicacion actual"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Well, you have checked GPS_PROVIDER but you also need to check LocationManager.NETWORK_PROVIDER
. So, you can get location status via Network when GPS is Off.
First of all, you need to check the permmissions and, also request the new permmissions if not granted.
// method to check
// if location is enabled
public boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
// method to request for permissions
public void requestPermissions() {
ActivityCompat.requestPermissions(FutureClientsMeet.this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_ID);
}
In your obtenerUbicacion()
use something like below:
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// check if location is enabled
if (isLocationEnabled()) {
locationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
CurrentLat = String.valueOf(location.getLatitude());
CurrentLng = String.valueOf(location.getLongitude());
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Please turn on" + " your location...", Toast.LENGTH_LONG).show();
}
} else {
requestPermissions();
}
Then, add requestNewLocationData()
and LocationCallback
to update the new location.
public LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
if (mLastLocation != null) {
//here you can get new location
Lat = mLastLocation.getLatitude();
Lng = mLastLocation.getLongitude();
}
}
};
@SuppressLint("MissingPermission")
public void requestNewLocationData() {
// Initializing LocationRequest
// object with appropriate methods
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);
// setting LocationRequest
// on FusedLocationClient
locationProviderClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
locationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}