OutOfMemory exception when loading bitmap from external storage

前端 未结 13 1722
广开言路
广开言路 2020-11-29 06:52

In my application I load a couple of images from JPEG and PNG files. When I place all those files into assets directory and load it in this way, everything is ok:

         


        
13条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 07:32

    One of the most common errors that I found developing Android Apps is the “java.lang.OutOfMemoryError: Bitmap Size Exceeds VM Budget” error. I found this error frecuently on activities using lots of bitmaps after changing orientation: the Activity is destroyed, created again and the layouts are “inflated” from the XML consuming the VM memory avaiable for bitmaps.

    Bitmaps on the previous activity layout are not properly deallocated by the garbage collector because they have crossed references to their activity. After many experiments I found a quite good solution for this problem.

    First, set the “id” attribute on the parent view of your XML layout:

        
        
         ...
    

    Then, on the onDestroy() method of your Activity, call the unbindDrawables() method passing a refence to the parent View and then do a System.gc()

        @Override
        protected void onDestroy() {
        super.onDestroy();
    
        unbindDrawables(findViewById(R.id.RootView));
        System.gc();
        }
    
        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));
                }
            ((ViewGroup) view).removeAllViews();
            }
        }
    

    This unbindDrawables() method explores the view tree recursively and:

    1. Removes callbacks on all the background drawables
    2. Removes childs on every viewgroup

提交回复
热议问题