<RelativeLayout 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" > <GridView android:id="@+id/id_gridView" android:layout_width="match_parent" android:layout_height="match_parent" android:cacheColorHint="@android:color/transparent" android:columnWidth="90dip" android:gravity="center" android:horizontalSpacing="20dip" android:listSelector="@android:color/transparent" android:numColumns="auto_fit" android:stretchMode="columnWidth" android:verticalSpacing="20dip" > </GridView> </RelativeLayout>
package com.example.zhy_handler_imageloader;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.Toast;
public class MainActivity extends Activity
{
private ProgressDialog mProgressDialog;
private ImageView mImageView;
/**
* 存储文件夹中的图片数量
*/
private int mPicsSize;
/**
* 图片数量最多的文件夹
*/
private File mImgDir;
/**
* 所有的图片
*/
private List<String> mImgs;
private GridView mGirdView;
private ListAdapter mAdapter;
/**
* 临时的辅助类,用于防止同一个文件夹的多次扫描
*/
private HashSet<String> mDirPaths = new HashSet<String>();
private Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
mProgressDialog.dismiss();
mImgs = Arrays.asList(mImgDir.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String filename)
{
if (filename.endsWith(".jpg"))
return true;
return false;
}
}));
/**
* 可以看到文件夹的路径和图片的路径分开保存,极大的减少了内存的消耗;
*/
mAdapter = new MyAdapter(getApplicationContext(), mImgs,
mImgDir.getAbsolutePath());
mGirdView.setAdapter(mAdapter);
};
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGirdView = (GridView) findViewById(R.id.id_gridView);
getImages();
}
/**
* 利用ContentProvider扫描手机中的图片,此方法在运行在子线程中 完成图片的扫描,最终获得jpg最多的那个文件夹
*/
private void getImages()
{
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED))
{
Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
return;
}
// 显示进度条
mProgressDialog = ProgressDialog.show(this, null, "正在加载...");
new Thread(new Runnable()
{
@Override
public void run()
{
Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver mContentResolver = MainActivity.this
.getContentResolver();
// 只查询jpeg和png的图片
Cursor mCursor = mContentResolver.query(mImageUri, null,
MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=?",
new String[] { "image/jpeg", "image/png" },
MediaStore.Images.Media.DATE_MODIFIED);
while (mCursor.moveToNext())
{
// 获取图片的路径
String path = mCursor.getString(mCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
// 获取该图片的父路径名
File parentFile = new File(path).getParentFile();
String dirPath = parentFile.getAbsolutePath();
//利用一个HashSet防止多次扫描同一个文件夹(不加这个判断,图片多起来还是相当恐怖的~~)
if(mDirPaths.contains(dirPath))
{
continue;
}
else
{
mDirPaths.add(dirPath);
}
int picSize = parentFile.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String filename)
{
if (filename.endsWith(".jpg"))
return true;
return false;
}
}).length;
if (picSize > mPicsSize)
{
mPicsSize = picSize;
mImgDir = parentFile;
}
}
mCursor.close();
//扫描完成,辅助的HashSet也就可以释放内存了
mDirPaths = null ;
// 通知Handler扫描图片完成
mHandler.sendEmptyMessage(0x110);
}
}).start();
}
}
package com.example.zhy_handler_imageloader;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.zhy.utils.ImageLoader;
public class MyAdapter extends BaseAdapter
{
private Context mContext;
private List<String> mData;
private String mDirPath;
private LayoutInflater mInflater;
private ImageLoader mImageLoader;
public MyAdapter(Context context, List<String> mData, String dirPath)
{
this.mContext = context;
this.mData = mData;
this.mDirPath = dirPath;
mInflater = LayoutInflater.from(mContext);
mImageLoader = ImageLoader.getInstance();
}
@Override
public int getCount()
{
return mData.size();
}
@Override
public Object getItem(int position)
{
return mData.get(position);
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public View getView(int position, View convertView, final ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.grid_item, parent,
false);
holder.mImageView = (ImageView) convertView
.findViewById(R.id.id_item_image);
convertView.setTag(holder);
} else
{
holder = (ViewHolder) convertView.getTag();
}
holder.mImageView
.setImageResource(R.drawable.friends_sends_pictures_no);
//使用Imageloader去加载图片
mImageLoader.loadImage(mDirPath + "/" + mData.get(position),
holder.mImageView);
return convertView;
}
private final class ViewHolder
{
ImageView mImageView;
}
}
mImageLoader.loadImage(mDirPath + "/" + mData.get(position),holder.mImageView);
/**
* 单例获得该实例对象
*
* @return
*/
public static ImageLoader getInstance()
{
if (mInstance == null)
{
synchronized (ImageLoader.class)
{
if (mInstance == null)
{
mInstance = new ImageLoader(1, Type.LIFO);
}
}
}
return mInstance;
}
private ImageLoader(int threadCount, Type type)
{
init(threadCount, type);
}
private void init(int threadCount, Type type)
{
// loop thread
mPoolThread = new Thread()
{
@Override
public void run()
{
try
{
// 请求一个信号量
mSemaphore.acquire();
} catch (InterruptedException e)
{
}
Looper.prepare();
mPoolThreadHander = new Handler()
{
@Override
public void handleMessage(Message msg)
{
mThreadPool.execute(getTask());
try
{
mPoolSemaphore.acquire();
} catch (InterruptedException e)
{
}
}
};
// 释放一个信号量
mSemaphore.release();
Looper.loop();
}
};
mPoolThread.start();
// 获取应用程序最大可用内存
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 8;
mLruCache = new LruCache<String, Bitmap>(cacheSize)
{
@Override
protected int sizeOf(String key, Bitmap value)
{
return value.getRowBytes() * value.getHeight();
};
};
mThreadPool = Executors.newFixedThreadPool(threadCount);
mPoolSemaphore = new Semaphore(threadCount);
mTasks = new LinkedList<Runnable>();
mType = type == null ? Type.LIFO : type;
}
/**
* 添加一个任务
*
* @param runnable
*/
private synchronized void addTask(Runnable runnable)
{
try
{
// 请求信号量,防止mPoolThreadHander为null
if (mPoolThreadHander == null)
mSemaphore.acquire();
} catch (InterruptedException e)
{
}
mTasks.add(runnable);
mPoolThreadHander.sendEmptyMessage(0x110);
}
mImageLoader.loadImage(mDirPath + "/" + mData.get(position),holder.mImageView);
/**
* 加载图片
*
* @param path
* @param imageView
*/
public void loadImage(final String path, final ImageView imageView)
{
// set tag
imageView.setTag(path);
// UI线程
if (mHandler == null)
{
mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
ImageView imageView = holder.imageView;
Bitmap bm = holder.bitmap;
String path = holder.path;
if (imageView.getTag().toString().equals(path))
{
imageView.setImageBitmap(bm);
}
}
};
}
Bitmap bm = getBitmapFromLruCache(path);
if (bm != null)
{
ImgBeanHolder holder = new ImgBeanHolder();
holder.bitmap = bm;
holder.imageView = imageView;
holder.path = path;
Message message = Message.obtain();
message.obj = holder;
mHandler.sendMessage(message);
} else
{
addTask(new Runnable()
{
@Override
public void run()
{
ImageSize imageSize = getImageViewWidth(imageView);
int reqWidth = imageSize.width;
int reqHeight = imageSize.height;
Bitmap bm = decodeSampledBitmapFromResource(path, reqWidth,
reqHeight);
addBitmapToLruCache(path, bm);
ImgBeanHolder holder = new ImgBeanHolder();
holder.bitmap = getBitmapFromLruCache(path);
holder.imageView = imageView;
holder.path = path;
Message message = Message.obtain();
message.obj = holder;
// Log.e("TAG", "mHandler.sendMessage(message);");
mHandler.sendMessage(message);
mPoolSemaphore.release();
}
});
}
}
/**
* 根据ImageView获得适当的压缩的宽和高
*
* @param imageView
* @return
*/
private ImageSize getImageViewWidth(ImageView imageView)
{
ImageSize imageSize = new ImageSize();
final DisplayMetrics displayMetrics = imageView.getContext()
.getResources().getDisplayMetrics();
final LayoutParams params = imageView.getLayoutParams();
int width = params.width == LayoutParams.WRAP_CONTENT ? 0 : imageView
.getWidth(); // Get actual image width
if (width <= 0)
width = params.width; // Get layout width parameter
if (width <= 0)
width = getImageViewFieldValue(imageView, "mMaxWidth"); // Check
// maxWidth
// parameter
if (width <= 0)
width = displayMetrics.widthPixels;
int height = params.height == LayoutParams.WRAP_CONTENT ? 0 : imageView
.getHeight(); // Get actual image height
if (height <= 0)
height = params.height; // Get layout height parameter
if (height <= 0)
height = getImageViewFieldValue(imageView, "mMaxHeight"); // Check
// maxHeight
// parameter
if (height <= 0)
height = displayMetrics.heightPixels;
imageSize.width = width;
imageSize.height = height;
return imageSize;
}
/**
* 根据计算的inSampleSize,得到压缩后图片
*
* @param pathName
* @param reqWidth
* @param reqHeight
* @return
*/
private Bitmap decodeSampledBitmapFromResource(String pathName,
int reqWidth, int reqHeight)
{
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
// 调用上面定义的方法计算inSampleSize值
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);
return bitmap;
}
/**
* 添加一个任务
*
* @param runnable
*/
private synchronized void addTask(Runnable runnable)
{
try
{
// 请求信号量,防止mPoolThreadHander为null
if (mPoolThreadHander == null)
mSemaphore.acquire();
} catch (InterruptedException e)
{
}
mTasks.add(runnable);
mPoolThreadHander.sendEmptyMessage(0x110);
}
mThreadPool.execute(getTask());
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有