1

I have a question regarding a memory leak in my Java Code:

I have a service that runs every second (in production it runs every minute) When I run the Android Studio Memory-Profiler, I can see that every time this code executes, the "Allocated Memory" value goes up by 6. So I guess this code is leaking? Obviously it leeks very slowly, but I wonder what is the problem with that code? What can I do to fix this? Or is this "normal" behaviour?

enter image description here

SyncService.java

public class SyncService extends Service {
@Override
public void onCreate() {
    Context context = getApplicationContext();

    new Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            if(!Helper.isNetworkAvailable(context)){
                Log.i(TAG, "Offline");
                return;
            }

            // ...
        }

    }, 1000, 1000);
}

}

Helper.java

public class Helper {
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

If I comment-out the call to Helper.isNetworkAvailable(context) the allocated value stays still.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Michael B
  • 1,660
  • 3
  • 28
  • 59
  • [This](https://stackoverflow.com/a/41431693/1744230) answer seems to address your problem, but then again, you're already providing `applicationContext` like the answer suggests – QBrute Jan 15 '20 at 09:13
  • When testing with a device of at least Android 7.1. you should be able to see [exactly what got allocated](https://developer.android.com/studio/profile/memory-profiler#record-allocations). – Joachim Sauer Jan 15 '20 at 09:31

0 Answers0