Location awareness is a common feature for mobile application that enhance the user experience by providing context-specific services.
The location awareness feature can significantly drain the device’s battery.
The recommended way to maximize the battery life is to use the fused location provider which combines signals from GPS, Wi-Fi, and cell
networks, as well as accelerometer, gyroscope, magnetometer and other sensors. The FusedLocationProviderClient automatically chooses the
best method to retrieve a device’s location based on the device’s context.
The rule flags an issue when android.location.LocationManager or com.google.android.gms.location.LocationClient is used
instead of com.google.android.gms.location.FusedLocationProviderClient.
Replace the usages of android.location.LocationManager or com.google.android.gms.location.LocationClient with
com.google.android.gms.location.FusedLocationProviderClient.
public class LocationsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Noncompliant
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Use the location object as needed
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
public class LocationsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); // Compliant
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, location -> {
// Use the location object as needed
});
}
}