Search code examples
androidstaticleakcanary

Android - LeakCanary triggered - static helper method


I wrote myself a little helper class:

public enum NetworkUtils {
    ;

    public static boolean hasNetworkConnection(Context context) {
        ConnectivityManager manager = getConnectivityManager(context);
        return manager != null
                && manager.getActiveNetworkInfo() != null
                && manager.getActiveNetworkInfo().isConnectedOrConnecting();
    }

    private static ConnectivityManager getConnectivityManager(Context context) {
        return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }
}

LeakCanary keeps telling me that I have an activity leak due to a reference to ConnectivityManager when I use that.

How to handle this situation? Is this a false positive?


Solution

  • Found the problem myself: Leak Canary Github issue
    The error can be prevented by using the application context:

    (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);