Track my location only when I'm load this app / fragment at the second time

57 Views Asked by At

I'm facing an unusual issue in my Android application where the initial GPS location doesn't update properly when the app is loaded for the first time. Here's the relevant code snippet:

public class MapFragment extends Fragment implements OnMapReadyCallback {
    private final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private boolean firstFetch = true;
    private boolean recenterOnLocationChange = false;
    private Location currentLocation;
    private FusedLocationProviderClient fusedLocationProviderClient;
    private CameraPosition prevCameraPosition;


    private GoogleMap mMap;

    private final ActivityResultLauncher<String[]> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), isGranted -> {
                boolean allPermissionsGranted = true;
                for (Boolean granted : isGranted.values()) {
                    if (!granted) {
                        allPermissionsGranted = false;
                        break;
                    }
                }
                if (allPermissionsGranted) {
                    getLastLocation();
                    System.out.println("!!!!!!!!!!!!!!!Here!!!!!!!!!!!!!!!!!");
                } else {
                    // Permission is denied, handle it
                }
            });



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_map, container, false);
        // FrameLayout mapContainer = rootView.findViewById(R.id.mapContainer);
       // mapContainer.addView(super.onCreateView(inflater, container, savedInstanceState));
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
        SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapContainer);
        supportMapFragment.getMapAsync(this);
        return rootView;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setPadding(0, 200, 0, 0);
        requestPermissions();
    }
    private void requestPermissions() {
        String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            getLastLocation();
        } else {
            // Request permissions
            requestPermissionLauncher.launch(permissions);
        }
    }
    @SuppressLint("MissingPermission")
    public void getLastLocation(){
        mMap.setMyLocationEnabled(true);
        fusedLocationProviderClient.requestLocationUpdates(
                new LocationRequest()
                        .setInterval(1000) // Update every second
                        .setFastestInterval(500), // Update as often as possible
                new LocationCallback() {
                    @Override
                    public void onLocationResult(LocationResult locationResult) {
                        currentLocation = locationResult.getLastLocation();
                        if (currentLocation != null) {
                            LatLng myLocation = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
                            if(firstFetch) {
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 50));
                                prevCameraPosition = mMap.getCameraPosition();
                                firstFetch = false;
                            }else{
                                if(prevCameraPosition.equals(mMap.getCameraPosition())){
                                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 50));
                                    prevCameraPosition = mMap.getCameraPosition();
                                }
                            }
                        }
                    }
                }, Looper.myLooper()
        );
        // Set a click listener for the "My Location" button
        mMap.setOnMyLocationButtonClickListener(() -> {
            if (currentLocation != null) {
                LatLng myLocation = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 50));
            }
            prevCameraPosition = mMap.getCameraPosition();
            return true; // Indicates that the listener has consumed the event
        });
    }
    public Location getCurrentLocation() {
        return currentLocation;
    }
}

The issue is that the initial GPS location doesn't update properly when the app is launched. However, if I navigate to another fragment and then return, the new location updates correctly. Subsequent location changes also work as expected. I've tried introducing a delay of 1 second before calling getLastLocation(), but the problem persists.

I'd appreciate any insights or suggestions on how to resolve this issue. Thank you!

Issue video: text

I've tried introducing a delay of 1 second before calling getLastLocation().

0

There are 0 best solutions below