android - 尽管使用弱引用内存泄漏

标签 android memory-leaks android-listview android-asynctask weak-references

在我的应用程序中,我使用了 ListView 和列表适配器。当单击 ListView 中的某个子项时,会出现一个可单击的 TextView ,它将多个位图加载到 ScrollView 中 - 并且此 ScrollView 显示在警报对话框中。

所有这一切都发生在一个扩展 BaseExpandableListAdapter 的类中,当单击此文本链接时 - 将调用一个静态内部类,它负责加载所有这些 (9) 位图。这个内部类扩展了 asynctask。

在将这些位图加载到 ScrollView 之前 - 这个内部类的两个静态方法被调用,将位图缩小到适合屏幕的大小。这里我使用 Bitmapfactory.decoderesource 和 Bitmap.scaledownBitmap。

所有这一切都工作得很好,..但是程序存在内存泄漏。这个泄漏之前相当大,因为这个内部类是非静态的。因此,通过将此内部类设为静态来减少泄漏。是的——减少了,但没有消除。

我也对几个对象进行了弱引用,但没有成功。例如 - 我对引用内部类的对象进行了弱引用。我对传递给内部类的上下文进行了弱引用。我什至对位图做了 w weak reference。根本没有成功。

我的 Samsung Galazy s3 的堆大小是 64 MB。当 ListView 及其所有子项首次加载时,使用的堆大约为 17 MB。然后,当加载 9 个位图时,它会增加到大约 42 MB。如果我然后单击另一个子项目,使用的图像堆是相同的 - 但在继续单击并加载位图后,堆突然变大到 47 MB​​ ... 然后相同的场景...... 静止一段时间 - 然后高达 52 MB .... 56 MB。所以我几乎必须单击并加载位图才能使内存不足。比如说 15 - 20 分钟的密集使用。

结论:使内部类静态化有助于我减少内存泄漏。但是尽管对几个对象(尤其是上下文)进行了弱引用,但我无法进一步减少泄漏。

有什么建议吗?

下面的代码有点乱....

static class BitmapWorkerTask extends AsyncTask <Integer, Void, Bitmap[]> {

        private int[] data;
        private int[] width, height;
        private int nmbrOfImages;
        private String[] scrollText;
        private ImageView mImage; 
        private View view;
        private LayoutInflater factory;
        private AlertDialog.Builder alertadd;
        private Context context;
        private WeakReference <Context> sc;
        private WeakReference <ImageView> mImageV;
        private WeakReference <Bitmap[]> bitmapV;

        public BitmapWorkerTask(int[] width, int[] height, int nmbrOfImages, String[] scrollText, Context context) {

            this.width = width;
            this.height = height;
            this.nmbrOfImages = nmbrOfImages;
            this.scrollText = scrollText;
            this.context = context;

            mImage = null;
            view = null;
            factory = null;
            alertadd = null;
            System.gc();

            sc = new WeakReference <Context> (context);

            try {
                for (int i = 0; i < scaledBitmap.length; i++) {
                    scaledBitmap[i].recycle();
                    scaledBitmap[i] = null;
                }
            } catch (NullPointerException ne) {
                System.out.println("nullpointerexception ... gick inte recycla bitmapbilder");
            }

            switch (nmbrOfImages) {
            case 0:
                data = new int[1];
                break;
            case 1:
                data = new int[3];
                break;
            case 2:
                data = new int[5];
                break;
            case 3:
                data = new int[9];
                break;
            }

        }

        @Override
        protected Bitmap[] doInBackground(Integer ... params) {

            switch (nmbrOfImages) {
            case 0:
                data[0] = params[0];
                break;
            case 1:
                data[0] = params[0];
                data[1] = params[1];
                data[2] = params[2];
                break;
            case 2:
                data[0] = params[0];
                data[1] = params[1];
                data[2] = params[2];
                data[3] = params[3];
                data[4] = params[4];
                break;
            case 3:
                data[0] = params[0];
                data[1] = params[1];
                data[2] = params[2];
                data[3] = params[3];
                data[4] = params[4];
                data[5] = params[5];
                data[6] = params[6];
                data[7] = params[7];
                data[8] = params[8];
                break;
            }

            alertadd = new AlertDialog.Builder(sc.get());
            factory = LayoutInflater.from(sc.get());
            Bitmap[] bm = decodeSampledBitmapFromResource(sc.get().getResources(), data, width, height);
            bitmapV = new WeakReference <Bitmap[]> (bm);

            return bitmapV.get(); 

        }

        protected void onPostExecute(Bitmap[] bitmap) { 
            switch (nmbrOfImages) {
                case 0:

                    if (view == null) { 
                        view = factory.inflate(R.layout.alertviews, null);
                    }
                    mImage = (ImageView) view.findViewById(R.id.extra_img);
                    mImage.setImageBitmap(bitmap[0]);
                    alertadd.setView(view);
                    alertadd.setNeutralButton("Here!", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dlg, int sumthin) {

                        }
                    });
                    alertadd.show();

