【问题标题】:Drawables resources management in androidandroid中的drawables资源管理
【发布时间】:2012-02-12 12:50:40
【问题描述】:

我有一个问题。我在网站上进行了快速搜索,但没有找到答案。 我们开发运行 android 2.2 及更高版本的应用程序。对于视图自定义,我们使用了许多可绘制对象,它们的使用方式如下:

<LinearLayout ...
    android:background="@drawable/some_drawable"/>

我们也使用地图并处理内存中的许多数据,我们的应用程序变得很重。在顶级设备上,它工作得很好,但在其他设备上,使用我们的应用程序几分钟后,我们得到了 OutOfMemory 异常。看起来我们有内存泄漏。 我正在尝试减少我们应用程序的内存使用量。问题,我们是否需要手动清理资源来销毁我们的活动:删除可绘制的视图,还是系统为我们制作的?

【问题讨论】:

  • 如果您使用大量将被缩放的高分辨率位图/drawable,这将消耗大量内存。这是特定活动中的问题吗?也许你在其中展示了一个包含很多位图的列表视图?

标签: android memory-management drawable


【解决方案1】:

我在我的应用程序中也遇到了这个问题。 OutOfMemoryError 如果在一个活动中使用了很多位图,并且带有缩放和/或其他位图操作,则会抛出。我所做的是将以下代码添加到我的活动中,这似乎使问题出现的频率降低(它并没有很好地解决它)并且应用程序现在在相当低端的手机上运行而没有错误。

@Override
protected void onDestroy()
{
    super.onDestroy();
    // explicitly release media player
    if(viewObjectInfo != null)
        viewObjectInfo.releaseMediaPlayer();
    //explicitly release all drawables and call GC
    unbindDrawables(findViewById(R.id.main));
    System.gc();
}

/**
 * Unbinds all drawables in a given view (and its child tree).
 * 
 * @param findViewById     Root view of the tree to unbind
 */
private void unbindDrawables(View view) {
    if (view.getBackground() != null) {
        view.getBackground().setCallback(null);
    }

    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            unbindDrawables(((ViewGroup) view).getChildAt(i));
        }
        try
        {
            ((ViewGroup) view).removeAllViews();
        }
        catch(UnsupportedOperationException ignore)
        {
            //if can't remove all view (e.g. adapter view) - no problem 
        }
    }
}

【讨论】:

  • unbindDrawables(findViewById(R.id.main)); 应该是unbindDrawables(findViewById(R.layout.main));
  • 如果我想从布局中取消绑定所有图像以释放资源直到再次调用布局怎么办?
  • @SiKni8 对于您的第一条评论,我使用了R.id.main - 您得到的是视图,而不是布局 - 尽管布局也可能有效。对于您的第二个,不要取消绑定所有内容 - 只需检查它是什么类型的视图。
  • 我的应用程序出现问题,我认为您可以帮助我:stackoverflow.com/questions/18473527/…
  • 调用 System.gc(); 是一种不好的做法;它不保证任何事情
猜你喜欢
  • 2014-11-05
  • 2011-09-26
  • 2011-12-02
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多