Search code examples
javaandroidandroid-studiolocationdeprecated

What should I replace with my deprecated code?


I have a code to get the current location of the user but some parts of the code says that it is deprecated

I tried copying other latest code but I also encountered some problems: Google maps does not get the user location if the user does not have a recent location

Then I tried reverting back to my old code though it is still working but I am quite worried that it may stop working at some point. Is there any code that I can replace with the deprecated code or latest codes that have the same function. I would greatly appreciate any insights or suggestions you might have. Thank you in advance for your help!

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private FusedLocationProviderClient fusedLocationClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private SupportMapFragment mapFragment;
private View locationButton;
private LatLng currentLocation;
private Marker currentLocationMarker;
private Handler handler;
private LinearLayout sidebarLayout;
private ImageView hamburgerButton;
private Button logoutButton;

private boolean isSidebarVisible = false;

private final LatLng MarisolTerminal = new LatLng(15.1519204,120.4476555);
private final LatLng VillaTerminal = new LatLng(15.1268318,120.5974806);
private final LatLng CheckpointTerminal = new LatLng(15.169206,120.5872296);

private Marker markerMarisolTerm;
private Marker markerVillaTerminal;
private Marker markerCheckpointTerminal;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    // Get references to the sidebar layout and buttons
    sidebarLayout = findViewById(R.id.sidebarLayout);
    hamburgerButton = findViewById(R.id.hamburger_button);
    logoutButton = findViewById(R.id.sidebar_logout_button);

    // Set a click listener for the hamburger button
    hamburgerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggleSidebar();
        }
    });

    // Set a click listener for the logout button in the sidebar
    logoutButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Call the signOut method to sign out the user
            signOut();
        }
    });

    // Initialize the FusedLocationProviderClient
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

   ** // Create the location request, DEPRACTED CODES
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(5000); // Update interval in milliseconds (adjust as needed)**

    // Create the location callback
    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
                updateLocationOnMap(location);
            }
        }
    };
}

@Override
protected void onResume() {
    super.onResume();
    startLocationUpdates();
}

@Override
protected void onPause() {
    super.onPause();
    stopLocationUpdates();
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setZoomControlsEnabled(true);

    // Enable the My Location button
    mMap.getUiSettings().setMyLocationButtonEnabled(false);
    mMap.setMyLocationEnabled(true);
    mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
        @Override
        public boolean onMyLocationButtonClick() {
            // Move the camera to the current location
            if (currentLocation != null) {
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15));
            }
            return true;
        }
    });

    // Start location updates
    startLocationUpdates();

    // Add some markers to the map, and add a data object to each marker.
    markerMarisolTerm = mMap.addMarker(new MarkerOptions()
            .position(MarisolTerminal)
            .title("Marisol Terminal"));
    markerMarisolTerm.setTag(0);

    markerVillaTerminal = mMap.addMarker(new MarkerOptions()
            .position(VillaTerminal)
            .title("Villa Terminal"));
    markerVillaTerminal.setTag(0);

    markerCheckpointTerminal = mMap.addMarker(new MarkerOptions()
            .position(CheckpointTerminal)
            .title("Checkpoint Terminal"));
    markerCheckpointTerminal.setTag(0);




}

private void startLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Request location permissions if not granted
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                100);
        return;
    }
    fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}

private void stopLocationUpdates() {
    fusedLocationClient.removeLocationUpdates(locationCallback);
}

private void updateLocationOnMap(Location location) {
    currentLocation = new LatLng(location.getLatitude(), location.getLongitude());

    if (currentLocationMarker == null) {
        currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation).title("You are here"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15));
    } else {
        currentLocationMarker.setPosition(currentLocation);
    }
}

`


Solution

  • The codes that I replace it with is

      locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 100)
                    .setWaitForAccurateLocation(false)
                    .setMinUpdateIntervalMillis(2000)
                    .setMaxUpdateDelayMillis(100)
                    .build();
    
    

    The old deprecated code is

    
    locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(5000);