roplacebo
roplacebo

Reputation: 2937

Retrieving NsdManager always leaks Activity

While profiling my app, I found, that retrieving the NsdManager by using

nsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);  // LEAKS!

is leaking the Activity, while

nsdManager = (NsdManager) getApplicationContext().getSystemService(Context.NSD_SERVICE);

does not. I made a small test app, that does nothing else with the NsdManager than retrieving it using the Activity context, but it's still leaking the activity. Is this a bug? Do I really have to use the application context all the time?

Device: Emulator (Android 11, API 30, x86)

Upvotes: 2

Views: 123

Answers (1)

Java42
Java42

Reputation: 657

This problem seems similar to memory leak issues with obtaining WIFI_SERVICE.

When doing:

activity.getSystemService(Context.WIFI_SERVICE);

Android Studio lint shows the following warning.

The WIFI_SERVICE must be looked up on the 
Application context or memory will leak on
devices < Android N. Try changing activity
to activity.getApplicationContext().

Although there is no lint warning with NSD_SERVICE and because I see memory leaks referencing NsdManager when using:

activity.getSystemService(Context.NSD_SERVICE);

I think using:

activity.getApplicationContext().getSystemService(Context.NSD_SERVICE);

seems like the correct action.

Upvotes: 0

Related Questions