Android的列表展示大量图片防止内存溢出的处理办法

根据项目需求获取手机相册中的所有图片并通过recyclerview列表展示
原因是拿到手机相册图片后存入一个集合,并把该集合的图片路径数据在循环中逐个取出来赋给实体类,同时也多此一举的把图片转bitmap并压缩,另外在列表加载图片选择的是gilde方式。但是加载出现了严重的问题,经过测试,在一些机型上会直接抛出OOM,开始不明所以,后面发现是我的实体类出现了问题即:实体类中的图片是一个bitmap类型而不是String类型的路径,所有尽管在循环中对集合的图片路径转bitmap做了压缩,但是面对大量的图片数据时会出现OOM,最好的解决办法就是实体类中的图片类型用String来表示路径,gilde加载路径就可以了

		Glide.with(mActivity)
	                            .load(“图片地址”)
	                            .into(“显示控件”);

另外,为了提高运行效率,建议获取相册图片写在子线程中并更新列表界面可即:( mPhotoAdapter是列表的适配器,实体类SystemPhotoBean)

private ArrayList<SystemPhotoBean> mSystemPhotoList = new ArrayList<>();
private List<String> mPhotoList;

   private void getAllPhotoInfo() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                mPhotoList = new ArrayList<String>();
                Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

                ContentResolver contentResolver = getContentResolver();
                Cursor cursor = contentResolver.query(uri, null, null, null, null);
                if (cursor != null && cursor.getCount() > 0) {
                    while (cursor.moveToNext()) {
                        int index = cursor
                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        String path = cursor.getString(index); // 文件地址
                        File file = new File(path);
                        if (file.exists()) {
                            mPhotoList.add(path);
                            Log.i(TAG, path);
                        }
                    }
                    cursor.close();
                }
                for (int i = mPhotoList.size() - 1; i >= 0; i--) {
                    SystemPhotoBean systemPhotoBean = new SystemPhotoBean();
                    systemPhotoBean.setId(i + "");
                    systemPhotoBean.setDesc(mPhotoList.get(i));
                    mSystemPhotoList.add(systemPhotoBean);
                }

                //更新界面
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPhotoAdapter.notifyDataSetChanged();
                    }
                });//更新界面
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPhotoAdapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值