Having studied the code in the repository, I found some problems in your design that could lead to the leak of your Activity .
1) You are using two different LocationCallbacks . One at the beginning and one in the stop method, but you should actually use the same. Thus, one instance of the instance will be sufficient and will probably lead to the successful result of your Task when deleting the LocationCallback .
2) Since you instantiate the LocationCallback twice with the Anonymous Class , you keep non-static references for the inner class, even if you end the class that calls your Memory Leak . You can read about it here .
3) IMHO it is better to use a separate manager class to process your location requests than to abstract the Activity .
It says that I ...
Decision
GpsManager.java
public class GpsManager extends LocationCallback { private FusedLocationProviderClient client; private Callback callback; public interface Callback { void onLocationResult(LocationResult locationResult); } public boolean start(Context context, Callback callback) { this.callback = callback; client = LocationServices.getFusedLocationProviderClient(context); if (!checkLocationPermission(context)) return false; client.requestLocationUpdates(getLocationRequest(), this, null); return true; } public void stop() { client.removeLocationUpdates(this); } @Override public void onLocationResult(LocationResult locationResult) { callback.onLocationResult(locationResult); } private boolean checkLocationPermission(Context context) { int permissionCheck = ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION); return permissionCheck == PackageManager.PERMISSION_GRANTED; } private LocationRequest getLocationRequest() { return LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(30_000L) .setFastestInterval(20_000L); } }
and calling it from your Activity as follows
YourActivity.java
public class MapsActivity extends AppCompatActivity implements GpsManager.Callback { private static final int PERMISSION_REQUEST_FINE_LOCATION = 1; private GpsManager mGpsManager; @Override protected void onCreate(Bundle savedInstanceState) { ... mGpsManager = new GpsManager(getApplicationContext(), this);
This is just an assumption because I have not tried your code, but the solution should help you anyway. Please correct me if I am wrong;)
Peppermint paddy
source share