«

Android 多图片情况下,发生内存溢出的解决办法

时间:2024-3-2 17:16     作者:韩俊     分类: Android


由于在项目中有用到多图片的处理,这里的图片在60张以上,本篇所采取的案例均通过测试,在模拟器上都可以很流畅的使用。

本篇关键节点如下:

1、图片显示采取GridView控件,图片源头由res下drawable资源文件;

2、获取资源图片的时候采取AsyncTask进行操作;

3、图片缓存采取LinkedHashMap<Integer, Bitmap>,需要注意的是:

static LinkedHashMap<Integer, Bitmap> hard = new LinkedHashMap<Integer, Bitmap>(6, 0.75f, true);

4、进行手动内存回收,方式为在adapter 的getView里面进行主动回收,具体查看下面实例代码;

5、图片压缩采取 BitmapFactory.Options ,opt.inSampleSize = 4;


示例代码:

package com.demo.image;

import java.lang.reflect.Field;
import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;

import com.demo.R;

/**
 * 目前在模拟器上都比较流畅,需要再加多图片试试 05-14
 * 
 * 
 * 
 * @author Michael ku
 * 
 *         2015-5-14 下午9:18:37
 */
public class DemoImage extends Activity {
    final static int CWJ_HEAP_SIZE = 6 * 1024 * 1024;

    public void onCreate(Bundle bun) {
        super.onCreate(bun);
        this.requestWindowFeature(1);

        // 设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理
        // VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);

        this.setContentView(R.layout.activity_demo_image);

        grid = (GridView) this.findViewById(R.id.image_grid);

        adapter = new ImageAdapter(this, getDatas());
        grid.setAdapter(adapter);
    }

    ImageAdapter adapter;

    public void onDestroy() {
        super.onDestroy();

        if (adapter.data != null) {
            adapter.data.clear();
        }
        ImageAdapter.hard.clear();
    }

    private static ArrayList<Integer> getDatas() {

        ArrayList<Integer> result = new ArrayList<Integer>();
        Field[] fs = R.drawable.class.getDeclaredFields();
        for (Field fi : fs) {
            try {
                result.add(fi.getInt(R.drawable.class));

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    GridView grid;

}// end



package com.demo.image;

import java.util.ArrayList;
import java.util.LinkedHashMap;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.demo.R;

/**
 * 
 * 
 * 
 * 
 * @author Michael ku
 * 
 *         2015-5-14 下午9:19:48
 */
public class ImageAdapter extends BaseAdapter {

    ArrayList<Integer> data;
    private Activity base;

    public ImageAdapter(Activity ac, ArrayList<Integer> srcs) {
        this.data = srcs;
        base = ac;
    }

    public int getCount() {

        return data.size();
    }

    public Object getItem(int position) {

        return data.get(position);
    }

    public long getItemId(int position) {

        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder = null;
        if (convertView == null) {
            convertView = base.getLayoutInflater().inflate(
                    R.layout.image_demo_item, null);
            holder = new Holder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
            resetHolder(holder);
        }

        int resid = data.get(position);
        if (resid > 0) {

            if (hard.get(position) != null) {
                holder.img.setImageBitmap(hard.get(position));
            } else {

                new Task(holder.img, position).execute(resid);

            }
        }
        if (position % 7 == 6) {
            System.gc();
        }

        return convertView;
    }

    static LinkedHashMap<Integer, Bitmap> hard = new LinkedHashMap<Integer, Bitmap>(
            6, 0.75f, true);

    private class Task extends AsyncTask<Integer, Void, Bitmap> {
        int position;
        ImageView image;

        Task(ImageView img, int posi) {
            position = posi;
            image = img;
        }

        protected Bitmap doInBackground(Integer... params) {

            Bitmap bm = BitmapFactory.decodeResource(base.getResources(),
                    params[0], getOpt());

            hard.put(position, bm);

            return bm;
        }

        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);

            if (result != null) {
                image.setImageBitmap(result);
            }
        }
    }

    static BitmapFactory.Options getOpt() {

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inSampleSize = 4;

        return opt;
    }

    private void resetHolder(Holder ho) {
        ho.img.setImageResource(0);
    }

    private class Holder {
        ImageView img;

        Holder(View view) {
            img = (ImageView) view.findViewById(R.id.item_image);
        }
    }
}// end

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/item_image"
        android:layout_width="80dip"
        android:layout_height="80dip"
        android:contentDescription="@string/app_name" />

</LinearLayout>



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <GridView
        android:id="@+id/image_grid"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:horizontalSpacing="10dip"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:columnWidth="80dip"
        android:verticalSpacing="10dip" />

</LinearLayout>

资源文件,图片



测试虚拟机


以上就是全部的测试代码。

上面这个是在网上看到的,我在测试的时候没有通过,提示找不到这个类,如果有知道的朋友,提示下呗!




标签: android

热门推荐