android – 使用Context的静态内存泄漏

我一直在做一些研究,如果这可能导致一个基础,我仍然不是100%肯定

内存泄漏.我正在使用按钮视图(v.context).我认为我没关系,因为上下文没有存储为静态,但如果可能的话,我想要一些反馈.我看到的主要问题是OSMonitor ……(M)值上升,上升和上升.每次打开/关闭小部件和屏幕旋转.

32M
43M
61M
77M
等等…

我不确定(M)是兆字节还是Megebits.如果这是基于堆栈,我假设Megebits perhpas,因为大多数高端设备限制在堆栈上的32/48 MB(或其他东西).

感谢您的反馈/额外的眼睛!

这是市场上的Banner应用程序,顺便说一下……

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;
}

最佳答案 没有泄漏.由于Dalvik VM的性质,堆在使用时会持续增长,直到达到最大堆大小.但是,堆中可能有足够的空间用于对象.我建议在仿真器映像中限制进程内存(堆),看看你是否真的得到了OutOfMemoryError.创建模拟器时,您要设置一个属性“Max VM application heap size”,例如到32(以兆字节为单位).

如果你得到一个OutOfMemoryError,你应该仔细看看Eclipse MAT.

P.S.:刚刚意识到你应该在你的情况下使用应用程序上下文,而不是活动.如果从活动中触发它,请考虑getApplicationContext而不是将活动作为上下文传递.静态内容可能比Activity实例寿命长.

点赞