有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    好的,您已经检查了GPS\U提供程序,但是您还需要检查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());
    }