kenyu73
kenyu73

Reputation: 681

Static memory leak with Context

I've been doing some researching and I'm still not 100% certain if this could cause an based memory leak. I'm using a button view (v.context). I think I'm OK since the context isn't stored as Static, but I'd like some feedback if possible. The main issue I'm seeing is with OSMonitor... the (M) value goes UP and UP and UP. With every open/close of the widget and on screen rotation.

32M 43M 61M 77M etc...

I'm not sure if (M) is Megabytes or Megebits. If this is based on the stack, I'm assuming Megebits perhpas since most high end devices are limited to 32/48 MB on the stack (or something).

Thanks for the feedback/extra eyes!

This is the Banner app in the Market, btw...

public class Globals {

public static final String  PREF_NAME       = "BannerPreferences";
public static final int     MAX_TEXT_SIZE   = 20;

// refresh ALL widgets loaded on the user's screens
// this could be for removing or adding 'pendingIntents or during bootup
public static void refreshAllWidgets(Context context) {
    Logger.d("BANNER", "Globals:refreshAllWidgets");

    invalidateWidgets(context, BannerWidget.class); // 1x4
    invalidateWidgets(context, BannerWidget1x2.class);
    invalidateWidgets(context, BannerWidget2x2.class);
}

// there has to be a API way to do this!! Until then, just loop thru all
// widget_provider classes..
private static void invalidateWidgets(Context context, Class<?> cls) {

    ComponentName comp = new ComponentName(context, cls);
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(comp);

    for (int i = 0; i < appWidgetIds.length; i++) {
        BannerWidgetBase.updateAppWidget(context, appWidgetManager, appWidgetIds[i]);
    }

    appWidgetIds = null;
}

Upvotes: 4

Views: 797

Answers (1)

Markus Junginger
Markus Junginger

Reputation: 7075

There does not have to be a leak. Due to the nature of the Dalvik VM, the heap keeps growing when it is in use until it reaches the maximum heap size. However, there may be enough space in the heap for your objects. I'd suggest to limit the process memory (heap) in a emulator image and see if you actually get an OutOfMemoryError. When creating the emulator, there's a property "Max VM application heap size" you want to set, e.g. to 32 (measured in megabyte).

If you get an OutOfMemoryError, you should have a closer look at Eclipse MAT.

P.S.: Just realized that you should probably use an application context in your case, and never an Activity. If you trigger it from an activity, consider getApplicationContext instead of passing the Activity as a context. Static stuff may outlive Activity instances.

Upvotes: 2

Related Questions