GPS,定位第一次,但不是第二次

GPS, Locate the first time, but not the second

我尝试一次定位用户的位置,所以我使用的是合并的位置提供程序。我遇到的问题是,当我第一次使用它时,我找到了位置,但是如果我关闭 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(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>

嗯,您已经检查了 GPS_PROVIDER,但您还需要检查 LocationManager.NETWORK_PROVIDER。因此,您可以在 GPS 关闭时通过网络获取位置状态。

首先,您需要检查权限,如果未授予权限,请申请新的权限。

// 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);
}

在您的 obtenerUbicacion() 中使用如下内容:

 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();
    }

然后,添加 requestNewLocationData()LocationCallback 以更新新位置。

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());
}