                break;
                case 1:

                    if (view == null) { 
                        view = factory.inflate(R.layout.alertviews2, null);
                    }

                    mImage = (ImageView) view.findViewById(R.id.img1);
                    mImage.setImageBitmap(bitmap[0]);
                    mImage = (ImageView) view.findViewById(R.id.img2);
                    mImage.setImageBitmap(bitmap[1]);
                    mImage = (ImageView) view.findViewById(R.id.img3);
                    mImage.setImageBitmap(bitmap[2]);

                    try {
                        TextView mText2 = (TextView) view.findViewById(R.id.text_img1_scrollview);
                        mText2.setText(scrollText[0]);
                        mText2 = (TextView) view.findViewById(R.id.text_img2_scrollview);
                        mText2.setText(scrollText[1]);
                        mText2 = (TextView) view.findViewById(R.id.text_img3_scrollview);
                        mText2.setText(scrollText[2]);
                    } catch (NullPointerException ne) {
                        System.out.println("nullpointerexception ... TextView i metoden onPostExecute");
                    }
                    alertadd.setView(view);
                    alertadd.setNeutralButton("Here!", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dlg, int sumthin) {

                        }
                    });

                    alertadd.show();

                break;
                case 2:

                    if (view == null) { 
                        view = factory.inflate(R.layout.alertviews3, null);
                    }
                    mImage = (ImageView) view.findViewById(R.id.img1);
                    mImage.setImageBitmap(bitmap[0]);
                    mImage = (ImageView) view.findViewById(R.id.img2);
                    mImage.setImageBitmap(bitmap[1]);
                    mImage = (ImageView) view.findViewById(R.id.img3);
                    mImage.setImageBitmap(bitmap[2]);
                    mImage = (ImageView) view.findViewById(R.id.img4);
                    mImage.setImageBitmap(bitmap[3]);
                    mImage = (ImageView) view.findViewById(R.id.img5);
                    mImage.setImageBitmap(bitmap[4]);

                    try {
                        TextView mText3 = (TextView) view.findViewById(R.id.text_img1_scrollview);
                        mText3.setText(scrollText[0]);
                        mText3 = (TextView) view.findViewById(R.id.text_img2_scrollview);
                        mText3.setText(scrollText[1]);
                        mText3 = (TextView) view.findViewById(R.id.text_img3_scrollview);
                        mText3.setText(scrollText[2]);
                        mText3 = (TextView) view.findViewById(R.id.text_img4_scrollview);
                        mText3.setText(scrollText[3]);
                        mText3 = (TextView) view.findViewById(R.id.text_img5_scrollview);
                        mText3.setText(scrollText[4]);
                    } catch (NullPointerException ne) {
                        System.out.println("nullpointerexception ... TextView i metoden onPostExecute");
                    }
                    alertadd.setView(view);
                    alertadd.setNeutralButton("Here!", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dlg, int sumthin) {

                        }
                    });
                    alertadd.show();

                break;
                case 3:

                    if (view == null) { 
                        view = factory.inflate(R.layout.alertviews4, null);
                    }

                    AlertDialog.Builder alertadd = new AlertDialog.Builder(context);



                    mImage = (ImageView) view.findViewById(R.id.img1);
                    mImage.setImageBitmap(bitmap[0]);
                    mImage = (ImageView) view.findViewById(R.id.img2);
                    mImage.setImageBitmap(bitmap[1]);
                    mImage = (ImageView) view.findViewById(R.id.img3);
                    mImage.setImageBitmap(bitmap[2]);
                    mImage = (ImageView) view.findViewById(R.id.img4);
                    mImage.setImageBitmap(bitmap[3]);
                    mImage = (ImageView) view.findViewById(R.id.img5);
                    mImage.setImageBitmap(bitmap[4]);
                    mImage = (ImageView) view.findViewById(R.id.img6);
                    mImage.setImageBitmap(bitmap[5]);
                    mImage = (ImageView) view.findViewById(R.id.img7);
                    mImage.setImageBitmap(bitmap[6]);
                    mImage = (ImageView) view.findViewById(R.id.img8);
                    mImage.setImageBitmap(bitmap[7]);
                    mImage = (ImageView) view.findViewById(R.id.img9);
                    mImage.setImageBitmap(bitmap[8]);



                    try {
                        TextView mText4 = (TextView) view.findViewById(R.id.text_img1_scrollview);
                        mText4.setText(scrollText[0]);
                        mText4 = (TextView) view.findViewById(R.id.text_img2_scrollview);
                        mText4.setText(scrollText[1]);
                        mText4 = (TextView) view.findViewById(R.id.text_img3_scrollview);
                        mText4.setText(scrollText[2]);
                        mText4 = (TextView) view.findViewById(R.id.text_img4_scrollview);
                        mText4.setText(scrollText[3]);
                        mText4 = (TextView) view.findViewById(R.id.text_img5_scrollview);
                        mText4.setText(scrollText[4]);
                        mText4 = (TextView) view.findViewById(R.id.text_img6_scrollview);
                        mText4.setText(scrollText[5]);
                        mText4 = (TextView) view.findViewById(R.id.text_img7_scrollview);
                        mText4.setText(scrollText[6]);
                        mText4 = (TextView) view.findViewById(R.id.text_img8_scrollview);
                        mText4.setText(scrollText[7]);
                        mText4 = (TextView) view.findViewById(R.id.text_img9_scrollview);
                        mText4.setText(scrollText[8]);
                    } catch (NullPointerException ne) {
                        System.out.println("nullpointerexception ... TextView i metoden onPostExecute");
                    }

                alertadd.setView(view);

                alertadd.setNeutralButton("Here!", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dlg, int sumthin) {

                    }
                });
                alertadd.show();

            break;
            }
        }


         /**
           * 
           * @param options
           * @param reqW
           * @param reqH
           * @return
           */
          public static int calculateInSampleSize(BitmapFactory.Options options, int reqW, int reqH) {

                int imageHeight = options.outHeight;
                int imageWidth = options.outWidth;
                int inSampleSize = 1;
                if (imageHeight > reqH || imageWidth > reqW) {
                    int heightRatio = Math.round((float) imageHeight / (float) reqH);
                    int widthRatio = Math.round((float) imageWidth / (float) reqW);
                    inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
                    System.out.println("i if-satsen!");
                    System.out.println("height-ratio: " + heightRatio + "\nwidth-ratio: " + widthRatio);
                }
                System.out.println("samplesize: " +  inSampleSize);
                inSampleSize = inSampleSize;

                return inSampleSize;
            }

            @SuppressLint("NewApi")
            /**
             * 
             * @param res
             * @param resId
             * @param reqW
             * @param reqH
             * @return
             */
            public static Bitmap[] decodeSampledBitmapFromResource(Resources res, int[] resId, int[] reqW, int[] reqH) {

                scaledBitmap = new Bitmap[resId.length];

                BitmapFactory.Options options;
                for (int i = 0; i < resId.length; i++) {
                    options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    Bitmap bm =BitmapFactory.decodeResource(res, resId[i], options);

                    System.out.println("ursprunglig bild: h = " + options.outHeight + " w = " + options.outWidth);
                    options.inSampleSize = calculateInSampleSize(options, reqW[i], reqH[i]);

                    while (options.outHeight < reqH[i] || options.outWidth < reqW[i]) {

                        options.inSampleSize--;
                        System.out.println("räknar nu ner insampleseize\ninSamleSize =" + options.inSampleSize);
                    }

                    options.inJustDecodeBounds = false;

                    bm = BitmapFactory.decodeResource(res, resId[i], options);
                    System.out.println("innan omskalning: h = " + options.outHeight + " w = " + options.outWidth);
                    System.out.println("antalet bytes: " + bm.getByteCount());
                    System.out.println("native free size: " + Debug.getNativeHeapFreeSize() );

                    scaledBitmap[i] = Bitmap.createScaledBitmap(bm, reqW[i], reqH[i], true); 

                    bm.recycle();
                    bm = null;

                }
                System.gc();
                WeakReference <Bitmap[] > sc = new WeakReference <Bitmap[]> (scaledBitmap);

                return sc.get();
            }
    }

