java GPS,第一次定位,但不是第二次
我试图定位用户的位置一次,所以我使用合并的位置提供程序。我遇到的问题是,当我第一次使用它时,我找到了位置,但如果我关闭GPS并按文本再次定位,它不会再次找到我。是什么问题使它第一次工作?非常感谢
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(安卓.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(安卓.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
<安卓x.constraintlayout.widget.ConstraintLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:app="http://schemas.安卓.com/apk/res-auto"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:id="@+id/cl_ubicacion"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
安卓:fitsSystemWindows="true"
安卓:background="@color/plataforma"
tools:context=".preusuario.registro2.DatosUbicacion">
<TextView
安卓:id="@+id/tv_localizar"
安卓:layout_width="0dp"
安卓:layout_height="wrap_content"
安卓:text="Obtener mi ubicacion actual"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</安卓x.constraintlayout.widget.ConstraintLayout>
# 1 楼答案
好的,您已经检查了GPS\U提供程序,但是您还需要检查
LocationManager.NETWORK_PROVIDER
。所以,当GPS关闭时,您可以通过网络获取位置状态首先,您需要检查永久任务,如果未授予,还需要请求新的永久任务
在
obtenerUbicacion()
中,使用如下内容:然后,添加
requestNewLocationData()
和LocationCallback
以更新新位置