How to make Location API backward compatible?

To make the Location API backward compatible in Android, you need to check the SDK version at runtime and implement appropriate logic to handle differing versions of the API. This ensures that your application can function correctly across older and newer devices.

Here's a basic example of how you can achieve this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Use the new Location API LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE); } else { // Get location Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); } } else { // Use the legacy Location API LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); }

Location API backward compatibility Android development SDK version handling LocationManager