最佳答案

您保持对位图的双重引用 曾经很弱,曾经是硬拷贝 你的问题代码是:

  Bitmap[] bm = decodeSampledBitmapFromResource(sc.get().getResources(), data, width, height);
                bitmapV = new WeakReference <Bitmap[]> (bm);

你没有去掉 bm 的内容

而且你不止一次这样做

     scaledBitmap[i] = Bitmap.createScaledBitmap(bm, reqW[i], reqH[i], true); 

                    bm.recycle();
                    bm = null;

                }
                System.gc();
   WeakReference <Bitmap[] > sc = new WeakReference <Bitmap[]> (scaledBitmap);

你应该这样做:

ArrayList<WeakReference<Bitmap>>scaledBitmaps= new ArrayList<WeakReference<Bitmap>>();

scaledBitmaps.add(new WeakReference<Bitmap>(Bitmap.createScaledBitmap...));

and do not use Bitmap[] array 

关于android - 尽管使用弱引用内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17272474/

相关文章:

android - ListView 中的标题 View 高度

android - 使用自定义适配器的 fragment 中的 OnItemSelectedListener

java - 更改方向会删除 UI 元素

Android合并两张图片

java - 在android中实现Parcelable,onRestoreInstanceState没有被调用

android - iOS/Android 上的增强现实 3D 动画

crash - NSMutableArray,removeFromArray和发行版,为什么会崩溃?

android - 我的 Android 应用程序占用太多内存

android - 在 android config.xml 中出现错误 "unbound prefix"

iOS 内存管理和 NSString 初始化