android自定义相册 支持低端机不内存溢出

1 之前在网上看的自定义相册很多时候在低端机都会内存溢出开始上代码把 首先我们要拿到图片的所有路径

  cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, // 大图URI
STORE_IMAGES, // 字段
null, // No where clause // 如果这个地方你想对图片的大小进行过滤 可以这样写String s = String.valueOf(1024*1024*4) MediaStore.Images.Media.SIZE+"<="+s
        null,         // No where clause
MediaStore.Images.Media.DATE_TAKEN + "DESC"); //根据时间排序
     int id = cursor.getInt(0);//大图ID
String path = cursor.getString(1);//大图路径
File file = new File(path);
//判断大图是否存在
if (file.exists()) {
String uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon().
appendPath(Integer.toString(id)).build().toString();
这样就得到很多 content://media/external/images/media/119 这样的路径,没个file 类型的资源 如果是isfile 都会有一个这样的映射


2 拿到url 之后就是gridview 的适配了 你需要使用一个gridview,图片的加载我使用的是imageloader,你可以用跟好的框架 在baseadapter 里面加载图片的逻辑为
ImageSize size = new ImageSize(getImageWidth(),getImageWidth());  //  这个getimagewidth 就就你imageview 宽和高 这个加载出来的图片比系统图片的缩略图还要小些
imageLoader.loadImage(url, size, options,new SimpleImageLoadingListener(viewHolder.imageView));  //

3 然后选择用一个全局的
LocalHelper.getInstance(getApplicationContext()).getCheckedItems();
来存储 你选择的图片


4 然后在返回的时候如何处理 ,就是要把你选择的图片放到你自己的缓存文件 然后size 这个我用是1280 960 标准4:3的图片 ,如果你加载原图 会oom
List<LocalHelper.LocalFile> localFiles = LocalHelper.getInstance(getApplicationContext()).getCheckedItems();
ImageSize size = new ImageSize(CameraConstant.DefaultWidth, 3 * CameraConstant.DefaultWidth / 4);
for (LocalHelper.LocalFile localFile : localFiles) {
final Uri uri =Uri.parse(localFile.getOriginalUri());
imageLoader.loadImage(uri.toString(),size, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String s, View view) {
}
@Override
public void onLoadingFailed(String s, View view, FailReason failReason) {
}
@Override
public void onLoadingComplete(String s, View view, Bitmap bitmap) {
if (Util.isNotEmpty(url)){
BitmapUtils.saveBitmapTofile(bitmap, url);
toastHelper.cancel();
finish();
}else {
String path = BitmapUtils.getCacheDir(act);
BitmapUtils.saveBitmapTofile(bitmap, path);
result.add(path);
if (result.size()==LocalHelper.getInstance(getApplicationContext()).getCheckedItems().size()){
toastHelper.cancel();
finish();
}
}
}
@Override
public void onLoadingCancelled(String s, View view) {
}
});
}
文件路径算法是
public static File getPhotoFolder(Context context) {
File photoFolder = context.getExternalFilesDir("photos");
if (photoFolder == null) {
photoFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/dj/files/photos");
}
return photoFolder;
}

5 回到你显示界面 你把文件路径放到一个list里面 并且把会传到 你选择图片的activity里面

Intent intent = new Intent();
intent.putStringArrayListExtra("path", result);
setResult(RESULT_OK,intent);

6 到界面之后 只需要用gridview 加载一下图片就可以,图片点击在加一个预览效果就prefrect了

7 如果需要源码 请在下面留言啊 兄弟们, 我看看有空传到github上







 
posted on 2016-06-21 11:02  肖恩大婶  阅读(563)  评论(0编辑  收藏  举报