-->

解绑定可绘的onPause()导致无响应后退导航并跳过这一步骤的原因存储器溢出(Unbinding

2019-09-22 09:01发布

我使用的图像设置为背景为我所有的活动,但它是造成内存溢出问题和系统崩溃的应用程序。 现在我解除绑定暂停我可绘制()和destroy()方法在我的活动,现在,它显示了按后退按钮空白屏幕。 那么,如何避免这种情况,而无需使用额外的内存。

    protected void onPause(){
    super.onPause();
    unbindDrawables(findViewById(R.id.login_root));
}

protected void onDestroy() {
        unbindDrawables(findViewById(R.id.login_root));
        super.onDestroy();
      }

private void unbindDrawables(View view) {
    System.gc();
    Runtime.getRuntime().gc();
    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));
        }
    ((ViewGroup) view).removeAllViews();
    }

起初,我在不断膨胀采用了android我的布局:背景=“@绘制/”总是造成内存溢出错误,指出VM不会让我们分配10MB现在我正在从绘制一个位图没有缩小和有约束力的(应用)。它runtime.Now它说VM不会让我们没有使用unbindDrawables(..)显然,这显示已经下降的背景图像质量分配5MB(应用程序),但我不能够明白,如果我使用的是png格式13KB的文件,如何JVM需要5或10MB的空间来处理请求?

我从的onCreate改变我的布局语句()来的onResume()方法,但应用程序再次运行的内存上按后退按钮。

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

  protected void onResume(){
        setContentView(R.layout.home);
        Bitmap bmp;
        ImageView background = (ImageView)findViewById(R.id.iv_home_background);
        InputStream is = getResources().openRawResource(R.drawable.background);
        bmp = BitmapFactory.decodeStream(is);
        background.setImageBitmap(bmp);

         super.onResume();
    }

 protected void onPause(){
        super.onPause();
        unbindDrawables(findViewById(R.id.home_root));
    }


 private void unbindDrawables(View view) {
        System.gc();
        Runtime.getRuntime().gc();
        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));
            }
        ((ViewGroup) view).removeAllViews();
        }
    }

Answer 1:

我发现这个问题的解决办法。 现在我在运行时缩放我的位图到一个非常小的尺寸,然后将它们存储在内部存储。 程序在运行时调用从存储经缩放的位图,并且如果其不存在那里,它从可绘制文件夹的话来说,缩放,将其写入到存储,然后将其绑定到视图。 这样就没有必要调用unbindDrawables方法在任何时间点和应用程序保持整个响应。 我唯一担心的,现在是位图的质量,我想我需要发挥与周围的​​缩放尺寸,以找出最高的质量尽可能少的大小。



Answer 2:

您所要求的每个子视图GC。 尝试调用它只有一次,当所有的解除绑定完成。

unbindDrawables(findViewById(R.id.login_root));
System.gc();

GC是一个沉重的负担,这是没用的,过于频繁调用它。 事实上,如果没有泄漏应该是nesesary可言。

还有记住,png文件大小无关对内存的位图。 下面是关于它的更多信息http://developer.android.com/training/displaying-bitmaps/index.html



文章来源: Unbinding drawables onPause() causing unresponsive back navigation and skipping this step cause memory overflow